miniaudio.h 3.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963869648696586966869678696886969869708697186972869738697486975869768697786978869798698086981869828698386984869858698686987869888698986990869918699286993869948699586996869978699886999870008700187002870038700487005870068700787008870098701087011870128701387014870158701687017870188701987020870218702287023870248702587026870278702887029870308703187032870338703487035870368703787038870398704087041870428704387044870458704687047870488704987050870518705287053870548705587056870578705887059870608706187062870638706487065870668706787068870698707087071870728707387074870758707687077870788707987080870818708287083870848708587086870878708887089870908709187092870938709487095870968709787098870998710087101871028710387104871058710687107871088710987110871118711287113871148711587116871178711887119871208712187122871238712487125871268712787128871298713087131871328713387134871358713687137871388713987140871418714287143871448714587146871478714887149871508715187152871538715487155871568715787158871598716087161871628716387164871658716687167871688716987170871718717287173871748717587176871778717887179871808718187182871838718487185871868718787188871898719087191871928719387194871958719687197871988719987200872018720287203872048720587206872078720887209872108721187212872138721487215872168721787218872198722087221872228722387224872258722687227872288722987230872318723287233872348723587236872378723887239872408724187242872438724487245872468724787248872498725087251872528725387254872558725687257872588725987260872618726287263872648726587266872678726887269872708727187272872738727487275872768727787278872798728087281872828728387284872858728687287872888728987290872918729287293872948729587296872978729887299873008730187302873038730487305873068730787308873098731087311873128731387314873158731687317873188731987320873218732287323873248732587326873278732887329873308733187332873338733487335873368733787338873398734087341873428734387344873458734687347873488734987350873518735287353873548735587356873578735887359873608736187362873638736487365873668736787368873698737087371873728737387374873758737687377873788737987380873818738287383873848738587386873878738887389873908739187392873938739487395873968739787398873998740087401874028740387404874058740687407874088740987410874118741287413874148741587416874178741887419874208742187422874238742487425874268742787428874298743087431874328743387434874358743687437874388743987440874418744287443874448744587446874478744887449874508745187452874538745487455874568745787458874598746087461874628746387464874658746687467874688746987470874718747287473874748747587476874778747887479874808748187482874838748487485874868748787488874898749087491874928749387494874958749687497874988749987500875018750287503875048750587506875078750887509875108751187512875138751487515875168751787518875198752087521875228752387524875258752687527875288752987530875318753287533875348753587536875378753887539875408754187542875438754487545875468754787548875498755087551875528755387554875558755687557875588755987560875618756287563875648756587566875678756887569875708757187572875738757487575875768757787578875798758087581875828758387584875858758687587875888758987590875918759287593875948759587596875978759887599876008760187602876038760487605876068760787608876098761087611876128761387614876158761687617876188761987620876218762287623876248762587626876278762887629876308763187632876338763487635876368763787638876398764087641876428764387644876458764687647876488764987650876518765287653876548765587656876578765887659876608766187662876638766487665876668766787668876698767087671876728767387674876758767687677876788767987680876818768287683876848768587686876878768887689876908769187692876938769487695876968769787698876998770087701877028770387704877058770687707877088770987710877118771287713877148771587716877178771887719877208772187722877238772487725877268772787728877298773087731877328773387734877358773687737877388773987740877418774287743877448774587746877478774887749877508775187752877538775487755877568775787758877598776087761877628776387764877658776687767877688776987770877718777287773877748777587776877778777887779877808778187782877838778487785877868778787788877898779087791877928779387794877958779687797877988779987800878018780287803878048780587806878078780887809878108781187812878138781487815878168781787818878198782087821878228782387824878258782687827878288782987830878318783287833878348783587836878378783887839878408784187842878438784487845878468784787848878498785087851878528785387854878558785687857878588785987860878618786287863878648786587866878678786887869878708787187872878738787487875878768787787878878798788087881878828788387884878858788687887878888788987890878918789287893878948789587896878978789887899879008790187902879038790487905879068790787908879098791087911879128791387914879158791687917879188791987920879218792287923879248792587926879278792887929879308793187932879338793487935879368793787938879398794087941879428794387944879458794687947879488794987950879518795287953879548795587956879578795887959879608796187962879638796487965879668796787968879698797087971879728797387974879758797687977879788797987980879818798287983879848798587986879878798887989879908799187992879938799487995879968799787998879998800088001880028800388004880058800688007880088800988010880118801288013880148801588016880178801888019880208802188022880238802488025880268802788028880298803088031880328803388034880358803688037880388803988040880418804288043880448804588046880478804888049880508805188052880538805488055880568805788058880598806088061880628806388064880658806688067880688806988070880718807288073880748807588076880778807888079880808808188082880838808488085880868808788088880898809088091880928809388094880958809688097880988809988100881018810288103881048810588106881078810888109881108811188112881138811488115881168811788118881198812088121881228812388124881258812688127881288812988130881318813288133881348813588136881378813888139881408814188142881438814488145881468814788148881498815088151881528815388154881558815688157881588815988160881618816288163881648816588166881678816888169881708817188172881738817488175881768817788178881798818088181881828818388184881858818688187881888818988190881918819288193881948819588196881978819888199882008820188202882038820488205882068820788208882098821088211882128821388214882158821688217882188821988220882218822288223882248822588226882278822888229882308823188232882338823488235882368823788238882398824088241882428824388244882458824688247882488824988250882518825288253882548825588256882578825888259882608826188262882638826488265882668826788268882698827088271882728827388274882758827688277882788827988280882818828288283882848828588286882878828888289882908829188292882938829488295882968829788298882998830088301883028830388304883058830688307883088830988310883118831288313883148831588316883178831888319883208832188322883238832488325883268832788328883298833088331883328833388334883358833688337883388833988340883418834288343883448834588346883478834888349883508835188352883538835488355883568835788358883598836088361883628836388364883658836688367883688836988370883718837288373883748837588376883778837888379883808838188382883838838488385883868838788388883898839088391883928839388394883958839688397883988839988400884018840288403884048840588406884078840888409884108841188412884138841488415884168841788418884198842088421884228842388424884258842688427884288842988430884318843288433884348843588436884378843888439884408844188442884438844488445884468844788448884498845088451884528845388454884558845688457884588845988460884618846288463884648846588466884678846888469884708847188472884738847488475884768847788478884798848088481884828848388484884858848688487884888848988490884918849288493884948849588496884978849888499885008850188502885038850488505885068850788508885098851088511885128851388514885158851688517885188851988520885218852288523885248852588526885278852888529885308853188532885338853488535885368853788538885398854088541885428854388544885458854688547885488854988550885518855288553885548855588556885578855888559885608856188562885638856488565885668856788568885698857088571885728857388574885758857688577885788857988580885818858288583885848858588586885878858888589885908859188592885938859488595885968859788598885998860088601886028860388604886058860688607886088860988610886118861288613886148861588616886178861888619886208862188622886238862488625886268862788628886298863088631886328863388634886358863688637886388863988640886418864288643886448864588646886478864888649886508865188652886538865488655886568865788658886598866088661886628866388664886658866688667886688866988670886718867288673886748867588676886778867888679886808868188682886838868488685886868868788688886898869088691886928869388694886958869688697886988869988700887018870288703887048870588706887078870888709887108871188712887138871488715887168871788718887198872088721887228872388724887258872688727887288872988730887318873288733887348873588736887378873888739887408874188742887438874488745887468874788748887498875088751887528875388754887558875688757887588875988760887618876288763887648876588766887678876888769887708877188772887738877488775887768877788778887798878088781887828878388784887858878688787887888878988790887918879288793887948879588796887978879888799888008880188802888038880488805888068880788808888098881088811888128881388814888158881688817888188881988820888218882288823888248882588826888278882888829888308883188832888338883488835888368883788838888398884088841888428884388844888458884688847888488884988850888518885288853888548885588856888578885888859888608886188862888638886488865888668886788868888698887088871888728887388874888758887688877888788887988880888818888288883888848888588886888878888888889888908889188892888938889488895888968889788898888998890088901889028890388904889058890688907889088890988910889118891288913889148891588916889178891888919889208892188922889238892488925889268892788928889298893088931889328893388934889358893688937889388893988940889418894288943889448894588946889478894888949889508895188952889538895488955889568895788958889598896088961889628896388964889658896688967889688896988970889718897288973889748897588976889778897888979889808898188982889838898488985889868898788988889898899088991889928899388994889958899688997889988899989000890018900289003890048900589006890078900889009890108901189012890138901489015890168901789018890198902089021890228902389024890258902689027890288902989030890318903289033890348903589036890378903889039890408904189042890438904489045890468904789048890498905089051890528905389054890558905689057890588905989060890618906289063890648906589066890678906889069890708907189072890738907489075890768907789078890798908089081890828908389084890858908689087890888908989090890918909289093890948909589096890978909889099891008910189102891038910489105891068910789108891098911089111891128911389114891158911689117891188911989120891218912289123891248912589126891278912889129891308913189132891338913489135891368913789138891398914089141891428914389144891458914689147891488914989150891518915289153891548915589156891578915889159891608916189162891638916489165891668916789168891698917089171891728917389174891758917689177891788917989180891818918289183891848918589186891878918889189891908919189192891938919489195891968919789198891998920089201892028920389204892058920689207892088920989210892118921289213892148921589216892178921889219892208922189222892238922489225892268922789228892298923089231892328923389234892358923689237892388923989240892418924289243892448924589246892478924889249892508925189252892538925489255892568925789258892598926089261892628926389264892658926689267892688926989270892718927289273892748927589276892778927889279892808928189282892838928489285892868928789288892898929089291892928929389294892958929689297892988929989300893018930289303893048930589306893078930889309893108931189312893138931489315893168931789318893198932089321893228932389324893258932689327893288932989330893318933289333893348933589336893378933889339893408934189342893438934489345893468934789348893498935089351893528935389354893558935689357893588935989360893618936289363893648936589366893678936889369893708937189372893738937489375893768937789378893798938089381893828938389384893858938689387893888938989390893918939289393893948939589396893978939889399894008940189402894038940489405894068940789408894098941089411894128941389414894158941689417894188941989420894218942289423894248942589426894278942889429894308943189432894338943489435894368943789438894398944089441894428944389444894458944689447894488944989450894518945289453894548945589456894578945889459894608946189462894638946489465894668946789468894698947089471894728947389474894758947689477894788947989480894818948289483894848948589486894878948889489894908949189492894938949489495894968949789498894998950089501895028950389504895058950689507895088950989510895118951289513895148951589516895178951889519895208952189522895238952489525895268952789528895298953089531895328953389534895358953689537895388953989540895418954289543895448954589546895478954889549895508955189552895538955489555895568955789558895598956089561895628956389564895658956689567895688956989570895718957289573895748957589576895778957889579895808958189582895838958489585895868958789588895898959089591895928959389594895958959689597895988959989600896018960289603896048960589606896078960889609896108961189612896138961489615896168961789618896198962089621896228962389624896258962689627896288962989630896318963289633896348963589636896378963889639896408964189642896438964489645896468964789648896498965089651896528965389654896558965689657896588965989660896618966289663896648966589666896678966889669896708967189672896738967489675896768967789678896798968089681896828968389684896858968689687896888968989690896918969289693896948969589696896978969889699897008970189702897038970489705897068970789708897098971089711897128971389714897158971689717897188971989720897218972289723897248972589726897278972889729897308973189732897338973489735897368973789738897398974089741897428974389744897458974689747897488974989750897518975289753897548975589756897578975889759897608976189762897638976489765897668976789768897698977089771897728977389774897758977689777897788977989780897818978289783897848978589786897878978889789897908979189792897938979489795897968979789798897998980089801898028980389804898058980689807898088980989810898118981289813898148981589816898178981889819898208982189822898238982489825898268982789828898298983089831898328983389834898358983689837898388983989840898418984289843898448984589846898478984889849898508985189852898538985489855898568985789858898598986089861898628986389864898658986689867898688986989870898718987289873898748987589876898778987889879898808988189882898838988489885898868988789888898898989089891898928989389894898958989689897898988989989900899018990289903899048990589906899078990889909899108991189912899138991489915899168991789918899198992089921899228992389924899258992689927899288992989930899318993289933899348993589936899378993889939899408994189942899438994489945899468994789948899498995089951899528995389954899558995689957899588995989960899618996289963899648996589966899678996889969899708997189972899738997489975899768997789978899798998089981899828998389984899858998689987899888998989990899918999289993899948999589996899978999889999900009000190002900039000490005900069000790008900099001090011900129001390014900159001690017900189001990020900219002290023900249002590026900279002890029900309003190032900339003490035900369003790038900399004090041900429004390044900459004690047900489004990050900519005290053900549005590056900579005890059900609006190062900639006490065900669006790068900699007090071900729007390074900759007690077900789007990080900819008290083900849008590086900879008890089900909009190092900939009490095900969009790098900999010090101901029010390104901059010690107901089010990110901119011290113901149011590116901179011890119901209012190122901239012490125901269012790128901299013090131901329013390134901359013690137901389013990140901419014290143901449014590146901479014890149901509015190152901539015490155901569015790158901599016090161901629016390164901659016690167901689016990170901719017290173901749017590176901779017890179901809018190182901839018490185901869018790188901899019090191901929019390194901959019690197901989019990200902019020290203902049020590206902079020890209902109021190212902139021490215902169021790218902199022090221902229022390224902259022690227902289022990230902319023290233902349023590236902379023890239902409024190242902439024490245902469024790248902499025090251902529025390254902559025690257902589025990260902619026290263902649026590266902679026890269902709027190272902739027490275902769027790278902799028090281902829028390284902859028690287902889028990290902919029290293902949029590296902979029890299903009030190302903039030490305903069030790308903099031090311903129031390314903159031690317903189031990320903219032290323903249032590326903279032890329903309033190332903339033490335903369033790338903399034090341903429034390344903459034690347903489034990350903519035290353903549035590356903579035890359903609036190362903639036490365903669036790368903699037090371903729037390374903759037690377903789037990380903819038290383903849038590386903879038890389903909039190392903939039490395903969039790398903999040090401904029040390404904059040690407904089040990410904119041290413904149041590416904179041890419904209042190422904239042490425904269042790428904299043090431904329043390434904359043690437904389043990440904419044290443904449044590446904479044890449904509045190452904539045490455904569045790458904599046090461904629046390464904659046690467904689046990470904719047290473904749047590476904779047890479904809048190482904839048490485904869048790488904899049090491904929049390494904959049690497904989049990500905019050290503905049050590506905079050890509905109051190512905139051490515905169051790518905199052090521905229052390524905259052690527905289052990530905319053290533905349053590536905379053890539905409054190542905439054490545905469054790548905499055090551905529055390554905559055690557905589055990560905619056290563905649056590566905679056890569905709057190572905739057490575905769057790578905799058090581905829058390584905859058690587905889058990590905919059290593905949059590596905979059890599906009060190602906039060490605906069060790608906099061090611906129061390614906159061690617906189061990620906219062290623906249062590626906279062890629906309063190632906339063490635906369063790638906399064090641906429064390644906459064690647906489064990650906519065290653906549065590656906579065890659906609066190662906639066490665906669066790668906699067090671906729067390674906759067690677906789067990680906819068290683906849068590686906879068890689906909069190692906939069490695906969069790698906999070090701907029070390704907059070690707907089070990710907119071290713907149071590716907179071890719907209072190722907239072490725907269072790728907299073090731907329073390734907359073690737907389073990740907419074290743907449074590746907479074890749907509075190752907539075490755907569075790758907599076090761907629076390764907659076690767907689076990770907719077290773907749077590776907779077890779907809078190782907839078490785907869078790788907899079090791907929079390794907959079690797907989079990800908019080290803908049080590806908079080890809908109081190812908139081490815908169081790818908199082090821908229082390824908259082690827908289082990830908319083290833908349083590836908379083890839908409084190842908439084490845908469084790848908499085090851908529085390854908559085690857908589085990860908619086290863908649086590866908679086890869908709087190872908739087490875908769087790878908799088090881908829088390884908859088690887908889088990890908919089290893908949089590896908979089890899909009090190902909039090490905909069090790908909099091090911909129091390914909159091690917909189091990920909219092290923909249092590926909279092890929909309093190932909339093490935909369093790938909399094090941909429094390944909459094690947909489094990950909519095290953909549095590956909579095890959909609096190962909639096490965909669096790968909699097090971909729097390974909759097690977909789097990980909819098290983909849098590986909879098890989909909099190992909939099490995909969099790998909999100091001910029100391004910059100691007910089100991010910119101291013910149101591016910179101891019910209102191022910239102491025910269102791028910299103091031910329103391034910359103691037910389103991040910419104291043910449104591046910479104891049910509105191052910539105491055910569105791058910599106091061910629106391064910659106691067910689106991070910719107291073910749107591076910779107891079910809108191082910839108491085910869108791088910899109091091910929109391094910959109691097910989109991100911019110291103911049110591106911079110891109911109111191112911139111491115911169111791118911199112091121911229112391124911259112691127911289112991130911319113291133911349113591136911379113891139911409114191142911439114491145911469114791148911499115091151911529115391154911559115691157911589115991160911619116291163911649116591166911679116891169911709117191172911739117491175911769117791178911799118091181911829118391184911859118691187911889118991190911919119291193911949119591196911979119891199912009120191202912039120491205912069120791208912099121091211912129121391214912159121691217912189121991220912219122291223912249122591226912279122891229912309123191232912339123491235912369123791238912399124091241912429124391244912459124691247912489124991250912519125291253912549125591256912579125891259912609126191262912639126491265912669126791268912699127091271912729127391274912759127691277912789127991280912819128291283912849128591286912879128891289
  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.11 - 2022-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); // This will stop the device so no need to do that manually.
  72. return 0;
  73. }
  74. ```
  75. In the example above, `data_callback()` is where audio data is written and read from the device.
  76. The idea is in playback mode you cause sound to be emitted from the speakers by writing audio data
  77. to the output buffer (`pOutput` in the example). In capture mode you read data from the input
  78. buffer (`pInput`) to extract sound captured by the microphone. The `frameCount` parameter tells you
  79. how many frames can be written to the output buffer and read from the input buffer. A "frame" is
  80. one sample for each channel. For example, in a stereo stream (2 channels), one frame is 2
  81. samples: one for the left, one for the right. The channel count is defined by the device config.
  82. The size in bytes of an individual sample is defined by the sample format which is also specified
  83. in the device config. Multi-channel audio data is always interleaved, which means the samples for
  84. each frame are stored next to each other in memory. For example, in a stereo stream the first pair
  85. of samples will be the left and right samples for the first frame, the second pair of samples will
  86. be the left and right samples for the second frame, etc.
  87. The configuration of the device is defined by the `ma_device_config` structure. The config object
  88. is always initialized with `ma_device_config_init()`. It's important to always initialize the
  89. config with this function as it initializes it with logical defaults and ensures your program
  90. doesn't break when new members are added to the `ma_device_config` structure. The example above
  91. uses a fairly simple and standard device configuration. The call to `ma_device_config_init()` takes
  92. a single parameter, which is whether or not the device is a playback, capture, duplex or loopback
  93. device (loopback devices are not supported on all backends). The `config.playback.format` member
  94. sets the sample format which can be one of the following (all formats are native-endian):
  95. +---------------+----------------------------------------+---------------------------+
  96. | Symbol | Description | Range |
  97. +---------------+----------------------------------------+---------------------------+
  98. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  99. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  100. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  101. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  102. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  103. +---------------+----------------------------------------+---------------------------+
  104. The `config.playback.channels` member sets the number of channels to use with the device. The
  105. channel count cannot exceed MA_MAX_CHANNELS. The `config.sampleRate` member sets the sample rate
  106. (which must be the same for both playback and capture in full-duplex configurations). This is
  107. usually set to 44100 or 48000, but can be set to anything. It's recommended to keep this between
  108. 8000 and 384000, however.
  109. Note that leaving the format, channel count and/or sample rate at their default values will result
  110. in the internal device's native configuration being used which is useful if you want to avoid the
  111. overhead of miniaudio's automatic data conversion.
  112. In addition to the sample format, channel count and sample rate, the data callback and user data
  113. pointer are also set via the config. The user data pointer is not passed into the callback as a
  114. parameter, but is instead set to the `pUserData` member of `ma_device` which you can access
  115. directly since all miniaudio structures are transparent.
  116. Initializing the device is done with `ma_device_init()`. This will return a result code telling you
  117. what went wrong, if anything. On success it will return `MA_SUCCESS`. After initialization is
  118. complete the device will be in a stopped state. To start it, use `ma_device_start()`.
  119. Uninitializing the device will stop it, which is what the example above does, but you can also stop
  120. the device with `ma_device_stop()`. To resume the device simply call `ma_device_start()` again.
  121. Note that it's important to never stop or start the device from inside the callback. This will
  122. result in a deadlock. Instead you set a variable or signal an event indicating that the device
  123. needs to stop and handle it in a different thread. The following APIs must never be called inside
  124. the callback:
  125. ```c
  126. ma_device_init()
  127. ma_device_init_ex()
  128. ma_device_uninit()
  129. ma_device_start()
  130. ma_device_stop()
  131. ```
  132. You must never try uninitializing and reinitializing a device inside the callback. You must also
  133. never try to stop and start it from inside the callback. There are a few other things you shouldn't
  134. do in the callback depending on your requirements, however this isn't so much a thread-safety
  135. thing, but rather a real-time processing thing which is beyond the scope of this introduction.
  136. The example above demonstrates the initialization of a playback device, but it works exactly the
  137. same for capture. All you need to do is change the device type from `ma_device_type_playback` to
  138. `ma_device_type_capture` when setting up the config, like so:
  139. ```c
  140. ma_device_config config = ma_device_config_init(ma_device_type_capture);
  141. config.capture.format = MY_FORMAT;
  142. config.capture.channels = MY_CHANNEL_COUNT;
  143. ```
  144. In the data callback you just read from the input buffer (`pInput` in the example above) and leave
  145. the output buffer alone (it will be set to NULL when the device type is set to
  146. `ma_device_type_capture`).
  147. These are the available device types and how you should handle the buffers in the callback:
  148. +-------------------------+--------------------------------------------------------+
  149. | Device Type | Callback Behavior |
  150. +-------------------------+--------------------------------------------------------+
  151. | ma_device_type_playback | Write to output buffer, leave input buffer untouched. |
  152. | ma_device_type_capture | Read from input buffer, leave output buffer untouched. |
  153. | ma_device_type_duplex | Read from input buffer, write to output buffer. |
  154. | ma_device_type_loopback | Read from input buffer, leave output buffer untouched. |
  155. +-------------------------+--------------------------------------------------------+
  156. You will notice in the example above that the sample format and channel count is specified
  157. separately for playback and capture. This is to support different data formats between the playback
  158. and capture devices in a full-duplex system. An example may be that you want to capture audio data
  159. as a monaural stream (one channel), but output sound to a stereo speaker system. Note that if you
  160. use different formats between playback and capture in a full-duplex configuration you will need to
  161. convert the data yourself. There are functions available to help you do this which will be
  162. explained later.
  163. The example above did not specify a physical device to connect to which means it will use the
  164. operating system's default device. If you have multiple physical devices connected and you want to
  165. use a specific one you will need to specify the device ID in the configuration, like so:
  166. ```c
  167. config.playback.pDeviceID = pMyPlaybackDeviceID; // Only if requesting a playback or duplex device.
  168. config.capture.pDeviceID = pMyCaptureDeviceID; // Only if requesting a capture, duplex or loopback device.
  169. ```
  170. To retrieve the device ID you will need to perform device enumeration, however this requires the
  171. use of a new concept called the "context". Conceptually speaking the context sits above the device.
  172. There is one context to many devices. The purpose of the context is to represent the backend at a
  173. more global level and to perform operations outside the scope of an individual device. Mainly it is
  174. used for performing run-time linking against backend libraries, initializing backends and
  175. enumerating devices. The example below shows how to enumerate devices.
  176. ```c
  177. ma_context context;
  178. if (ma_context_init(NULL, 0, NULL, &context) != MA_SUCCESS) {
  179. // Error.
  180. }
  181. ma_device_info* pPlaybackInfos;
  182. ma_uint32 playbackCount;
  183. ma_device_info* pCaptureInfos;
  184. ma_uint32 captureCount;
  185. if (ma_context_get_devices(&context, &pPlaybackInfos, &playbackCount, &pCaptureInfos, &captureCount) != MA_SUCCESS) {
  186. // Error.
  187. }
  188. // Loop over each device info and do something with it. Here we just print the name with their index. You may want
  189. // to give the user the opportunity to choose which device they'd prefer.
  190. for (ma_uint32 iDevice = 0; iDevice < playbackCount; iDevice += 1) {
  191. printf("%d - %s\n", iDevice, pPlaybackInfos[iDevice].name);
  192. }
  193. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  194. config.playback.pDeviceID = &pPlaybackInfos[chosenPlaybackDeviceIndex].id;
  195. config.playback.format = MY_FORMAT;
  196. config.playback.channels = MY_CHANNEL_COUNT;
  197. config.sampleRate = MY_SAMPLE_RATE;
  198. config.dataCallback = data_callback;
  199. config.pUserData = pMyCustomData;
  200. ma_device device;
  201. if (ma_device_init(&context, &config, &device) != MA_SUCCESS) {
  202. // Error
  203. }
  204. ...
  205. ma_device_uninit(&device);
  206. ma_context_uninit(&context);
  207. ```
  208. The first thing we do in this example is initialize a `ma_context` object with `ma_context_init()`.
  209. The first parameter is a pointer to a list of `ma_backend` values which are used to override the
  210. default backend priorities. When this is NULL, as in this example, miniaudio's default priorities
  211. are used. The second parameter is the number of backends listed in the array pointed to by the
  212. first parameter. The third parameter is a pointer to a `ma_context_config` object which can be
  213. NULL, in which case defaults are used. The context configuration is used for setting the logging
  214. callback, custom memory allocation callbacks, user-defined data and some backend-specific
  215. configurations.
  216. Once the context has been initialized you can enumerate devices. In the example above we use the
  217. simpler `ma_context_get_devices()`, however you can also use a callback for handling devices by
  218. using `ma_context_enumerate_devices()`. When using `ma_context_get_devices()` you provide a pointer
  219. to a pointer that will, upon output, be set to a pointer to a buffer containing a list of
  220. `ma_device_info` structures. You also provide a pointer to an unsigned integer that will receive
  221. the number of items in the returned buffer. Do not free the returned buffers as their memory is
  222. managed internally by miniaudio.
  223. The `ma_device_info` structure contains an `id` member which is the ID you pass to the device
  224. config. It also contains the name of the device which is useful for presenting a list of devices
  225. to the user via the UI.
  226. When creating your own context you will want to pass it to `ma_device_init()` when initializing the
  227. device. Passing in NULL, like we do in the first example, will result in miniaudio creating the
  228. context for you, which you don't want to do since you've already created a context. Note that
  229. internally the context is only tracked by it's pointer which means you must not change the location
  230. of the `ma_context` object. If this is an issue, consider using `malloc()` to allocate memory for
  231. the context.
  232. 1.2. High Level API
  233. -------------------
  234. The high level API consists of three main parts:
  235. * Resource management for loading and streaming sounds.
  236. * A node graph for advanced mixing and effect processing.
  237. * A high level "engine" that wraps around the resource manager and node graph.
  238. The resource manager (`ma_resource_manager`) is used for loading sounds. It supports loading sounds
  239. fully into memory and also streaming. It will also deal with reference counting for you which
  240. avoids the same sound being loaded multiple times.
  241. The node graph is used for mixing and effect processing. The idea is that you connect a number of
  242. nodes into the graph by connecting each node's outputs to another node's inputs. Each node can
  243. implement it's own effect. By chaining nodes together, advanced mixing and effect processing can
  244. be achieved.
  245. The engine encapsulates both the resource manager and the node graph to create a simple, easy to
  246. use high level API. The resource manager and node graph APIs are covered in more later sections of
  247. this manual.
  248. The code below shows how you can initialize an engine using it's default configuration.
  249. ```c
  250. ma_result result;
  251. ma_engine engine;
  252. result = ma_engine_init(NULL, &engine);
  253. if (result != MA_SUCCESS) {
  254. return result; // Failed to initialize the engine.
  255. }
  256. ```
  257. This creates an engine instance which will initialize a device internally which you can access with
  258. `ma_engine_get_device()`. It will also initialize a resource manager for you which can be accessed
  259. with `ma_engine_get_resource_manager()`. The engine itself is a node graph (`ma_node_graph`) which
  260. means you can pass a pointer to the engine object into any of the `ma_node_graph` APIs (with a
  261. cast). Alternatively, you can use `ma_engine_get_node_graph()` instead of a cast.
  262. Note that all objects in miniaudio, including the `ma_engine` object in the example above, are
  263. transparent structures. There are no handles to opaque structures in miniaudio which means you need
  264. to be mindful of how you declare them. In the example above we are declaring it on the stack, but
  265. this will result in the struct being invalidated once the function encapsulating it returns. If
  266. allocating the engine on the heap is more appropriate, you can easily do so with a standard call
  267. to `malloc()` or whatever heap allocation routine you like:
  268. ```c
  269. ma_engine* pEngine = malloc(sizeof(*pEngine));
  270. ```
  271. The `ma_engine` API uses the same config/init pattern used all throughout miniaudio. To configure
  272. an engine, you can fill out a `ma_engine_config` object and pass it into the first parameter of
  273. `ma_engine_init()`:
  274. ```c
  275. ma_result result;
  276. ma_engine engine;
  277. ma_engine_config engineConfig;
  278. engineConfig = ma_engine_config_init();
  279. engineConfig.pResourceManager = &myCustomResourceManager; // <-- Initialized as some earlier stage.
  280. result = ma_engine_init(&engineConfig, &engine);
  281. if (result != MA_SUCCESS) {
  282. return result;
  283. }
  284. ```
  285. This creates an engine instance using a custom config. In this particular example it's showing how
  286. you can specify a custom resource manager rather than having the engine initialize one internally.
  287. This is particularly useful if you want to have multiple engine's share the same resource manager.
  288. The engine must be uninitialized with `ma_engine_uninit()` when it's no longer needed.
  289. By default the engine will be started, but nothing will be playing because no sounds have been
  290. initialized. The easiest but least flexible way of playing a sound is like so:
  291. ```c
  292. ma_engine_play_sound(&engine, "my_sound.wav", NULL);
  293. ```
  294. This plays what miniaudio calls an "inline" sound. It plays the sound once, and then puts the
  295. internal sound up for recycling. The last parameter is used to specify which sound group the sound
  296. should be associated with which will be explained later. This particular way of playing a sound is
  297. simple, but lacks flexibility and features. A more flexible way of playing a sound is to first
  298. initialize a sound:
  299. ```c
  300. ma_result result;
  301. ma_sound sound;
  302. result = ma_sound_init_from_file(&engine, "my_sound.wav", 0, NULL, NULL, &sound);
  303. if (result != MA_SUCCESS) {
  304. return result;
  305. }
  306. ma_sound_start(&sound);
  307. ```
  308. This returns a `ma_sound` object which represents a single instance of the specified sound file. If
  309. you want to play the same file multiple times simultaneously, you need to create one sound for each
  310. instance.
  311. Sounds should be uninitialized with `ma_sound_uninit()`.
  312. Sounds are not started by default. Start a sound with `ma_sound_start()` and stop it with
  313. `ma_sound_stop()`. When a sound is stopped, it is not rewound to the start. Use
  314. `ma_sound_seek_to_pcm_frame(&sound, 0)` to seek back to the start of a sound. By default, starting
  315. and stopping sounds happens immediately, but sometimes it might be convenient to schedule the sound
  316. the be started and/or stopped at a specific time. This can be done with the following functions:
  317. ```c
  318. ma_sound_set_start_time_in_pcm_frames()
  319. ma_sound_set_start_time_in_milliseconds()
  320. ma_sound_set_stop_time_in_pcm_frames()
  321. ma_sound_set_stop_time_in_milliseconds()
  322. ```
  323. The start/stop time needs to be specified based on the absolute timer which is controlled by the
  324. engine. The current global time time in PCM frames can be retrieved with `ma_engine_get_time()`.
  325. The engine's global time can be changed with `ma_engine_set_time()` for synchronization purposes if
  326. required. Note that scheduling a start time still requires an explicit call to `ma_sound_start()`
  327. before anything will play:
  328. ```c
  329. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time(&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. 2.1. Windows
  372. ------------
  373. The Windows build should compile cleanly on all popular compilers without the need to configure any
  374. include paths nor link to any libraries.
  375. The UWP build may require linking to mmdevapi.lib if you get errors about an unresolved external
  376. symbol for `ActivateAudioInterfaceAsync()`.
  377. 2.2. macOS and iOS
  378. ------------------
  379. The macOS build should compile cleanly without the need to download any dependencies nor link to
  380. any libraries or frameworks. The iOS build needs to be compiled as Objective-C and will need to
  381. link the relevant frameworks but should compile cleanly out of the box with Xcode. Compiling
  382. through the command line requires linking to `-lpthread` and `-lm`.
  383. Due to the way miniaudio links to frameworks at runtime, your application may not pass Apple's
  384. notarization process. To fix this there are two options. The first is to use the
  385. `MA_NO_RUNTIME_LINKING` option, like so:
  386. ```c
  387. #ifdef __APPLE__
  388. #define MA_NO_RUNTIME_LINKING
  389. #endif
  390. #define MINIAUDIO_IMPLEMENTATION
  391. #include "miniaudio.h"
  392. ```
  393. This will require linking with `-framework CoreFoundation -framework CoreAudio -framework AudioUnit`.
  394. Alternatively, if you would rather keep using runtime linking you can add the following to your
  395. entitlements.xcent file:
  396. ```
  397. <key>com.apple.security.cs.allow-dyld-environment-variables</key>
  398. <true/>
  399. <key>com.apple.security.cs.allow-unsigned-executable-memory</key>
  400. <true/>
  401. ```
  402. See this discussion for more info: https://github.com/mackron/miniaudio/issues/203.
  403. 2.3. Linux
  404. ----------
  405. The Linux build only requires linking to `-ldl`, `-lpthread` and `-lm`. You do not need any
  406. development packages. You may need to link with `-latomic` if you're compiling for 32-bit ARM.
  407. 2.4. BSD
  408. --------
  409. The BSD build only requires linking to `-lpthread` and `-lm`. NetBSD uses audio(4), OpenBSD uses
  410. sndio and FreeBSD uses OSS. You may need to link with `-latomic` if you're compiling for 32-bit
  411. ARM.
  412. 2.5. Android
  413. ------------
  414. AAudio is the highest priority backend on Android. This should work out of the box without needing
  415. any kind of compiler configuration. Support for AAudio starts with Android 8 which means older
  416. versions will fall back to OpenSL|ES which requires API level 16+.
  417. There have been reports that the OpenSL|ES backend fails to initialize on some Android based
  418. devices due to `dlopen()` failing to open "libOpenSLES.so". If this happens on your platform
  419. you'll need to disable run-time linking with `MA_NO_RUNTIME_LINKING` and link with -lOpenSLES.
  420. 2.6. Emscripten
  421. ---------------
  422. The Emscripten build emits Web Audio JavaScript directly and should compile cleanly out of the box.
  423. You cannot use `-std=c*` compiler flags, nor `-ansi`.
  424. 2.7. Build Options
  425. ------------------
  426. `#define` these options before including miniaudio.h.
  427. +----------------------------------+--------------------------------------------------------------------+
  428. | Option | Description |
  429. +----------------------------------+--------------------------------------------------------------------+
  430. | MA_NO_WASAPI | Disables the WASAPI backend. |
  431. +----------------------------------+--------------------------------------------------------------------+
  432. | MA_NO_DSOUND | Disables the DirectSound backend. |
  433. +----------------------------------+--------------------------------------------------------------------+
  434. | MA_NO_WINMM | Disables the WinMM backend. |
  435. +----------------------------------+--------------------------------------------------------------------+
  436. | MA_NO_ALSA | Disables the ALSA backend. |
  437. +----------------------------------+--------------------------------------------------------------------+
  438. | MA_NO_PULSEAUDIO | Disables the PulseAudio backend. |
  439. +----------------------------------+--------------------------------------------------------------------+
  440. | MA_NO_JACK | Disables the JACK backend. |
  441. +----------------------------------+--------------------------------------------------------------------+
  442. | MA_NO_COREAUDIO | Disables the Core Audio backend. |
  443. +----------------------------------+--------------------------------------------------------------------+
  444. | MA_NO_SNDIO | Disables the sndio backend. |
  445. +----------------------------------+--------------------------------------------------------------------+
  446. | MA_NO_AUDIO4 | Disables the audio(4) backend. |
  447. +----------------------------------+--------------------------------------------------------------------+
  448. | MA_NO_OSS | Disables the OSS backend. |
  449. +----------------------------------+--------------------------------------------------------------------+
  450. | MA_NO_AAUDIO | Disables the AAudio backend. |
  451. +----------------------------------+--------------------------------------------------------------------+
  452. | MA_NO_OPENSL | Disables the OpenSL|ES backend. |
  453. +----------------------------------+--------------------------------------------------------------------+
  454. | MA_NO_WEBAUDIO | Disables the Web Audio backend. |
  455. +----------------------------------+--------------------------------------------------------------------+
  456. | MA_NO_NULL | Disables the null backend. |
  457. +----------------------------------+--------------------------------------------------------------------+
  458. | MA_ENABLE_ONLY_SPECIFIC_BACKENDS | Disables all backends by default and requires `MA_ENABLE_*` to |
  459. | | enable specific backends. |
  460. +----------------------------------+--------------------------------------------------------------------+
  461. | MA_ENABLE_WASAPI | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  462. | | enable the WASAPI backend. |
  463. +----------------------------------+--------------------------------------------------------------------+
  464. | MA_ENABLE_DSOUND | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  465. | | enable the DirectSound backend. |
  466. +----------------------------------+--------------------------------------------------------------------+
  467. | MA_ENABLE_WINMM | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  468. | | enable the WinMM backend. |
  469. +----------------------------------+--------------------------------------------------------------------+
  470. | MA_ENABLE_ALSA | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  471. | | enable the ALSA backend. |
  472. +----------------------------------+--------------------------------------------------------------------+
  473. | MA_ENABLE_PULSEAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  474. | | enable the PulseAudio backend. |
  475. +----------------------------------+--------------------------------------------------------------------+
  476. | MA_ENABLE_JACK | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  477. | | enable the JACK backend. |
  478. +----------------------------------+--------------------------------------------------------------------+
  479. | MA_ENABLE_COREAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  480. | | enable the Core Audio backend. |
  481. +----------------------------------+--------------------------------------------------------------------+
  482. | MA_ENABLE_SNDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  483. | | enable the sndio backend. |
  484. +----------------------------------+--------------------------------------------------------------------+
  485. | MA_ENABLE_AUDIO4 | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  486. | | enable the audio(4) backend. |
  487. +----------------------------------+--------------------------------------------------------------------+
  488. | MA_ENABLE_OSS | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  489. | | enable the OSS backend. |
  490. +----------------------------------+--------------------------------------------------------------------+
  491. | MA_ENABLE_AAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  492. | | enable the AAudio backend. |
  493. +----------------------------------+--------------------------------------------------------------------+
  494. | MA_ENABLE_OPENSL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  495. | | enable the OpenSL|ES backend. |
  496. +----------------------------------+--------------------------------------------------------------------+
  497. | MA_ENABLE_WEBAUDIO | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  498. | | enable the Web Audio backend. |
  499. +----------------------------------+--------------------------------------------------------------------+
  500. | MA_ENABLE_NULL | Used in conjunction with MA_ENABLE_ONLY_SPECIFIC_BACKENDS to |
  501. | | enable the null backend. |
  502. +----------------------------------+--------------------------------------------------------------------+
  503. | MA_NO_DECODING | Disables decoding APIs. |
  504. +----------------------------------+--------------------------------------------------------------------+
  505. | MA_NO_ENCODING | Disables encoding APIs. |
  506. +----------------------------------+--------------------------------------------------------------------+
  507. | MA_NO_WAV | Disables the built-in WAV decoder and encoder. |
  508. +----------------------------------+--------------------------------------------------------------------+
  509. | MA_NO_FLAC | Disables the built-in FLAC decoder. |
  510. +----------------------------------+--------------------------------------------------------------------+
  511. | MA_NO_MP3 | Disables the built-in MP3 decoder. |
  512. +----------------------------------+--------------------------------------------------------------------+
  513. | MA_NO_DEVICE_IO | Disables playback and recording. This will disable `ma_context` |
  514. | | and `ma_device` APIs. This is useful if you only want to use |
  515. | | miniaudio's data conversion and/or decoding APIs. |
  516. +----------------------------------+--------------------------------------------------------------------+
  517. | MA_NO_RESOURCE_MANAGER | Disables the resource manager. When using the engine this will |
  518. | | also disable the following functions: |
  519. | | |
  520. | | ``` |
  521. | | ma_sound_init_from_file() |
  522. | | ma_sound_init_from_file_w() |
  523. | | ma_sound_init_copy() |
  524. | | ma_engine_play_sound_ex() |
  525. | | ma_engine_play_sound() |
  526. | | ``` |
  527. | | |
  528. | | The only way to initialize a `ma_sound` object is to initialize it |
  529. | | from a data source. |
  530. +----------------------------------+--------------------------------------------------------------------+
  531. | MA_NO_NODE_GRAPH | Disables the node graph API. This will also disable the engine API |
  532. | | because it depends on the node graph. |
  533. +----------------------------------+--------------------------------------------------------------------+
  534. | MA_NO_ENGINE | Disables the engine API. |
  535. +----------------------------------+--------------------------------------------------------------------+
  536. | MA_NO_THREADING | Disables the `ma_thread`, `ma_mutex`, `ma_semaphore` and |
  537. | | `ma_event` APIs. This option is useful if you only need to use |
  538. | | miniaudio for data conversion, decoding and/or encoding. Some |
  539. | | families of APIs require threading which means the following |
  540. | | options must also be set: |
  541. | | |
  542. | | ``` |
  543. | | MA_NO_DEVICE_IO |
  544. | | ``` |
  545. +----------------------------------+--------------------------------------------------------------------+
  546. | MA_NO_GENERATION | Disables generation APIs such a `ma_waveform` and `ma_noise`. |
  547. +----------------------------------+--------------------------------------------------------------------+
  548. | MA_NO_SSE2 | Disables SSE2 optimizations. |
  549. +----------------------------------+--------------------------------------------------------------------+
  550. | MA_NO_AVX2 | Disables AVX2 optimizations. |
  551. +----------------------------------+--------------------------------------------------------------------+
  552. | MA_NO_NEON | Disables NEON optimizations. |
  553. +----------------------------------+--------------------------------------------------------------------+
  554. | MA_NO_RUNTIME_LINKING | Disables runtime linking. This is useful for passing Apple's |
  555. | | notarization process. When enabling this, you may need to avoid |
  556. | | using `-std=c89` or `-std=c99` on Linux builds or else you may end |
  557. | | up with compilation errors due to conflicts with `timespec` and |
  558. | | `timeval` data types. |
  559. | | |
  560. | | You may need to enable this if your target platform does not allow |
  561. | | runtime linking via `dlopen()`. |
  562. +----------------------------------+--------------------------------------------------------------------+
  563. | MA_DEBUG_OUTPUT | Enable `printf()` output of debug logs (`MA_LOG_LEVEL_DEBUG`). |
  564. +----------------------------------+--------------------------------------------------------------------+
  565. | MA_COINIT_VALUE | Windows only. The value to pass to internal calls to |
  566. | | `CoInitializeEx()`. Defaults to `COINIT_MULTITHREADED`. |
  567. +----------------------------------+--------------------------------------------------------------------+
  568. | MA_API | Controls how public APIs should be decorated. Default is `extern`. |
  569. +----------------------------------+--------------------------------------------------------------------+
  570. 3. Definitions
  571. ==============
  572. This section defines common terms used throughout miniaudio. Unfortunately there is often ambiguity
  573. in the use of terms throughout the audio space, so this section is intended to clarify how miniaudio
  574. uses each term.
  575. 3.1. Sample
  576. -----------
  577. A sample is a single unit of audio data. If the sample format is f32, then one sample is one 32-bit
  578. floating point number.
  579. 3.2. Frame / PCM Frame
  580. ----------------------
  581. A frame is a group of samples equal to the number of channels. For a stereo stream a frame is 2
  582. samples, a mono frame is 1 sample, a 5.1 surround sound frame is 6 samples, etc. The terms "frame"
  583. and "PCM frame" are the same thing in miniaudio. Note that this is different to a compressed frame.
  584. If ever miniaudio needs to refer to a compressed frame, such as a FLAC frame, it will always
  585. clarify what it's referring to with something like "FLAC frame".
  586. 3.3. Channel
  587. ------------
  588. A stream of monaural audio that is emitted from an individual speaker in a speaker system, or
  589. received from an individual microphone in a microphone system. A stereo stream has two channels (a
  590. left channel, and a right channel), a 5.1 surround sound system has 6 channels, etc. Some audio
  591. systems refer to a channel as a complex audio stream that's mixed with other channels to produce
  592. the final mix - this is completely different to miniaudio's use of the term "channel" and should
  593. not be confused.
  594. 3.4. Sample Rate
  595. ----------------
  596. The sample rate in miniaudio is always expressed in Hz, such as 44100, 48000, etc. It's the number
  597. of PCM frames that are processed per second.
  598. 3.5. Formats
  599. ------------
  600. Throughout miniaudio you will see references to different sample formats:
  601. +---------------+----------------------------------------+---------------------------+
  602. | Symbol | Description | Range |
  603. +---------------+----------------------------------------+---------------------------+
  604. | ma_format_f32 | 32-bit floating point | [-1, 1] |
  605. | ma_format_s16 | 16-bit signed integer | [-32768, 32767] |
  606. | ma_format_s24 | 24-bit signed integer (tightly packed) | [-8388608, 8388607] |
  607. | ma_format_s32 | 32-bit signed integer | [-2147483648, 2147483647] |
  608. | ma_format_u8 | 8-bit unsigned integer | [0, 255] |
  609. +---------------+----------------------------------------+---------------------------+
  610. All formats are native-endian.
  611. 4. Data Sources
  612. ===============
  613. The data source abstraction in miniaudio is used for retrieving audio data from some source. A few
  614. examples include `ma_decoder`, `ma_noise` and `ma_waveform`. You will need to be familiar with data
  615. sources in order to make sense of some of the higher level concepts in miniaudio.
  616. The `ma_data_source` API is a generic interface for reading from a data source. Any object that
  617. implements the data source interface can be plugged into any `ma_data_source` function.
  618. To read data from a data source:
  619. ```c
  620. ma_result result;
  621. ma_uint64 framesRead;
  622. result = ma_data_source_read_pcm_frames(pDataSource, pFramesOut, frameCount, &framesRead, loop);
  623. if (result != MA_SUCCESS) {
  624. return result; // Failed to read data from the data source.
  625. }
  626. ```
  627. If you don't need the number of frames that were successfully read you can pass in `NULL` to the
  628. `pFramesRead` parameter. If this returns a value less than the number of frames requested it means
  629. the end of the file has been reached. `MA_AT_END` will be returned only when the number of frames
  630. read is 0.
  631. When calling any data source function, with the exception of `ma_data_source_init()` and
  632. `ma_data_source_uninit()`, you can pass in any object that implements a data source. For example,
  633. you could plug in a decoder like so:
  634. ```c
  635. ma_result result;
  636. ma_uint64 framesRead;
  637. ma_decoder decoder; // <-- This would be initialized with `ma_decoder_init_*()`.
  638. result = ma_data_source_read_pcm_frames(&decoder, pFramesOut, frameCount, &framesRead, loop);
  639. if (result != MA_SUCCESS) {
  640. return result; // Failed to read data from the decoder.
  641. }
  642. ```
  643. If you want to seek forward you can pass in `NULL` to the `pFramesOut` parameter. Alternatively you
  644. can use `ma_data_source_seek_pcm_frames()`.
  645. To seek to a specific PCM frame:
  646. ```c
  647. result = ma_data_source_seek_to_pcm_frame(pDataSource, frameIndex);
  648. if (result != MA_SUCCESS) {
  649. return result; // Failed to seek to PCM frame.
  650. }
  651. ```
  652. You can retrieve the total length of a data source in PCM frames, but note that some data sources
  653. may not have the notion of a length, such as noise and waveforms, and others may just not have a
  654. way of determining the length such as some decoders. To retrieve the length:
  655. ```c
  656. ma_uint64 length;
  657. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &length);
  658. if (result != MA_SUCCESS) {
  659. return result; // Failed to retrieve the length.
  660. }
  661. ```
  662. Care should be taken when retrieving the length of a data source where the underlying decoder is
  663. pulling data from a data stream with an undefined length, such as internet radio or some kind of
  664. broadcast. If you do this, `ma_data_source_get_length_in_pcm_frames()` may never return.
  665. The current position of the cursor in PCM frames can also be retrieved:
  666. ```c
  667. ma_uint64 cursor;
  668. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
  669. if (result != MA_SUCCESS) {
  670. return result; // Failed to retrieve the cursor.
  671. }
  672. ```
  673. You will often need to know the data format that will be returned after reading. This can be
  674. retrieved like so:
  675. ```c
  676. ma_format format;
  677. ma_uint32 channels;
  678. ma_uint32 sampleRate;
  679. ma_channel channelMap[MA_MAX_CHANNELS];
  680. result = ma_data_source_get_data_format(pDataSource, &format, &channels, &sampleRate, channelMap, MA_MAX_CHANNELS);
  681. if (result != MA_SUCCESS) {
  682. return result; // Failed to retrieve data format.
  683. }
  684. ```
  685. If you do not need a specific data format property, just pass in NULL to the respective parameter.
  686. There may be cases where you want to implement something like a sound bank where you only want to
  687. read data within a certain range of the underlying data. To do this you can use a range:
  688. ```c
  689. result = ma_data_source_set_range_in_pcm_frames(pDataSource, rangeBegInFrames, rangeEndInFrames);
  690. if (result != MA_SUCCESS) {
  691. return result; // Failed to set the range.
  692. }
  693. ```
  694. This is useful if you have a sound bank where many sounds are stored in the same file and you want
  695. the data source to only play one of those sub-sounds.
  696. Custom loop points can also be used with data sources. By default, data sources will loop after
  697. they reach the end of the data source, but if you need to loop at a specific location, you can do
  698. the following:
  699. ```c
  700. result = ma_data_set_loop_point_in_pcm_frames(pDataSource, loopBegInFrames, loopEndInFrames);
  701. if (result != MA_SUCCESS) {
  702. return result; // Failed to set the loop point.
  703. }
  704. ```
  705. The loop point is relative to the current range.
  706. It's sometimes useful to chain data sources together so that a seamless transition can be achieved.
  707. To do this, you can use chaining:
  708. ```c
  709. ma_decoder decoder1;
  710. ma_decoder decoder2;
  711. // ... initialize decoders with ma_decoder_init_*() ...
  712. result = ma_data_source_set_next(&decoder1, &decoder2);
  713. if (result != MA_SUCCESS) {
  714. return result; // Failed to set the next data source.
  715. }
  716. result = ma_data_source_read_pcm_frames(&decoder1, pFramesOut, frameCount, pFramesRead, MA_FALSE);
  717. if (result != MA_SUCCESS) {
  718. return result; // Failed to read from the decoder.
  719. }
  720. ```
  721. In the example above we're using decoders. When reading from a chain, you always want to read from
  722. the top level data source in the chain. In the example above, `decoder1` is the top level data
  723. source in the chain. When `decoder1` reaches the end, `decoder2` will start seamlessly without any
  724. gaps.
  725. Note that the `loop` parameter is set to false in the example above. When this is set to true, only
  726. the current data source will be looped. You can loop the entire chain by linking in a loop like so:
  727. ```c
  728. ma_data_source_set_next(&decoder1, &decoder2); // decoder1 -> decoder2
  729. ma_data_source_set_next(&decoder2, &decoder1); // decoder2 -> decoder1 (loop back to the start).
  730. ```
  731. Note that setting up chaining is not thread safe, so care needs to be taken if you're dynamically
  732. changing links while the audio thread is in the middle of reading.
  733. Do not use `ma_decoder_seek_to_pcm_frame()` as a means to reuse a data source to play multiple
  734. instances of the same sound simultaneously. Instead, initialize multiple data sources for each
  735. instance. This can be extremely inefficient depending on the data source and can result in
  736. glitching due to subtle changes to the state of internal filters.
  737. 4.1. Custom Data Sources
  738. ------------------------
  739. You can implement a custom data source by implementing the functions in `ma_data_source_vtable`.
  740. Your custom object must have `ma_data_source_base` as it's first member:
  741. ```c
  742. struct my_data_source
  743. {
  744. ma_data_source_base base;
  745. ...
  746. };
  747. ```
  748. In your initialization routine, you need to call `ma_data_source_init()` in order to set up the
  749. base object (`ma_data_source_base`):
  750. ```c
  751. static ma_result my_data_source_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  752. {
  753. // Read data here. Output in the same format returned by my_data_source_get_data_format().
  754. }
  755. static ma_result my_data_source_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  756. {
  757. // Seek to a specific PCM frame here. Return MA_NOT_IMPLEMENTED if seeking is not supported.
  758. }
  759. 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)
  760. {
  761. // Return the format of the data here.
  762. }
  763. static ma_result my_data_source_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  764. {
  765. // 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.
  766. }
  767. static ma_result my_data_source_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  768. {
  769. // 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.
  770. }
  771. static g_my_data_source_vtable =
  772. {
  773. my_data_source_read,
  774. my_data_source_seek,
  775. my_data_source_get_data_format,
  776. my_data_source_get_cursor,
  777. my_data_source_get_length
  778. };
  779. ma_result my_data_source_init(my_data_source* pMyDataSource)
  780. {
  781. ma_result result;
  782. ma_data_source_config baseConfig;
  783. baseConfig = ma_data_source_config_init();
  784. baseConfig.vtable = &g_my_data_source_vtable;
  785. result = ma_data_source_init(&baseConfig, &pMyDataSource->base);
  786. if (result != MA_SUCCESS) {
  787. return result;
  788. }
  789. // ... do the initialization of your custom data source here ...
  790. return MA_SUCCESS;
  791. }
  792. void my_data_source_uninit(my_data_source* pMyDataSource)
  793. {
  794. // ... do the uninitialization of your custom data source here ...
  795. // You must uninitialize the base data source.
  796. ma_data_source_uninit(&pMyDataSource->base);
  797. }
  798. ```
  799. Note that `ma_data_source_init()` and `ma_data_source_uninit()` are never called directly outside
  800. of the custom data source. It's up to the custom data source itself to call these within their own
  801. init/uninit functions.
  802. 5. Engine
  803. =========
  804. The `ma_engine` API is a high level API for managing and mixing sounds and effect processing. The
  805. `ma_engine` object encapsulates a resource manager and a node graph, both of which will be
  806. explained in more detail later.
  807. Sounds are called `ma_sound` and are created from an engine. Sounds can be associated with a mixing
  808. group called `ma_sound_group` which are also created from the engine. Both `ma_sound` and
  809. `ma_sound_group` objects are nodes within the engine's node graph.
  810. When the engine is initialized, it will normally create a device internally. If you would rather
  811. manage the device yourself, you can do so and just pass a pointer to it via the engine config when
  812. you initialize the engine. You can also just use the engine without a device, which again can be
  813. configured via the engine config.
  814. The most basic way to initialize the engine is with a default config, like so:
  815. ```c
  816. ma_result result;
  817. ma_engine engine;
  818. result = ma_engine_init(NULL, &engine);
  819. if (result != MA_SUCCESS) {
  820. return result; // Failed to initialize the engine.
  821. }
  822. ```
  823. This will result in the engine initializing a playback device using the operating system's default
  824. device. This will be sufficient for many use cases, but if you need more flexibility you'll want to
  825. configure the engine with an engine config:
  826. ```c
  827. ma_result result;
  828. ma_engine engine;
  829. ma_engine_config engineConfig;
  830. engineConfig = ma_engine_config_init();
  831. engineConfig.pPlaybackDevice = &myDevice;
  832. result = ma_engine_init(&engineConfig, &engine);
  833. if (result != MA_SUCCESS) {
  834. return result; // Failed to initialize the engine.
  835. }
  836. ```
  837. In the example above we're passing in a pre-initialized device. Since the caller is the one in
  838. control of the device's data callback, it's their responsibility to manually call
  839. `ma_engine_read_pcm_frames()` from inside their data callback:
  840. ```c
  841. void playback_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  842. {
  843. ma_engine_read_pcm_frames(&g_Engine, pOutput, frameCount, NULL);
  844. }
  845. ```
  846. You can also use the engine independent of a device entirely:
  847. ```c
  848. ma_result result;
  849. ma_engine engine;
  850. ma_engine_config engineConfig;
  851. engineConfig = ma_engine_config_init();
  852. engineConfig.noDevice = MA_TRUE;
  853. engineConfig.channels = 2; // Must be set when not using a device.
  854. engineConfig.sampleRate = 48000; // Must be set when not using a device.
  855. result = ma_engine_init(&engineConfig, &engine);
  856. if (result != MA_SUCCESS) {
  857. return result; // Failed to initialize the engine.
  858. }
  859. ```
  860. Note that when you're not using a device, you must set the channel count and sample rate in the
  861. config or else miniaudio won't know what to use (miniaudio will use the device to determine this
  862. normally). When not using a device, you need to use `ma_engine_read_pcm_frames()` to process audio
  863. data from the engine. This kind of setup is useful if you want to do something like offline
  864. processing.
  865. When a sound is loaded it goes through a resource manager. By default the engine will initialize a
  866. resource manager internally, but you can also specify a pre-initialized resource manager:
  867. ```c
  868. ma_result result;
  869. ma_engine engine1;
  870. ma_engine engine2;
  871. ma_engine_config engineConfig;
  872. engineConfig = ma_engine_config_init();
  873. engineConfig.pResourceManager = &myResourceManager;
  874. ma_engine_init(&engineConfig, &engine1);
  875. ma_engine_init(&engineConfig, &engine2);
  876. ```
  877. In this example we are initializing two engines, both of which are sharing the same resource
  878. manager. This is especially useful for saving memory when loading the same file across multiple
  879. engines. If you were not to use a shared resource manager, each engine instance would use their own
  880. which would result in any sounds that are used between both engine's being loaded twice. By using
  881. a shared resource manager, it would only be loaded once. Using multiple engine's is useful when you
  882. need to output to multiple playback devices, such as in a local multiplayer game where each player
  883. is using their own set of headphones.
  884. By default an engine will be in a started state. To make it so the engine is not automatically
  885. started you can configure it as such:
  886. ```c
  887. engineConfig.noAutoStart = MA_TRUE;
  888. // The engine will need to be started manually.
  889. ma_engine_start(&engine);
  890. // Later on the engine can be stopped with ma_engine_stop().
  891. ma_engine_stop(&engine);
  892. ```
  893. The concept of starting or stopping an engine is only relevant when using the engine with a
  894. device. Attempting to start or stop an engine that is not associated with a device will result in
  895. `MA_INVALID_OPERATION`.
  896. The master volume of the engine can be controlled with `ma_engine_set_volume()` which takes a
  897. linear scale, with 0 resulting in silence and anything above 1 resulting in amplification. If you
  898. prefer decibel based volume control, use `ma_volume_db_to_linear()` to convert from dB to linear.
  899. When a sound is spatialized, it is done so relative to a listener. An engine can be configured to
  900. have multiple listeners which can be configured via the config:
  901. ```c
  902. engineConfig.listenerCount = 2;
  903. ```
  904. The maximum number of listeners is restricted to `MA_ENGINE_MAX_LISTENERS`. By default, when a
  905. sound is spatialized, it will be done so relative to the closest listener. You can also pin a sound
  906. to a specific listener which will be explained later. Listener's have a position, direction, cone,
  907. and velocity (for doppler effect). A listener is referenced by an index, the meaning of which is up
  908. to the caller (the index is 0 based and cannot go beyond the listener count, minus 1). The
  909. position, direction and velocity are all specified in absolute terms:
  910. ```c
  911. ma_engine_listener_set_position(&engine, listenerIndex, worldPosX, worldPosY, worldPosZ);
  912. ```
  913. The direction of the listener represents it's forward vector. The listener's up vector can also be
  914. specified and defaults to +1 on the Y axis.
  915. ```c
  916. ma_engine_listener_set_direction(&engine, listenerIndex, forwardX, forwardY, forwardZ);
  917. ma_engine_listener_set_world_up(&engine, listenerIndex, 0, 1, 0);
  918. ```
  919. The engine supports directional attenuation. The listener can have a cone the controls how sound is
  920. attenuated based on the listener's direction. When a sound is between the inner and outer cones, it
  921. will be attenuated between 1 and the cone's outer gain:
  922. ```c
  923. ma_engine_listener_set_cone(&engine, listenerIndex, innerAngleInRadians, outerAngleInRadians, outerGain);
  924. ```
  925. When a sound is inside the inner code, no directional attenuation is applied. When the sound is
  926. outside of the outer cone, the attenuation will be set to `outerGain` in the example above. When
  927. the sound is in between the inner and outer cones, the attenuation will be interpolated between 1
  928. and the outer gain.
  929. The engine's coordinate system follows the OpenGL coordinate system where positive X points right,
  930. positive Y points up and negative Z points forward.
  931. The simplest and least flexible way to play a sound is like so:
  932. ```c
  933. ma_engine_play_sound(&engine, "my_sound.wav", pGroup);
  934. ```
  935. This is a "fire and forget" style of function. The engine will manage the `ma_sound` object
  936. internally. When the sound finishes playing, it'll be put up for recycling. For more flexibility
  937. you'll want to initialize a sound object:
  938. ```c
  939. ma_sound sound;
  940. result = ma_sound_init_from_file(&engine, "my_sound.wav", flags, pGroup, NULL, &sound);
  941. if (result != MA_SUCCESS) {
  942. return result; // Failed to load sound.
  943. }
  944. ```
  945. Sounds need to be uninitialized with `ma_sound_uninit()`.
  946. The example above loads a sound from a file. If the resource manager has been disabled you will not
  947. be able to use this function and instead you'll need to initialize a sound directly from a data
  948. source:
  949. ```c
  950. ma_sound sound;
  951. result = ma_sound_init_from_data_source(&engine, &dataSource, flags, pGroup, &sound);
  952. if (result != MA_SUCCESS) {
  953. return result;
  954. }
  955. ```
  956. Each `ma_sound` object represents a single instance of the sound. If you want to play the same
  957. sound multiple times at the same time, you need to initialize a separate `ma_sound` object.
  958. For the most flexibility when initializing sounds, use `ma_sound_init_ex()`. This uses miniaudio's
  959. standard config/init pattern:
  960. ```c
  961. ma_sound sound;
  962. ma_sound_config soundConfig;
  963. soundConfig = ma_sound_config_init();
  964. soundConfig.pFilePath = NULL; // Set this to load from a file path.
  965. soundConfig.pDataSource = NULL; // Set this to initialize from an existing data source.
  966. soundConfig.pInitialAttachment = &someNodeInTheNodeGraph;
  967. soundConfig.initialAttachmentInputBusIndex = 0;
  968. soundConfig.channelsIn = 1;
  969. soundConfig.channelsOut = 0; // Set to 0 to use the engine's native channel count.
  970. result = ma_sound_init_ex(&soundConfig, &sound);
  971. if (result != MA_SUCCESS) {
  972. return result;
  973. }
  974. ```
  975. In the example above, the sound is being initialized without a file nor a data source. This is
  976. valid, in which case the sound acts as a node in the middle of the node graph. This means you can
  977. connect other sounds to this sound and allow it to act like a sound group. Indeed, this is exactly
  978. what a `ma_sound_group` is.
  979. When loading a sound, you specify a set of flags that control how the sound is loaded and what
  980. features are enabled for that sound. When no flags are set, the sound will be fully loaded into
  981. memory in exactly the same format as how it's stored on the file system. The resource manager will
  982. allocate a block of memory and then load the file directly into it. When reading audio data, it
  983. will be decoded dynamically on the fly. In order to save processing time on the audio thread, it
  984. might be beneficial to pre-decode the sound. You can do this with the `MA_SOUND_FLAG_DECODE` flag:
  985. ```c
  986. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE, pGroup, NULL, &sound);
  987. ```
  988. By default, sounds will be loaded synchronously, meaning `ma_sound_init_*()` will not return until
  989. the sound has been fully loaded. If this is prohibitive you can instead load sounds asynchronously
  990. by specificying the `MA_SOUND_FLAG_ASYNC` flag:
  991. ```c
  992. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, NULL, &sound);
  993. ```
  994. This will result in `ma_sound_init_*()` returning quickly, but the sound won't yet have been fully
  995. loaded. When you start the sound, it won't output anything until some sound is available. The sound
  996. will start outputting audio before the sound has been fully decoded when the `MA_SOUND_FLAG_DECODE`
  997. is specified.
  998. If you need to wait for an asynchronously loaded sound to be fully loaded, you can use a fence. A
  999. fence in miniaudio is a simple synchronization mechanism which simply blocks until it's internal
  1000. counter hit's zero. You can specify a fence like so:
  1001. ```c
  1002. ma_result result;
  1003. ma_fence fence;
  1004. ma_sound sounds[4];
  1005. result = ma_fence_init(&fence);
  1006. if (result != MA_SUCCES) {
  1007. return result;
  1008. }
  1009. // Load some sounds asynchronously.
  1010. for (int iSound = 0; iSound < 4; iSound += 1) {
  1011. ma_sound_init_from_file(&engine, mySoundFilesPaths[iSound], MA_SOUND_FLAG_DECODE | MA_SOUND_FLAG_ASYNC, pGroup, &fence, &sounds[iSound]);
  1012. }
  1013. // ... do some other stuff here in the mean time ...
  1014. // Wait for all sounds to finish loading.
  1015. ma_fence_wait(&fence);
  1016. ```
  1017. If loading the entire sound into memory is prohibitive, you can also configure the engine to stream
  1018. the audio data:
  1019. ```c
  1020. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_STREAM, pGroup, NULL, &sound);
  1021. ```
  1022. When streaming sounds, 2 seconds worth of audio data is stored in memory. Although it should work
  1023. fine, it's inefficient to use streaming for short sounds. Streaming is useful for things like music
  1024. tracks in games.
  1025. When loading a sound from a file path, the engine will reference count the file to prevent it from
  1026. being loaded if it's already in memory. When you uninitialize a sound, the reference count will be
  1027. decremented, and if it hits zero, the sound will be unloaded from memory. This reference counting
  1028. system is not used for streams. The engine will use a 64-bit hash of the file name when comparing
  1029. file paths which means there's a small chance you might encounter a name collision. If this is an
  1030. issue, you'll need to use a different name for one of the colliding file paths, or just not load
  1031. from files and instead load from a data source.
  1032. When you initialize a sound, if you specify a sound group the sound will be attached to that group
  1033. automatically. If you set it to NULL, it will be automatically attached to the engine's endpoint.
  1034. If you would instead rather leave the sound unattached by default, you can can specify the
  1035. `MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT` flag. This is useful if you want to set up a complex node
  1036. graph.
  1037. Sounds are not started by default. To start a sound, use `ma_sound_start()`. Stop a sound with
  1038. `ma_sound_stop()`.
  1039. Sounds can have their volume controlled with `ma_sound_set_volume()` in the same way as the
  1040. engine's master volume.
  1041. Sounds support stereo panning and pitching. Set the pan with `ma_sound_set_pan()`. Setting the pan
  1042. to 0 will result in an unpanned sound. Setting it to -1 will shift everything to the left, whereas
  1043. +1 will shift it to the right. The pitch can be controlled with `ma_sound_set_pitch()`. A larger
  1044. value will result in a higher pitch. The pitch must be greater than 0.
  1045. The engine supports 3D spatialization of sounds. By default sounds will have spatialization
  1046. enabled, but if a sound does not need to be spatialized it's best to disable it. There are two ways
  1047. to disable spatialization of a sound:
  1048. ```c
  1049. // Disable spatialization at initialization time via a flag:
  1050. ma_sound_init_from_file(&engine, "my_sound.wav", MA_SOUND_FLAG_NO_SPATIALIZATION, NULL, NULL, &sound);
  1051. // Dynamically disable or enable spatialization post-initialization:
  1052. ma_sound_set_spatialization_enabled(&sound, isSpatializationEnabled);
  1053. ```
  1054. By default sounds will be spatialized based on the closest listener. If a sound should always be
  1055. spatialized relative to a specific listener it can be pinned to one:
  1056. ```c
  1057. ma_sound_set_pinned_listener_index(&sound, listenerIndex);
  1058. ```
  1059. Like listeners, sounds have a position. By default, the position of a sound is in absolute space,
  1060. but it can be changed to be relative to a listener:
  1061. ```c
  1062. ma_sound_set_positioning(&sound, ma_positioning_relative);
  1063. ```
  1064. Note that relative positioning of a sound only makes sense if there is either only one listener, or
  1065. the sound is pinned to a specific listener. To set the position of a sound:
  1066. ```c
  1067. ma_sound_set_position(&sound, posX, posY, posZ);
  1068. ```
  1069. The direction works the same way as a listener and represents the sound's forward direction:
  1070. ```c
  1071. ma_sound_set_direction(&sound, forwardX, forwardY, forwardZ);
  1072. ```
  1073. Sound's also have a cone for controlling directional attenuation. This works exactly the same as
  1074. listeners:
  1075. ```c
  1076. ma_sound_set_cone(&sound, innerAngleInRadians, outerAngleInRadians, outerGain);
  1077. ```
  1078. The velocity of a sound is used for doppler effect and can be set as such:
  1079. ```c
  1080. ma_sound_set_velocity(&sound, velocityX, velocityY, velocityZ);
  1081. ```
  1082. The engine supports different attenuation models which can be configured on a per-sound basis. By
  1083. default the attenuation model is set to `ma_attenuation_model_inverse` which is the equivalent to
  1084. OpenAL's `AL_INVERSE_DISTANCE_CLAMPED`. Configure the attenuation model like so:
  1085. ```c
  1086. ma_sound_set_attenuation_model(&sound, ma_attenuation_model_inverse);
  1087. ```
  1088. The supported attenuation models include the following:
  1089. +----------------------------------+----------------------------------------------+
  1090. | ma_attenuation_model_none | No distance attenuation. |
  1091. +----------------------------------+----------------------------------------------+
  1092. | ma_attenuation_model_inverse | Equivalent to `AL_INVERSE_DISTANCE_CLAMPED`. |
  1093. +----------------------------------+----------------------------------------------+
  1094. | ma_attenuation_model_linear | Linear attenuation. |
  1095. +----------------------------------+----------------------------------------------+
  1096. | ma_attenuation_model_exponential | Exponential attenuation. |
  1097. +----------------------------------+----------------------------------------------+
  1098. To control how quickly a sound rolls off as it moves away from the listener, you need to configure
  1099. the rolloff:
  1100. ```c
  1101. ma_sound_set_rolloff(&sound, rolloff);
  1102. ```
  1103. You can control the minimum and maximum gain to apply from spatialization:
  1104. ```c
  1105. ma_sound_set_min_gain(&sound, minGain);
  1106. ma_sound_set_max_gain(&sound, maxGain);
  1107. ```
  1108. Likewise, in the calculation of attenuation, you can control the minimum and maximum distances for
  1109. the attenuation calculation. This is useful if you want to ensure sounds don't drop below a certain
  1110. volume after the listener moves further away and to have sounds play a maximum volume when the
  1111. listener is within a certain distance:
  1112. ```c
  1113. ma_sound_set_min_distance(&sound, minDistance);
  1114. ma_sound_set_max_distance(&sound, maxDistance);
  1115. ```
  1116. The engine's spatialization system supports doppler effect. The doppler factor can be configure on
  1117. a per-sound basis like so:
  1118. ```c
  1119. ma_sound_set_doppler_factor(&sound, dopplerFactor);
  1120. ```
  1121. You can fade sounds in and out with `ma_sound_set_fade_in_pcm_frames()` and
  1122. `ma_sound_set_fade_in_milliseconds()`. Set the volume to -1 to use the current volume as the
  1123. starting volume:
  1124. ```c
  1125. // Fade in over 1 second.
  1126. ma_sound_set_fade_in_milliseconds(&sound, 0, 1, 1000);
  1127. // ... sometime later ...
  1128. // Fade out over 1 second, starting from the current volume.
  1129. ma_sound_set_fade_in_milliseconds(&sound, -1, 0, 1000);
  1130. ```
  1131. By default sounds will start immediately, but sometimes for timing and synchronization purposes it
  1132. can be useful to schedule a sound to start or stop:
  1133. ```c
  1134. // Start the sound in 1 second from now.
  1135. ma_sound_set_start_time_in_pcm_frames(&sound, ma_engine_get_time(&engine) + (ma_engine_get_sample_rate(&engine) * 1));
  1136. // Stop the sound in 2 seconds from now.
  1137. ma_sound_set_stop_time_in_pcm_frames(&sound, ma_engine_get_time(&engine) + (ma_engine_get_sample_rate(&engine) * 2));
  1138. ```
  1139. Note that scheduling a start time still requires an explicit call to `ma_sound_start()` before
  1140. anything will play.
  1141. The time is specified in global time which is controlled by the engine. You can get the engine's
  1142. current time with `ma_engine_get_time()`. The engine's global time is incremented automatically as
  1143. audio data is read, but it can be reset with `ma_engine_set_time()` in case it needs to be
  1144. resynchronized for some reason.
  1145. To determine whether or not a sound is currently playing, use `ma_sound_is_playing()`. This will
  1146. take the scheduled start and stop times into account.
  1147. Whether or not a sound should loop can be controlled with `ma_sound_set_looping()`. Sounds will not
  1148. be looping by default. Use `ma_sound_is_looping()` to determine whether or not a sound is looping.
  1149. Use `ma_sound_at_end()` to determine whether or not a sound is currently at the end. For a looping
  1150. sound this should never return true.
  1151. Internally a sound wraps around a data source. Some APIs exist to control the underlying data
  1152. source, mainly for convenience:
  1153. ```c
  1154. ma_sound_seek_to_pcm_frame(&sound, frameIndex);
  1155. ma_sound_get_data_format(&sound, &format, &channels, &sampleRate, pChannelMap, channelMapCapacity);
  1156. ma_sound_get_cursor_in_pcm_frames(&sound, &cursor);
  1157. ma_sound_get_length_in_pcm_frames(&sound, &length);
  1158. ```
  1159. Sound groups have the same API as sounds, only they are called `ma_sound_group`, and since they do
  1160. not have any notion of a data source, anything relating to a data source is unavailable.
  1161. Internally, sound data is loaded via the `ma_decoder` API which means by default it only supports
  1162. file formats that have built-in support in miniaudio. You can extend this to support any kind of
  1163. file format through the use of custom decoders. To do this you'll need to use a self-managed
  1164. resource manager and configure it appropriately. See the "Resource Management" section below for
  1165. details on how to set this up.
  1166. 6. Resource Management
  1167. ======================
  1168. Many programs will want to manage sound resources for things such as reference counting and
  1169. streaming. This is supported by miniaudio via the `ma_resource_manager` API.
  1170. The resource manager is mainly responsible for the following:
  1171. * Loading of sound files into memory with reference counting.
  1172. * Streaming of sound data.
  1173. When loading a sound file, the resource manager will give you back a `ma_data_source` compatible
  1174. object called `ma_resource_manager_data_source`. This object can be passed into any
  1175. `ma_data_source` API which is how you can read and seek audio data. When loading a sound file, you
  1176. specify whether or not you want the sound to be fully loaded into memory (and optionally
  1177. pre-decoded) or streamed. When loading into memory, you can also specify whether or not you want
  1178. the data to be loaded asynchronously.
  1179. The example below is how you can initialize a resource manager using it's default configuration:
  1180. ```c
  1181. ma_resource_manager_config config;
  1182. ma_resource_manager resourceManager;
  1183. config = ma_resource_manager_config_init();
  1184. result = ma_resource_manager_init(&config, &resourceManager);
  1185. if (result != MA_SUCCESS) {
  1186. ma_device_uninit(&device);
  1187. printf("Failed to initialize the resource manager.");
  1188. return -1;
  1189. }
  1190. ```
  1191. You can configure the format, channels and sample rate of the decoded audio data. By default it
  1192. will use the file's native data format, but you can configure it to use a consistent format. This
  1193. is useful for offloading the cost of data conversion to load time rather than dynamically
  1194. converting at mixing time. To do this, you configure the decoded format, channels and sample rate
  1195. like the code below:
  1196. ```c
  1197. config = ma_resource_manager_config_init();
  1198. config.decodedFormat = device.playback.format;
  1199. config.decodedChannels = device.playback.channels;
  1200. config.decodedSampleRate = device.sampleRate;
  1201. ```
  1202. In the code above, the resource manager will be configured so that any decoded audio data will be
  1203. pre-converted at load time to the device's native data format. If instead you used defaults and
  1204. the data format of the file did not match the device's data format, you would need to convert the
  1205. data at mixing time which may be prohibitive in high-performance and large scale scenarios like
  1206. games.
  1207. Internally the resource manager uses the `ma_decoder` API to load sounds. This means by default it
  1208. only supports decoders that are built into miniaudio. It's possible to support additional encoding
  1209. formats through the use of custom decoders. To do so, pass in your `ma_decoding_backend_vtable`
  1210. vtables into the resource manager config:
  1211. ```c
  1212. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  1213. {
  1214. &g_ma_decoding_backend_vtable_libvorbis,
  1215. &g_ma_decoding_backend_vtable_libopus
  1216. };
  1217. ...
  1218. resourceManagerConfig.ppCustomDecodingBackendVTables = pCustomBackendVTables;
  1219. resourceManagerConfig.customDecodingBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  1220. resourceManagerConfig.pCustomDecodingBackendUserData = NULL;
  1221. ```
  1222. This system can allow you to support any kind of file format. See the "Decoding" section for
  1223. details on how to implement custom decoders. The miniaudio repository includes examples for Opus
  1224. via libopus and libopusfile and Vorbis via libvorbis and libvorbisfile.
  1225. Asynchronicity is achieved via a job system. When an operation needs to be performed, such as the
  1226. decoding of a page, a job will be posted to a queue which will then be processed by a job thread.
  1227. By default there will be only one job thread running, but this can be configured, like so:
  1228. ```c
  1229. config = ma_resource_manager_config_init();
  1230. config.jobThreadCount = MY_JOB_THREAD_COUNT;
  1231. ```
  1232. By default job threads are managed internally by the resource manager, however you can also self
  1233. manage your job threads if, for example, you want to integrate the job processing into your
  1234. existing job infrastructure, or if you simply don't like the way the resource manager does it. To
  1235. do this, just set the job thread count to 0 and process jobs manually. To process jobs, you first
  1236. need to retrieve a job using `ma_resource_manager_next_job()` and then process it using
  1237. `ma_job_process()`:
  1238. ```c
  1239. config = ma_resource_manager_config_init();
  1240. config.jobThreadCount = 0; // Don't manage any job threads internally.
  1241. config.flags = MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING; // Optional. Makes `ma_resource_manager_next_job()` non-blocking.
  1242. // ... Initialize your custom job threads ...
  1243. void my_custom_job_thread(...)
  1244. {
  1245. for (;;) {
  1246. ma_job job;
  1247. ma_result result = ma_resource_manager_next_job(pMyResourceManager, &job);
  1248. if (result != MA_SUCCESS) {
  1249. if (result == MA_NO_DATA_AVAILABLE) {
  1250. // No jobs are available. Keep going. Will only get this if the resource manager was initialized
  1251. // with MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING.
  1252. continue;
  1253. } else if (result == MA_CANCELLED) {
  1254. // MA_JOB_TYPE_QUIT was posted. Exit.
  1255. break;
  1256. } else {
  1257. // Some other error occurred.
  1258. break;
  1259. }
  1260. }
  1261. ma_job_process(&job);
  1262. }
  1263. }
  1264. ```
  1265. In the example above, the `MA_JOB_TYPE_QUIT` event is the used as the termination
  1266. indicator, but you can use whatever you would like to terminate the thread. The call to
  1267. `ma_resource_manager_next_job()` is blocking by default, but can be configured to be non-blocking
  1268. by initializing the resource manager with the `MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING` configuration
  1269. flag. Note that the `MA_JOB_TYPE_QUIT` will never be removed from the job queue. This
  1270. is to give every thread the opportunity to catch the event and terminate naturally.
  1271. When loading a file, it's sometimes convenient to be able to customize how files are opened and
  1272. read instead of using standard `fopen()`, `fclose()`, etc. which is what miniaudio will use by
  1273. default. This can be done by setting `pVFS` member of the resource manager's config:
  1274. ```c
  1275. // Initialize your custom VFS object. See documentation for VFS for information on how to do this.
  1276. my_custom_vfs vfs = my_custom_vfs_init();
  1277. config = ma_resource_manager_config_init();
  1278. config.pVFS = &vfs;
  1279. ```
  1280. This is particularly useful in programs like games where you want to read straight from an archive
  1281. rather than the normal file system. If you do not specify a custom VFS, the resource manager will
  1282. use the operating system's normal file operations.
  1283. To load a sound file and create a data source, call `ma_resource_manager_data_source_init()`. When
  1284. loading a sound you need to specify the file path and options for how the sounds should be loaded.
  1285. By default a sound will be loaded synchronously. The returned data source is owned by the caller
  1286. which means the caller is responsible for the allocation and freeing of the data source. Below is
  1287. an example for initializing a data source:
  1288. ```c
  1289. ma_resource_manager_data_source dataSource;
  1290. ma_result result = ma_resource_manager_data_source_init(pResourceManager, pFilePath, flags, &dataSource);
  1291. if (result != MA_SUCCESS) {
  1292. // Error.
  1293. }
  1294. // ...
  1295. // A ma_resource_manager_data_source object is compatible with the `ma_data_source` API. To read data, just call
  1296. // the `ma_data_source_read_pcm_frames()` like you would with any normal data source.
  1297. result = ma_data_source_read_pcm_frames(&dataSource, pDecodedData, frameCount, &framesRead);
  1298. if (result != MA_SUCCESS) {
  1299. // Failed to read PCM frames.
  1300. }
  1301. // ...
  1302. ma_resource_manager_data_source_uninit(pResourceManager, &dataSource);
  1303. ```
  1304. The `flags` parameter specifies how you want to perform loading of the sound file. It can be a
  1305. combination of the following flags:
  1306. ```
  1307. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM
  1308. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE
  1309. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC
  1310. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT
  1311. ```
  1312. When no flags are specified (set to 0), the sound will be fully loaded into memory, but not
  1313. decoded, meaning the raw file data will be stored in memory, and then dynamically decoded when
  1314. `ma_data_source_read_pcm_frames()` is called. To instead decode the audio data before storing it in
  1315. memory, use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` flag. By default, the sound file will
  1316. be loaded synchronously, meaning `ma_resource_manager_data_source_init()` will only return after
  1317. the entire file has been loaded. This is good for simplicity, but can be prohibitively slow. You
  1318. can instead load the sound asynchronously using the `MA_RESOURCE_MANAGER_DATA_SOURCE_ASYNC` flag.
  1319. This will result in `ma_resource_manager_data_source_init()` returning quickly, but no data will be
  1320. returned by `ma_data_source_read_pcm_frames()` until some data is available. When no data is
  1321. available because the asynchronous decoding hasn't caught up, `MA_BUSY` will be returned by
  1322. `ma_data_source_read_pcm_frames()`.
  1323. For large sounds, it's often prohibitive to store the entire file in memory. To mitigate this, you
  1324. can instead stream audio data which you can do by specifying the
  1325. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. When streaming, data will be decoded in 1
  1326. second pages. When a new page needs to be decoded, a job will be posted to the job queue and then
  1327. subsequently processed in a job thread.
  1328. For in-memory sounds, reference counting is used to ensure the data is loaded only once. This means
  1329. multiple calls to `ma_resource_manager_data_source_init()` with the same file path will result in
  1330. the file data only being loaded once. Each call to `ma_resource_manager_data_source_init()` must be
  1331. matched up with a call to `ma_resource_manager_data_source_uninit()`. Sometimes it can be useful
  1332. for a program to register self-managed raw audio data and associate it with a file path. Use the
  1333. `ma_resource_manager_register_*()` and `ma_resource_manager_unregister_*()` APIs to do this.
  1334. `ma_resource_manager_register_decoded_data()` is used to associate a pointer to raw, self-managed
  1335. decoded audio data in the specified data format with the specified name. Likewise,
  1336. `ma_resource_manager_register_encoded_data()` is used to associate a pointer to raw self-managed
  1337. encoded audio data (the raw file data) with the specified name. Note that these names need not be
  1338. actual file paths. When `ma_resource_manager_data_source_init()` is called (without the
  1339. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag), the resource manager will look for these
  1340. explicitly registered data buffers and, if found, will use it as the backing data for the data
  1341. source. Note that the resource manager does *not* make a copy of this data so it is up to the
  1342. caller to ensure the pointer stays valid for it's lifetime. Use
  1343. `ma_resource_manager_unregister_data()` to unregister the self-managed data. You can also use
  1344. `ma_resource_manager_register_file()` and `ma_resource_manager_unregister_file()` to register and
  1345. unregister a file. It does not make sense to use the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM`
  1346. flag with a self-managed data pointer.
  1347. 6.1. Asynchronous Loading and Synchronization
  1348. ---------------------------------------------
  1349. When loading asynchronously, it can be useful to poll whether or not loading has finished. Use
  1350. `ma_resource_manager_data_source_result()` to determine this. For in-memory sounds, this will
  1351. return `MA_SUCCESS` when the file has been *entirely* decoded. If the sound is still being decoded,
  1352. `MA_BUSY` will be returned. Otherwise, some other error code will be returned if the sound failed
  1353. to load. For streaming data sources, `MA_SUCCESS` will be returned when the first page has been
  1354. decoded and the sound is ready to be played. If the first page is still being decoded, `MA_BUSY`
  1355. will be returned. Otherwise, some other error code will be returned if the sound failed to load.
  1356. In addition to polling, you can also use a simple synchronization object called a "fence" to wait
  1357. for asynchronously loaded sounds to finish. This is called `ma_fence`. The advantage to using a
  1358. fence is that it can be used to wait for a group of sounds to finish loading rather than waiting
  1359. for sounds on an individual basis. There are two stages to loading a sound:
  1360. * Initialization of the internal decoder; and
  1361. * Completion of decoding of the file (the file is fully decoded)
  1362. You can specify separate fences for each of the different stages. Waiting for the initialization
  1363. of the internal decoder is important for when you need to know the sample format, channels and
  1364. sample rate of the file.
  1365. The example below shows how you could use a fence when loading a number of sounds:
  1366. ```c
  1367. // This fence will be released when all sounds are finished loading entirely.
  1368. ma_fence fence;
  1369. ma_fence_init(&fence);
  1370. // This will be passed into the initialization routine for each sound.
  1371. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1372. notifications.done.pFence = &fence;
  1373. // Now load a bunch of sounds:
  1374. for (iSound = 0; iSound < soundCount; iSound += 1) {
  1375. ma_resource_manager_data_source_init(pResourceManager, pSoundFilePaths[iSound], flags, &notifications, &pSoundSources[iSound]);
  1376. }
  1377. // ... DO SOMETHING ELSE WHILE SOUNDS ARE LOADING ...
  1378. // Wait for loading of sounds to finish.
  1379. ma_fence_wait(&fence);
  1380. ```
  1381. In the example above we used a fence for waiting until the entire file has been fully decoded. If
  1382. you only need to wait for the initialization of the internal decoder to complete, you can use the
  1383. `init` member of the `ma_resource_manager_pipeline_notifications` object:
  1384. ```c
  1385. notifications.init.pFence = &fence;
  1386. ```
  1387. If a fence is not appropriate for your situation, you can instead use a callback that is fired on
  1388. an individual sound basis. This is done in a very similar way to fences:
  1389. ```c
  1390. typedef struct
  1391. {
  1392. ma_async_notification_callbacks cb;
  1393. void* pMyData;
  1394. } my_notification;
  1395. void my_notification_callback(ma_async_notification* pNotification)
  1396. {
  1397. my_notification* pMyNotification = (my_notification*)pNotification;
  1398. // Do something in response to the sound finishing loading.
  1399. }
  1400. ...
  1401. my_notification myCallback;
  1402. myCallback.cb.onSignal = my_notification_callback;
  1403. myCallback.pMyData = pMyData;
  1404. ma_resource_manager_pipeline_notifications notifications = ma_resource_manager_pipeline_notifications_init();
  1405. notifications.done.pNotification = &myCallback;
  1406. ma_resource_manager_data_source_init(pResourceManager, "my_sound.wav", flags, &notifications, &mySound);
  1407. ```
  1408. In the example above we just extend the `ma_async_notification_callbacks` object and pass an
  1409. instantiation into the `ma_resource_manager_pipeline_notifications` in the same way as we did with
  1410. the fence, only we set `pNotification` instead of `pFence`. You can set both of these at the same
  1411. time and they should both work as expected. If using the `pNotification` system, you need to ensure
  1412. your `ma_async_notification_callbacks` object stays valid.
  1413. 6.2. Resource Manager Implementation Details
  1414. --------------------------------------------
  1415. Resources are managed in two main ways:
  1416. * By storing the entire sound inside an in-memory buffer (referred to as a data buffer)
  1417. * By streaming audio data on the fly (referred to as a data stream)
  1418. A resource managed data source (`ma_resource_manager_data_source`) encapsulates a data buffer or
  1419. data stream, depending on whether or not the data source was initialized with the
  1420. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag. If so, it will make use of a
  1421. `ma_resource_manager_data_stream` object. Otherwise it will use a `ma_resource_manager_data_buffer`
  1422. object. Both of these objects are data sources which means they can be used with any
  1423. `ma_data_source_*()` API.
  1424. Another major feature of the resource manager is the ability to asynchronously decode audio files.
  1425. This relieves the audio thread of time-consuming decoding which can negatively affect scalability
  1426. due to the audio thread needing to complete it's work extremely quickly to avoid glitching.
  1427. Asynchronous decoding is achieved through a job system. There is a central multi-producer,
  1428. multi-consumer, fixed-capacity job queue. When some asynchronous work needs to be done, a job is
  1429. posted to the queue which is then read by a job thread. The number of job threads can be
  1430. configured for improved scalability, and job threads can all run in parallel without needing to
  1431. worry about the order of execution (how this is achieved is explained below).
  1432. When a sound is being loaded asynchronously, playback can begin before the sound has been fully
  1433. decoded. This enables the application to start playback of the sound quickly, while at the same
  1434. time allowing to resource manager to keep loading in the background. Since there may be less
  1435. threads than the number of sounds being loaded at a given time, a simple scheduling system is used
  1436. to keep decoding time balanced and fair. The resource manager solves this by splitting decoding
  1437. into chunks called pages. By default, each page is 1 second long. When a page has been decoded, a
  1438. new job will be posted to start decoding the next page. By dividing up decoding into pages, an
  1439. individual sound shouldn't ever delay every other sound from having their first page decoded. Of
  1440. course, when loading many sounds at the same time, there will always be an amount of time required
  1441. to process jobs in the queue so in heavy load situations there will still be some delay. To
  1442. determine if a data source is ready to have some frames read, use
  1443. `ma_resource_manager_data_source_get_available_frames()`. This will return the number of frames
  1444. available starting from the current position.
  1445. 6.2.1. Job Queue
  1446. ----------------
  1447. The resource manager uses a job queue which is multi-producer, multi-consumer, and fixed-capacity.
  1448. This job queue is not currently lock-free, and instead uses a spinlock to achieve thread-safety.
  1449. Only a fixed number of jobs can be allocated and inserted into the queue which is done through a
  1450. lock-free data structure for allocating an index into a fixed sized array, with reference counting
  1451. for mitigation of the ABA problem. The reference count is 32-bit.
  1452. For many types of jobs it's important that they execute in a specific order. In these cases, jobs
  1453. are executed serially. For the resource manager, serial execution of jobs is only required on a
  1454. per-object basis (per data buffer or per data stream). Each of these objects stores an execution
  1455. counter. When a job is posted it is associated with an execution counter. When the job is
  1456. processed, it checks if the execution counter of the job equals the execution counter of the
  1457. owning object and if so, processes the job. If the counters are not equal, the job will be posted
  1458. back onto the job queue for later processing. When the job finishes processing the execution order
  1459. of the main object is incremented. This system means the no matter how many job threads are
  1460. executing, decoding of an individual sound will always get processed serially. The advantage to
  1461. having multiple threads comes into play when loading multiple sounds at the same time.
  1462. The resource manager's job queue is not 100% lock-free and will use a spinlock to achieve
  1463. thread-safety for a very small section of code. This is only relevant when the resource manager
  1464. uses more than one job thread. If only using a single job thread, which is the default, the
  1465. lock should never actually wait in practice. The amount of time spent locking should be quite
  1466. short, but it's something to be aware of for those who have pedantic lock-free requirements and
  1467. need to use more than one job thread. There are plans to remove this lock in a future version.
  1468. In addition, posting a job will release a semaphore, which on Win32 is implemented with
  1469. `ReleaseSemaphore` and on POSIX platforms via a condition variable:
  1470. ```c
  1471. pthread_mutex_lock(&pSemaphore->lock);
  1472. {
  1473. pSemaphore->value += 1;
  1474. pthread_cond_signal(&pSemaphore->cond);
  1475. }
  1476. pthread_mutex_unlock(&pSemaphore->lock);
  1477. ```
  1478. Again, this is relevant for those with strict lock-free requirements in the audio thread. To avoid
  1479. this, you can use non-blocking mode (via the `MA_JOB_QUEUE_FLAG_NON_BLOCKING`
  1480. flag) and implement your own job processing routine (see the "Resource Manager" section above for
  1481. details on how to do this).
  1482. 6.2.2. Data Buffers
  1483. -------------------
  1484. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM` flag is excluded at initialization time, the
  1485. resource manager will try to load the data into an in-memory data buffer. Before doing so, however,
  1486. it will first check if the specified file is already loaded. If so, it will increment a reference
  1487. counter and just use the already loaded data. This saves both time and memory. When the data buffer
  1488. is uninitialized, the reference counter will be decremented. If the counter hits zero, the file
  1489. will be unloaded. This is a detail to keep in mind because it could result in excessive loading and
  1490. unloading of a sound. For example, the following sequence will result in a file be loaded twice,
  1491. once after the other:
  1492. ```c
  1493. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer0); // Refcount = 1. Initial load.
  1494. ma_resource_manager_data_source_uninit(pResourceManager, &myDataBuffer0); // Refcount = 0. Unloaded.
  1495. ma_resource_manager_data_source_init(pResourceManager, "my_file", ..., &myDataBuffer1); // Refcount = 1. Reloaded because previous uninit() unloaded it.
  1496. ma_resource_manager_data_source_uninit(pResourceManager, &myDataBuffer1); // Refcount = 0. Unloaded.
  1497. ```
  1498. A binary search tree (BST) is used for storing data buffers as it has good balance between
  1499. efficiency and simplicity. The key of the BST is a 64-bit hash of the file path that was passed
  1500. into `ma_resource_manager_data_source_init()`. The advantage of using a hash is that it saves
  1501. memory over storing the entire path, has faster comparisons, and results in a mostly balanced BST
  1502. due to the random nature of the hash. The disadvantages are that file names are case-sensitive and
  1503. there's a small chance of name collisions. If case-sensitivity is an issue, you should normalize
  1504. your file names to upper- or lower-case before initializing your data sources. If name collisions
  1505. become an issue, you'll need to change the name of one of the colliding names or just not use the
  1506. resource manager.
  1507. When a sound file has not already been loaded and the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC`
  1508. flag is excluded, the file will be decoded synchronously by the calling thread. There are two
  1509. options for controlling how the audio is stored in the data buffer - encoded or decoded. When the
  1510. `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` option is excluded, the raw file data will be stored
  1511. in memory. Otherwise the sound will be decoded before storing it in memory. Synchronous loading is
  1512. a very simple and standard process of simply adding an item to the BST, allocating a block of
  1513. memory and then decoding (if `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE` is specified).
  1514. When the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag is specified, loading of the data buffer
  1515. is done asynchronously. In this case, a job is posted to the queue to start loading and then the
  1516. function immediately returns, setting an internal result code to `MA_BUSY`. This result code is
  1517. returned when the program calls `ma_resource_manager_data_source_result()`. When decoding has fully
  1518. completed `MA_SUCCESS` will be returned. This can be used to know if loading has fully completed.
  1519. When loading asynchronously, a single job is posted to the queue of the type
  1520. `MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE`. This involves making a copy of the file path and
  1521. associating it with job. When the job is processed by the job thread, it will first load the file
  1522. using the VFS associated with the resource manager. When using a custom VFS, it's important that it
  1523. be completely thread-safe because it will be used from one or more job threads at the same time.
  1524. Individual files should only ever be accessed by one thread at a time, however. After opening the
  1525. file via the VFS, the job will determine whether or not the file is being decoded. If not, it
  1526. simply allocates a block of memory and loads the raw file contents into it and returns. On the
  1527. other hand, when the file is being decoded, it will first allocate a decoder on the heap and
  1528. initialize it. Then it will check if the length of the file is known. If so it will allocate a
  1529. block of memory to store the decoded output and initialize it to silence. If the size is unknown,
  1530. it will allocate room for one page. After memory has been allocated, the first page will be
  1531. decoded. If the sound is shorter than a page, the result code will be set to `MA_SUCCESS` and the
  1532. completion event will be signalled and loading is now complete. If, however, there is more to
  1533. decode, a job with the code `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` is posted. This job
  1534. will decode the next page and perform the same process if it reaches the end. If there is more to
  1535. decode, the job will post another `MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE` job which will
  1536. keep on happening until the sound has been fully decoded. For sounds of an unknown length, each
  1537. page will be linked together as a linked list. Internally this is implemented via the
  1538. `ma_paged_audio_buffer` object.
  1539. 6.2.3. Data Streams
  1540. -------------------
  1541. Data streams only ever store two pages worth of data for each instance. They are most useful for
  1542. large sounds like music tracks in games that would consume too much memory if fully decoded in
  1543. memory. After every frame from a page has been read, a job will be posted to load the next page
  1544. which is done from the VFS.
  1545. For data streams, the `MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC` flag will determine whether or
  1546. not initialization of the data source waits until the two pages have been decoded. When unset,
  1547. `ma_resource_manager_data_source_init()` will wait until the two pages have been loaded, otherwise
  1548. it will return immediately.
  1549. When frames are read from a data stream using `ma_resource_manager_data_source_read_pcm_frames()`,
  1550. `MA_BUSY` will be returned if there are no frames available. If there are some frames available,
  1551. but less than the number requested, `MA_SUCCESS` will be returned, but the actual number of frames
  1552. read will be less than the number requested. Due to the asynchronous nature of data streams,
  1553. seeking is also asynchronous. If the data stream is in the middle of a seek, `MA_BUSY` will be
  1554. returned when trying to read frames.
  1555. When `ma_resource_manager_data_source_read_pcm_frames()` results in a page getting fully consumed
  1556. a job is posted to load the next page. This will be posted from the same thread that called
  1557. `ma_resource_manager_data_source_read_pcm_frames()`.
  1558. Data streams are uninitialized by posting a job to the queue, but the function won't return until
  1559. that job has been processed. The reason for this is that the caller owns the data stream object and
  1560. therefore miniaudio needs to ensure everything completes before handing back control to the caller.
  1561. Also, if the data stream is uninitialized while pages are in the middle of decoding, they must
  1562. complete before destroying any underlying object and the job system handles this cleanly.
  1563. Note that when a new page needs to be loaded, a job will be posted to the resource manager's job
  1564. thread from the audio thread. You must keep in mind the details mentioned in the "Job Queue"
  1565. section above regarding locking when posting an event if you require a strictly lock-free audio
  1566. thread.
  1567. 7. Node Graph
  1568. =============
  1569. miniaudio's routing infrastructure follows a node graph paradigm. The idea is that you create a
  1570. node whose outputs are attached to inputs of another node, thereby creating a graph. There are
  1571. different types of nodes, with each node in the graph processing input data to produce output,
  1572. which is then fed through the chain. Each node in the graph can apply their own custom effects. At
  1573. the start of the graph will usually be one or more data source nodes which have no inputs and
  1574. instead pull their data from a data source. At the end of the graph is an endpoint which represents
  1575. the end of the chain and is where the final output is ultimately extracted from.
  1576. Each node has a number of input buses and a number of output buses. An output bus from a node is
  1577. attached to an input bus of another. Multiple nodes can connect their output buses to another
  1578. node's input bus, in which case their outputs will be mixed before processing by the node. Below is
  1579. a diagram that illustrates a hypothetical node graph setup:
  1580. ```
  1581. >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Data flows left to right >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  1582. +---------------+ +-----------------+
  1583. | Data Source 1 =----+ +----------+ +----= Low Pass Filter =----+
  1584. +---------------+ | | =----+ +-----------------+ | +----------+
  1585. +----= Splitter | +----= ENDPOINT |
  1586. +---------------+ | | =----+ +-----------------+ | +----------+
  1587. | Data Source 2 =----+ +----------+ +----= Echo / Delay =----+
  1588. +---------------+ +-----------------+
  1589. ```
  1590. In the above graph, it starts with two data sources whose outputs are attached to the input of a
  1591. splitter node. It's at this point that the two data sources are mixed. After mixing, the splitter
  1592. performs it's processing routine and produces two outputs which is simply a duplication of the
  1593. input stream. One output is attached to a low pass filter, whereas the other output is attached to
  1594. a echo/delay. The outputs of the the low pass filter and the echo are attached to the endpoint, and
  1595. since they're both connected to the same input bus, they'll be mixed.
  1596. Each input bus must be configured to accept the same number of channels, but the number of channels
  1597. used by input buses can be different to the number of channels for output buses in which case
  1598. miniaudio will automatically convert the input data to the output channel count before processing.
  1599. The number of channels of an output bus of one node must match the channel count of the input bus
  1600. it's attached to. The channel counts cannot be changed after the node has been initialized. If you
  1601. attempt to attach an output bus to an input bus with a different channel count, attachment will
  1602. fail.
  1603. To use a node graph, you first need to initialize a `ma_node_graph` object. This is essentially a
  1604. container around the entire graph. The `ma_node_graph` object is required for some thread-safety
  1605. issues which will be explained later. A `ma_node_graph` object is initialized using miniaudio's
  1606. standard config/init system:
  1607. ```c
  1608. ma_node_graph_config nodeGraphConfig = ma_node_graph_config_init(myChannelCount);
  1609. result = ma_node_graph_init(&nodeGraphConfig, NULL, &nodeGraph); // Second parameter is a pointer to allocation callbacks.
  1610. if (result != MA_SUCCESS) {
  1611. // Failed to initialize node graph.
  1612. }
  1613. ```
  1614. When you initialize the node graph, you're specifying the channel count of the endpoint. The
  1615. endpoint is a special node which has one input bus and one output bus, both of which have the
  1616. same channel count, which is specified in the config. Any nodes that connect directly to the
  1617. endpoint must be configured such that their output buses have the same channel count. When you read
  1618. audio data from the node graph, it'll have the channel count you specified in the config. To read
  1619. data from the graph:
  1620. ```c
  1621. ma_uint32 framesRead;
  1622. result = ma_node_graph_read_pcm_frames(&nodeGraph, pFramesOut, frameCount, &framesRead);
  1623. if (result != MA_SUCCESS) {
  1624. // Failed to read data from the node graph.
  1625. }
  1626. ```
  1627. When you read audio data, miniaudio starts at the node graph's endpoint node which then pulls in
  1628. data from it's input attachments, which in turn recusively pull in data from their inputs, and so
  1629. on. At the start of the graph there will be some kind of data source node which will have zero
  1630. inputs and will instead read directly from a data source. The base nodes don't literally need to
  1631. read from a `ma_data_source` object, but they will always have some kind of underlying object that
  1632. sources some kind of audio. The `ma_data_source_node` node can be used to read from a
  1633. `ma_data_source`. Data is always in floating-point format and in the number of channels you
  1634. specified when the graph was initialized. The sample rate is defined by the underlying data sources.
  1635. It's up to you to ensure they use a consistent and appropraite sample rate.
  1636. The `ma_node` API is designed to allow custom nodes to be implemented with relative ease, but
  1637. miniaudio includes a few stock nodes for common functionality. This is how you would initialize a
  1638. node which reads directly from a data source (`ma_data_source_node`) which is an example of one
  1639. of the stock nodes that comes with miniaudio:
  1640. ```c
  1641. ma_data_source_node_config config = ma_data_source_node_config_init(pMyDataSource);
  1642. ma_data_source_node dataSourceNode;
  1643. result = ma_data_source_node_init(&nodeGraph, &config, NULL, &dataSourceNode);
  1644. if (result != MA_SUCCESS) {
  1645. // Failed to create data source node.
  1646. }
  1647. ```
  1648. The data source node will use the output channel count to determine the channel count of the output
  1649. bus. There will be 1 output bus and 0 input buses (data will be drawn directly from the data
  1650. source). The data source must output to floating-point (`ma_format_f32`) or else an error will be
  1651. returned from `ma_data_source_node_init()`.
  1652. By default the node will not be attached to the graph. To do so, use `ma_node_attach_output_bus()`:
  1653. ```c
  1654. result = ma_node_attach_output_bus(&dataSourceNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0);
  1655. if (result != MA_SUCCESS) {
  1656. // Failed to attach node.
  1657. }
  1658. ```
  1659. The code above connects the data source node directly to the endpoint. Since the data source node
  1660. has only a single output bus, the index will always be 0. Likewise, the endpoint only has a single
  1661. input bus which means the input bus index will also always be 0.
  1662. To detach a specific output bus, use `ma_node_detach_output_bus()`. To detach all output buses, use
  1663. `ma_node_detach_all_output_buses()`. If you want to just move the output bus from one attachment to
  1664. another, you do not need to detach first. You can just call `ma_node_attach_output_bus()` and it'll
  1665. deal with it for you.
  1666. Less frequently you may want to create a specialized node. This will be a node where you implement
  1667. your own processing callback to apply a custom effect of some kind. This is similar to initalizing
  1668. one of the stock node types, only this time you need to specify a pointer to a vtable containing a
  1669. pointer to the processing function and the number of input and output buses. Example:
  1670. ```c
  1671. static void my_custom_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  1672. {
  1673. // Do some processing of ppFramesIn (one stream of audio data per input bus)
  1674. const float* pFramesIn_0 = ppFramesIn[0]; // Input bus @ index 0.
  1675. const float* pFramesIn_1 = ppFramesIn[1]; // Input bus @ index 1.
  1676. float* pFramesOut_0 = ppFramesOut[0]; // Output bus @ index 0.
  1677. // Do some processing. On input, `pFrameCountIn` will be the number of input frames in each
  1678. // buffer in `ppFramesIn` and `pFrameCountOut` will be the capacity of each of the buffers
  1679. // in `ppFramesOut`. On output, `pFrameCountIn` should be set to the number of input frames
  1680. // your node consumed and `pFrameCountOut` should be set the number of output frames that
  1681. // were produced.
  1682. //
  1683. // You should process as many frames as you can. If your effect consumes input frames at the
  1684. // same rate as output frames (always the case, unless you're doing resampling), you need
  1685. // only look at `ppFramesOut` and process that exact number of frames. If you're doing
  1686. // resampling, you'll need to be sure to set both `pFrameCountIn` and `pFrameCountOut`
  1687. // properly.
  1688. }
  1689. static ma_node_vtable my_custom_node_vtable =
  1690. {
  1691. 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.
  1692. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1693. 2, // 2 input buses.
  1694. 1, // 1 output bus.
  1695. 0 // Default flags.
  1696. };
  1697. ...
  1698. // Each bus needs to have a channel count specified. To do this you need to specify the channel
  1699. // counts in an array and then pass that into the node config.
  1700. ma_uint32 inputChannels[2]; // Equal in size to the number of input channels specified in the vtable.
  1701. ma_uint32 outputChannels[1]; // Equal in size to the number of output channels specicied in the vtable.
  1702. inputChannels[0] = channelsIn;
  1703. inputChannels[1] = channelsIn;
  1704. outputChannels[0] = channelsOut;
  1705. ma_node_config nodeConfig = ma_node_config_init();
  1706. nodeConfig.vtable = &my_custom_node_vtable;
  1707. nodeConfig.pInputChannels = inputChannels;
  1708. nodeConfig.pOutputChannels = outputChannels;
  1709. ma_node_base node;
  1710. result = ma_node_init(&nodeGraph, &nodeConfig, NULL, &node);
  1711. if (result != MA_SUCCESS) {
  1712. // Failed to initialize node.
  1713. }
  1714. ```
  1715. When initializing a custom node, as in the code above, you'll normally just place your vtable in
  1716. static space. The number of input and output buses are specified as part of the vtable. If you need
  1717. a variable number of buses on a per-node bases, the vtable should have the relevant bus count set
  1718. to `MA_NODE_BUS_COUNT_UNKNOWN`. In this case, the bus count should be set in the node config:
  1719. ```c
  1720. static ma_node_vtable my_custom_node_vtable =
  1721. {
  1722. 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.
  1723. NULL, // Optional. A callback for calculating the number of input frames that are required to process a specified number of output frames.
  1724. MA_NODE_BUS_COUNT_UNKNOWN, // The number of input buses is determined on a per-node basis.
  1725. 1, // 1 output bus.
  1726. 0 // Default flags.
  1727. };
  1728. ...
  1729. ma_node_config nodeConfig = ma_node_config_init();
  1730. nodeConfig.vtable = &my_custom_node_vtable;
  1731. nodeConfig.inputBusCount = myBusCount; // <-- Since the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN, the input bus count should be set here.
  1732. nodeConfig.pInputChannels = inputChannels; // <-- Make sure there are nodeConfig.inputBusCount elements in this array.
  1733. nodeConfig.pOutputChannels = outputChannels; // <-- The vtable specifies 1 output bus, so there must be 1 element in this array.
  1734. ```
  1735. In the above example it's important to never set the `inputBusCount` and `outputBusCount` members
  1736. to anything other than their defaults if the vtable specifies an explicit count. They can only be
  1737. set if the vtable specifies MA_NODE_BUS_COUNT_UNKNOWN in the relevant bus count.
  1738. Most often you'll want to create a structure to encapsulate your node with some extra data. You
  1739. need to make sure the `ma_node_base` object is your first member of the structure:
  1740. ```c
  1741. typedef struct
  1742. {
  1743. ma_node_base base; // <-- Make sure this is always the first member.
  1744. float someCustomData;
  1745. } my_custom_node;
  1746. ```
  1747. By doing this, your object will be compatible with all `ma_node` APIs and you can attach it to the
  1748. graph just like any other node.
  1749. In the custom processing callback (`my_custom_node_process_pcm_frames()` in the example above), the
  1750. number of channels for each bus is what was specified by the config when the node was initialized
  1751. with `ma_node_init()`. In addition, all attachments to each of the input buses will have been
  1752. pre-mixed by miniaudio. The config allows you to specify different channel counts for each
  1753. individual input and output bus. It's up to the effect to handle it appropriate, and if it can't,
  1754. return an error in it's initialization routine.
  1755. Custom nodes can be assigned some flags to describe their behaviour. These are set via the vtable
  1756. and include the following:
  1757. +-----------------------------------------+---------------------------------------------------+
  1758. | Flag Name | Description |
  1759. +-----------------------------------------+---------------------------------------------------+
  1760. | MA_NODE_FLAG_PASSTHROUGH | Useful for nodes that do not do any kind of audio |
  1761. | | processing, but are instead used for tracking |
  1762. | | time, handling events, etc. Also used by the |
  1763. | | internal endpoint node. It reads directly from |
  1764. | | the input bus to the output bus. Nodes with this |
  1765. | | flag must have exactly 1 input bus and 1 output |
  1766. | | bus, and both buses must have the same channel |
  1767. | | counts. |
  1768. +-----------------------------------------+---------------------------------------------------+
  1769. | MA_NODE_FLAG_CONTINUOUS_PROCESSING | Causes the processing callback to be called even |
  1770. | | when no data is available to be read from input |
  1771. | | attachments. This is useful for effects like |
  1772. | | echos where there will be a tail of audio data |
  1773. | | that still needs to be processed even when the |
  1774. | | original data sources have reached their ends. |
  1775. +-----------------------------------------+---------------------------------------------------+
  1776. | MA_NODE_FLAG_ALLOW_NULL_INPUT | Used in conjunction with |
  1777. | | `MA_NODE_FLAG_CONTINUOUS_PROCESSING`. When this |
  1778. | | is set, the `ppFramesIn` parameter of the |
  1779. | | processing callback will be set to NULL when |
  1780. | | there are no input frames are available. When |
  1781. | | this is unset, silence will be posted to the |
  1782. | | processing callback. |
  1783. +-----------------------------------------+---------------------------------------------------+
  1784. | MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES | Used to tell miniaudio that input and output |
  1785. | | frames are processed at different rates. You |
  1786. | | should set this for any nodes that perform |
  1787. | | resampling. |
  1788. +-----------------------------------------+---------------------------------------------------+
  1789. | MA_NODE_FLAG_SILENT_OUTPUT | Used to tell miniaudio that a node produces only |
  1790. | | silent output. This is useful for nodes where you |
  1791. | | don't want the output to contribute to the final |
  1792. | | mix. An example might be if you want split your |
  1793. | | stream and have one branch be output to a file. |
  1794. | | When using this flag, you should avoid writing to |
  1795. | | the output buffer of the node's processing |
  1796. | | callback because miniaudio will ignore it anyway. |
  1797. +-----------------------------------------+---------------------------------------------------+
  1798. If you need to make a copy of an audio stream for effect processing you can use a splitter node
  1799. called `ma_splitter_node`. This takes has 1 input bus and splits the stream into 2 output buses.
  1800. You can use it like this:
  1801. ```c
  1802. ma_splitter_node_config splitterNodeConfig = ma_splitter_node_config_init(channels);
  1803. ma_splitter_node splitterNode;
  1804. result = ma_splitter_node_init(&nodeGraph, &splitterNodeConfig, NULL, &splitterNode);
  1805. if (result != MA_SUCCESS) {
  1806. // Failed to create node.
  1807. }
  1808. // Attach your output buses to two different input buses (can be on two different nodes).
  1809. ma_node_attach_output_bus(&splitterNode, 0, ma_node_graph_get_endpoint(&nodeGraph), 0); // Attach directly to the endpoint.
  1810. ma_node_attach_output_bus(&splitterNode, 1, &myEffectNode, 0); // Attach to input bus 0 of some effect node.
  1811. ```
  1812. The volume of an output bus can be configured on a per-bus basis:
  1813. ```c
  1814. ma_node_set_output_bus_volume(&splitterNode, 0, 0.5f);
  1815. ma_node_set_output_bus_volume(&splitterNode, 1, 0.5f);
  1816. ```
  1817. In the code above we're using the splitter node from before and changing the volume of each of the
  1818. copied streams.
  1819. You can start and stop a node with the following:
  1820. ```c
  1821. ma_node_set_state(&splitterNode, ma_node_state_started); // The default state.
  1822. ma_node_set_state(&splitterNode, ma_node_state_stopped);
  1823. ```
  1824. By default the node is in a started state, but since it won't be connected to anything won't
  1825. actually be invoked by the node graph until it's connected. When you stop a node, data will not be
  1826. read from any of it's input connections. You can use this property to stop a group of sounds
  1827. atomically.
  1828. You can configure the initial state of a node in it's config:
  1829. ```c
  1830. nodeConfig.initialState = ma_node_state_stopped;
  1831. ```
  1832. Note that for the stock specialized nodes, all of their configs will have a `nodeConfig` member
  1833. which is the config to use with the base node. This is where the initial state can be configured
  1834. for specialized nodes:
  1835. ```c
  1836. dataSourceNodeConfig.nodeConfig.initialState = ma_node_state_stopped;
  1837. ```
  1838. When using a specialized node like `ma_data_source_node` or `ma_splitter_node`, be sure to not
  1839. modify the `vtable` member of the `nodeConfig` object.
  1840. 7.1. Timing
  1841. -----------
  1842. The node graph supports starting and stopping nodes at scheduled times. This is especially useful
  1843. for data source nodes where you want to get the node set up, but only start playback at a specific
  1844. time. There are two clocks: local and global.
  1845. A local clock is per-node, whereas the global clock is per graph. Scheduling starts and stops can
  1846. only be done based on the global clock because the local clock will not be running while the node
  1847. is stopped. The global clocks advances whenever `ma_node_graph_read_pcm_frames()` is called. On the
  1848. other hand, the local clock only advances when the node's processing callback is fired, and is
  1849. advanced based on the output frame count.
  1850. To retrieve the global time, use `ma_node_graph_get_time()`. The global time can be set with
  1851. `ma_node_graph_set_time()` which might be useful if you want to do seeking on a global timeline.
  1852. Getting and setting the local time is similar. Use `ma_node_get_time()` to retrieve the local time,
  1853. and `ma_node_set_time()` to set the local time. The global and local times will be advanced by the
  1854. audio thread, so care should be taken to avoid data races. Ideally you should avoid calling these
  1855. outside of the node processing callbacks which are always run on the audio thread.
  1856. There is basic support for scheduling the starting and stopping of nodes. You can only schedule one
  1857. start and one stop at a time. This is mainly intended for putting nodes into a started or stopped
  1858. state in a frame-exact manner. Without this mechanism, starting and stopping of a node is limited
  1859. to the resolution of a call to `ma_node_graph_read_pcm_frames()` which would typically be in blocks
  1860. of several milliseconds. The following APIs can be used for scheduling node states:
  1861. ```c
  1862. ma_node_set_state_time()
  1863. ma_node_get_state_time()
  1864. ```
  1865. The time is absolute and must be based on the global clock. An example is below:
  1866. ```c
  1867. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1); // Delay starting to 1 second.
  1868. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5); // Delay stopping to 5 seconds.
  1869. ```
  1870. An example for changing the state using a relative time.
  1871. ```c
  1872. ma_node_set_state_time(&myNode, ma_node_state_started, sampleRate*1 + ma_node_graph_get_time(&myNodeGraph));
  1873. ma_node_set_state_time(&myNode, ma_node_state_stopped, sampleRate*5 + ma_node_graph_get_time(&myNodeGraph));
  1874. ```
  1875. Note that due to the nature of multi-threading the times may not be 100% exact. If this is an
  1876. issue, consider scheduling state changes from within a processing callback. An idea might be to
  1877. have some kind of passthrough trigger node that is used specifically for tracking time and handling
  1878. events.
  1879. 7.2. Thread Safety and Locking
  1880. ------------------------------
  1881. When processing audio, it's ideal not to have any kind of locking in the audio thread. Since it's
  1882. expected that `ma_node_graph_read_pcm_frames()` would be run on the audio thread, it does so
  1883. without the use of any locks. This section discusses the implementation used by miniaudio and goes
  1884. over some of the compromises employed by miniaudio to achieve this goal. Note that the current
  1885. implementation may not be ideal - feedback and critiques are most welcome.
  1886. The node graph API is not *entirely* lock-free. Only `ma_node_graph_read_pcm_frames()` is expected
  1887. to be lock-free. Attachment, detachment and uninitialization of nodes use locks to simplify the
  1888. implementation, but are crafted in a way such that such locking is not required when reading audio
  1889. data from the graph. Locking in these areas are achieved by means of spinlocks.
  1890. The main complication with keeping `ma_node_graph_read_pcm_frames()` lock-free stems from the fact
  1891. that a node can be uninitialized, and it's memory potentially freed, while in the middle of being
  1892. processed on the audio thread. There are times when the audio thread will be referencing a node,
  1893. which means the uninitialization process of a node needs to make sure it delays returning until the
  1894. audio thread is finished so that control is not handed back to the caller thereby giving them a
  1895. chance to free the node's memory.
  1896. When the audio thread is processing a node, it does so by reading from each of the output buses of
  1897. the node. In order for a node to process data for one of it's output buses, it needs to read from
  1898. each of it's input buses, and so on an so forth. It follows that once all output buses of a node
  1899. are detached, the node as a whole will be disconnected and no further processing will occur unless
  1900. it's output buses are reattached, which won't be happening when the node is being uninitialized.
  1901. By having `ma_node_detach_output_bus()` wait until the audio thread is finished with it, we can
  1902. simplify a few things, at the expense of making `ma_node_detach_output_bus()` a bit slower. By
  1903. doing this, the implementation of `ma_node_uninit()` becomes trivial - just detach all output
  1904. nodes, followed by each of the attachments to each of it's input nodes, and then do any final clean
  1905. up.
  1906. With the above design, the worst-case scenario is `ma_node_detach_output_bus()` taking as long as
  1907. it takes to process the output bus being detached. This will happen if it's called at just the
  1908. wrong moment where the audio thread has just iterated it and has just started processing. The
  1909. caller of `ma_node_detach_output_bus()` will stall until the audio thread is finished, which
  1910. includes the cost of recursively processing it's inputs. This is the biggest compromise made with
  1911. the approach taken by miniaudio for it's lock-free processing system. The cost of detaching nodes
  1912. earlier in the pipeline (data sources, for example) will be cheaper than the cost of detaching
  1913. higher level nodes, such as some kind of final post-processing endpoint. If you need to do mass
  1914. detachments, detach starting from the lowest level nodes and work your way towards the final
  1915. endpoint node (but don't try detaching the node graph's endpoint). If the audio thread is not
  1916. running, detachment will be fast and detachment in any order will be the same. The reason nodes
  1917. need to wait for their input attachments to complete is due to the potential for desyncs between
  1918. data sources. If the node was to terminate processing mid way through processing it's inputs,
  1919. there's a chance that some of the underlying data sources will have been read, but then others not.
  1920. That will then result in a potential desynchronization when detaching and reattaching higher-level
  1921. nodes. A possible solution to this is to have an option when detaching to terminate processing
  1922. before processing all input attachments which should be fairly simple.
  1923. Another compromise, albeit less significant, is locking when attaching and detaching nodes. This
  1924. locking is achieved by means of a spinlock in order to reduce memory overhead. A lock is present
  1925. for each input bus and output bus. When an output bus is connected to an input bus, both the output
  1926. bus and input bus is locked. This locking is specifically for attaching and detaching across
  1927. different threads and does not affect `ma_node_graph_read_pcm_frames()` in any way. The locking and
  1928. unlocking is mostly self-explanatory, but a slightly less intuitive aspect comes into it when
  1929. considering that iterating over attachments must not break as a result of attaching or detaching a
  1930. node while iteration is occuring.
  1931. Attaching and detaching are both quite simple. When an output bus of a node is attached to an input
  1932. bus of another node, it's added to a linked list. Basically, an input bus is a linked list, where
  1933. each item in the list is and output bus. We have some intentional (and convenient) restrictions on
  1934. what can done with the linked list in order to simplify the implementation. First of all, whenever
  1935. something needs to iterate over the list, it must do so in a forward direction. Backwards iteration
  1936. is not supported. Also, items can only be added to the start of the list.
  1937. The linked list is a doubly-linked list where each item in the list (an output bus) holds a pointer
  1938. to the next item in the list, and another to the previous item. A pointer to the previous item is
  1939. only required for fast detachment of the node - it is never used in iteration. This is an
  1940. important property because it means from the perspective of iteration, attaching and detaching of
  1941. an item can be done with a single atomic assignment. This is exploited by both the attachment and
  1942. detachment process. When attaching the node, the first thing that is done is the setting of the
  1943. local "next" and "previous" pointers of the node. After that, the item is "attached" to the list
  1944. by simply performing an atomic exchange with the head pointer. After that, the node is "attached"
  1945. to the list from the perspective of iteration. Even though the "previous" pointer of the next item
  1946. hasn't yet been set, from the perspective of iteration it's been attached because iteration will
  1947. only be happening in a forward direction which means the "previous" pointer won't actually ever get
  1948. used. The same general process applies to detachment. See `ma_node_attach_output_bus()` and
  1949. `ma_node_detach_output_bus()` for the implementation of this mechanism.
  1950. 8. Decoding
  1951. ===========
  1952. The `ma_decoder` API is used for reading audio files. Decoders are completely decoupled from
  1953. devices and can be used independently. The following formats are supported:
  1954. +---------+------------------+----------+
  1955. | Format | Decoding Backend | Built-In |
  1956. +---------+------------------+----------+
  1957. | WAV | dr_wav | Yes |
  1958. | MP3 | dr_mp3 | Yes |
  1959. | FLAC | dr_flac | Yes |
  1960. | Vorbis | stb_vorbis | No |
  1961. +---------+------------------+----------+
  1962. Vorbis is supported via stb_vorbis which can be enabled by including the header section before the
  1963. implementation of miniaudio, like the following:
  1964. ```c
  1965. #define STB_VORBIS_HEADER_ONLY
  1966. #include "extras/stb_vorbis.c" // Enables Vorbis decoding.
  1967. #define MINIAUDIO_IMPLEMENTATION
  1968. #include "miniaudio.h"
  1969. // The stb_vorbis implementation must come after the implementation of miniaudio.
  1970. #undef STB_VORBIS_HEADER_ONLY
  1971. #include "extras/stb_vorbis.c"
  1972. ```
  1973. A copy of stb_vorbis is included in the "extras" folder in the miniaudio repository (https://github.com/mackron/miniaudio).
  1974. Built-in decoders are amalgamated into the implementation section of miniaudio. You can disable the
  1975. built-in decoders by specifying one or more of the following options before the miniaudio
  1976. implementation:
  1977. ```c
  1978. #define MA_NO_WAV
  1979. #define MA_NO_MP3
  1980. #define MA_NO_FLAC
  1981. ```
  1982. Disabling built-in decoding libraries is useful if you use these libraries independantly of the
  1983. `ma_decoder` API.
  1984. A decoder can be initialized from a file with `ma_decoder_init_file()`, a block of memory with
  1985. `ma_decoder_init_memory()`, or from data delivered via callbacks with `ma_decoder_init()`. Here is
  1986. an example for loading a decoder from a file:
  1987. ```c
  1988. ma_decoder decoder;
  1989. ma_result result = ma_decoder_init_file("MySong.mp3", NULL, &decoder);
  1990. if (result != MA_SUCCESS) {
  1991. return false; // An error occurred.
  1992. }
  1993. ...
  1994. ma_decoder_uninit(&decoder);
  1995. ```
  1996. When initializing a decoder, you can optionally pass in a pointer to a `ma_decoder_config` object
  1997. (the `NULL` argument in the example above) which allows you to configure the output format, channel
  1998. count, sample rate and channel map:
  1999. ```c
  2000. ma_decoder_config config = ma_decoder_config_init(ma_format_f32, 2, 48000);
  2001. ```
  2002. When passing in `NULL` for decoder config in `ma_decoder_init*()`, the output format will be the
  2003. same as that defined by the decoding backend.
  2004. Data is read from the decoder as PCM frames. This will output the number of PCM frames actually
  2005. read. If this is less than the requested number of PCM frames it means you've reached the end. The
  2006. return value will be `MA_AT_END` if no samples have been read and the end has been reached.
  2007. ```c
  2008. ma_result result = ma_decoder_read_pcm_frames(pDecoder, pFrames, framesToRead, &framesRead);
  2009. if (framesRead < framesToRead) {
  2010. // Reached the end.
  2011. }
  2012. ```
  2013. You can also seek to a specific frame like so:
  2014. ```c
  2015. ma_result result = ma_decoder_seek_to_pcm_frame(pDecoder, targetFrame);
  2016. if (result != MA_SUCCESS) {
  2017. return false; // An error occurred.
  2018. }
  2019. ```
  2020. If you want to loop back to the start, you can simply seek back to the first PCM frame:
  2021. ```c
  2022. ma_decoder_seek_to_pcm_frame(pDecoder, 0);
  2023. ```
  2024. When loading a decoder, miniaudio uses a trial and error technique to find the appropriate decoding
  2025. backend. This can be unnecessarily inefficient if the type is already known. In this case you can
  2026. use `encodingFormat` variable in the device config to specify a specific encoding format you want
  2027. to decode:
  2028. ```c
  2029. decoderConfig.encodingFormat = ma_encoding_format_wav;
  2030. ```
  2031. See the `ma_encoding_format` enum for possible encoding formats.
  2032. The `ma_decoder_init_file()` API will try using the file extension to determine which decoding
  2033. backend to prefer.
  2034. 8.1. Custom Decoders
  2035. --------------------
  2036. It's possible to implement a custom decoder and plug it into miniaudio. This is extremely useful
  2037. when you want to use the `ma_decoder` API, but need to support an encoding format that's not one of
  2038. the stock formats supported by miniaudio. This can be put to particularly good use when using the
  2039. `ma_engine` and/or `ma_resource_manager` APIs because they use `ma_decoder` internally. If, for
  2040. example, you wanted to support Opus, you can do so with a custom decoder (there if a reference
  2041. Opus decoder in the "extras" folder of the miniaudio repository which uses libopus + libopusfile).
  2042. A custom decoder must implement a data source. A vtable called `ma_decoding_backend_vtable` needs
  2043. to be implemented which is then passed into the decoder config:
  2044. ```c
  2045. ma_decoding_backend_vtable* pCustomBackendVTables[] =
  2046. {
  2047. &g_ma_decoding_backend_vtable_libvorbis,
  2048. &g_ma_decoding_backend_vtable_libopus
  2049. };
  2050. ...
  2051. decoderConfig = ma_decoder_config_init_default();
  2052. decoderConfig.pCustomBackendUserData = NULL;
  2053. decoderConfig.ppCustomBackendVTables = pCustomBackendVTables;
  2054. decoderConfig.customBackendCount = sizeof(pCustomBackendVTables) / sizeof(pCustomBackendVTables[0]);
  2055. ```
  2056. The `ma_decoding_backend_vtable` vtable has the following functions:
  2057. ```
  2058. onInit
  2059. onInitFile
  2060. onInitFileW
  2061. onInitMemory
  2062. onUninit
  2063. ```
  2064. There are only two functions that must be implemented - `onInit` and `onUninit`. The other
  2065. functions can be implemented for a small optimization for loading from a file path or memory. If
  2066. these are not specified, miniaudio will deal with it for you via a generic implementation.
  2067. When you initialize a custom data source (by implementing the `onInit` function in the vtable) you
  2068. will need to output a pointer to a `ma_data_source` which implements your custom decoder. See the
  2069. section about data sources for details on how to implemen this. Alternatively, see the
  2070. "custom_decoders" example in the miniaudio repository.
  2071. The `onInit` function takes a pointer to some callbacks for the purpose of reading raw audio data
  2072. from some abitrary source. You'll use these functions to read from the raw data and perform the
  2073. decoding. When you call them, you will pass in the `pReadSeekTellUserData` pointer to the relevant
  2074. parameter.
  2075. The `pConfig` parameter in `onInit` can be used to configure the backend if appropriate. It's only
  2076. used as a hint and can be ignored. However, if any of the properties are relevant to your decoder,
  2077. an optimal implementation will handle the relevant properties appropriately.
  2078. If memory allocation is required, it should be done so via the specified allocation callbacks if
  2079. possible (the `pAllocationCallbacks` parameter).
  2080. If an error occurs when initializing the decoder, you should leave `ppBackend` unset, or set to
  2081. NULL, and make sure everything is cleaned up appropriately and an appropriate result code returned.
  2082. When multiple custom backends are specified, miniaudio will cycle through the vtables in the order
  2083. they're listed in the array that's passed into the decoder config so it's important that your
  2084. initialization routine is clean.
  2085. When a decoder is uninitialized, the `onUninit` callback will be fired which will give you an
  2086. opportunity to clean up and internal data.
  2087. 9. Encoding
  2088. ===========
  2089. The `ma_encoding` API is used for writing audio files. The only supported output format is WAV
  2090. which is achieved via dr_wav which is amalgamated into the implementation section of miniaudio.
  2091. This can be disabled by specifying the following option before the implementation of miniaudio:
  2092. ```c
  2093. #define MA_NO_WAV
  2094. ```
  2095. An encoder can be initialized to write to a file with `ma_encoder_init_file()` or from data
  2096. delivered via callbacks with `ma_encoder_init()`. Below is an example for initializing an encoder
  2097. to output to a file.
  2098. ```c
  2099. ma_encoder_config config = ma_encoder_config_init(ma_encoding_format_wav, FORMAT, CHANNELS, SAMPLE_RATE);
  2100. ma_encoder encoder;
  2101. ma_result result = ma_encoder_init_file("my_file.wav", &config, &encoder);
  2102. if (result != MA_SUCCESS) {
  2103. // Error
  2104. }
  2105. ...
  2106. ma_encoder_uninit(&encoder);
  2107. ```
  2108. When initializing an encoder you must specify a config which is initialized with
  2109. `ma_encoder_config_init()`. Here you must specify the file type, the output sample format, output
  2110. channel count and output sample rate. The following file types are supported:
  2111. +------------------------+-------------+
  2112. | Enum | Description |
  2113. +------------------------+-------------+
  2114. | ma_encoding_format_wav | WAV |
  2115. +------------------------+-------------+
  2116. If the format, channel count or sample rate is not supported by the output file type an error will
  2117. be returned. The encoder will not perform data conversion so you will need to convert it before
  2118. outputting any audio data. To output audio data, use `ma_encoder_write_pcm_frames()`, like in the
  2119. example below:
  2120. ```c
  2121. framesWritten = ma_encoder_write_pcm_frames(&encoder, pPCMFramesToWrite, framesToWrite);
  2122. ```
  2123. Encoders must be uninitialized with `ma_encoder_uninit()`.
  2124. 10. Data Conversion
  2125. ===================
  2126. A data conversion API is included with miniaudio which supports the majority of data conversion
  2127. requirements. This supports conversion between sample formats, channel counts (with channel
  2128. mapping) and sample rates.
  2129. 10.1. Sample Format Conversion
  2130. ------------------------------
  2131. Conversion between sample formats is achieved with the `ma_pcm_*_to_*()`, `ma_pcm_convert()` and
  2132. `ma_convert_pcm_frames_format()` APIs. Use `ma_pcm_*_to_*()` to convert between two specific
  2133. formats. Use `ma_pcm_convert()` to convert based on a `ma_format` variable. Use
  2134. `ma_convert_pcm_frames_format()` to convert PCM frames where you want to specify the frame count
  2135. and channel count as a variable instead of the total sample count.
  2136. 10.1.1. Dithering
  2137. -----------------
  2138. Dithering can be set using the ditherMode parameter.
  2139. The different dithering modes include the following, in order of efficiency:
  2140. +-----------+--------------------------+
  2141. | Type | Enum Token |
  2142. +-----------+--------------------------+
  2143. | None | ma_dither_mode_none |
  2144. | Rectangle | ma_dither_mode_rectangle |
  2145. | Triangle | ma_dither_mode_triangle |
  2146. +-----------+--------------------------+
  2147. Note that even if the dither mode is set to something other than `ma_dither_mode_none`, it will be
  2148. ignored for conversions where dithering is not needed. Dithering is available for the following
  2149. conversions:
  2150. ```
  2151. s16 -> u8
  2152. s24 -> u8
  2153. s32 -> u8
  2154. f32 -> u8
  2155. s24 -> s16
  2156. s32 -> s16
  2157. f32 -> s16
  2158. ```
  2159. Note that it is not an error to pass something other than ma_dither_mode_none for conversions where
  2160. dither is not used. It will just be ignored.
  2161. 10.2. Channel Conversion
  2162. ------------------------
  2163. Channel conversion is used for channel rearrangement and conversion from one channel count to
  2164. another. The `ma_channel_converter` API is used for channel conversion. Below is an example of
  2165. initializing a simple channel converter which converts from mono to stereo.
  2166. ```c
  2167. ma_channel_converter_config config = ma_channel_converter_config_init(
  2168. ma_format, // Sample format
  2169. 1, // Input channels
  2170. NULL, // Input channel map
  2171. 2, // Output channels
  2172. NULL, // Output channel map
  2173. ma_channel_mix_mode_default); // The mixing algorithm to use when combining channels.
  2174. result = ma_channel_converter_init(&config, NULL, &converter);
  2175. if (result != MA_SUCCESS) {
  2176. // Error.
  2177. }
  2178. ```
  2179. To perform the conversion simply call `ma_channel_converter_process_pcm_frames()` like so:
  2180. ```c
  2181. ma_result result = ma_channel_converter_process_pcm_frames(&converter, pFramesOut, pFramesIn, frameCount);
  2182. if (result != MA_SUCCESS) {
  2183. // Error.
  2184. }
  2185. ```
  2186. It is up to the caller to ensure the output buffer is large enough to accomodate the new PCM
  2187. frames.
  2188. Input and output PCM frames are always interleaved. Deinterleaved layouts are not supported.
  2189. 10.2.1. Channel Mapping
  2190. -----------------------
  2191. In addition to converting from one channel count to another, like the example above, the channel
  2192. converter can also be used to rearrange channels. When initializing the channel converter, you can
  2193. optionally pass in channel maps for both the input and output frames. If the channel counts are the
  2194. same, and each channel map contains the same channel positions with the exception that they're in
  2195. a different order, a simple shuffling of the channels will be performed. If, however, there is not
  2196. a 1:1 mapping of channel positions, or the channel counts differ, the input channels will be mixed
  2197. based on a mixing mode which is specified when initializing the `ma_channel_converter_config`
  2198. object.
  2199. When converting from mono to multi-channel, the mono channel is simply copied to each output
  2200. channel. When going the other way around, the audio of each output channel is simply averaged and
  2201. copied to the mono channel.
  2202. In more complicated cases blending is used. The `ma_channel_mix_mode_simple` mode will drop excess
  2203. channels and silence extra channels. For example, converting from 4 to 2 channels, the 3rd and 4th
  2204. channels will be dropped, whereas converting from 2 to 4 channels will put silence into the 3rd and
  2205. 4th channels.
  2206. The `ma_channel_mix_mode_rectangle` mode uses spacial locality based on a rectangle to compute a
  2207. simple distribution between input and output. Imagine sitting in the middle of a room, with
  2208. speakers on the walls representing channel positions. The `MA_CHANNEL_FRONT_LEFT` position can be
  2209. thought of as being in the corner of the front and left walls.
  2210. Finally, the `ma_channel_mix_mode_custom_weights` mode can be used to use custom user-defined
  2211. weights. Custom weights can be passed in as the last parameter of
  2212. `ma_channel_converter_config_init()`.
  2213. Predefined channel maps can be retrieved with `ma_channel_map_init_standard()`. This takes a
  2214. `ma_standard_channel_map` enum as it's first parameter, which can be one of the following:
  2215. +-----------------------------------+-----------------------------------------------------------+
  2216. | Name | Description |
  2217. +-----------------------------------+-----------------------------------------------------------+
  2218. | ma_standard_channel_map_default | Default channel map used by miniaudio. See below. |
  2219. | ma_standard_channel_map_microsoft | Channel map used by Microsoft's bitfield channel maps. |
  2220. | ma_standard_channel_map_alsa | Default ALSA channel map. |
  2221. | ma_standard_channel_map_rfc3551 | RFC 3551. Based on AIFF. |
  2222. | ma_standard_channel_map_flac | FLAC channel map. |
  2223. | ma_standard_channel_map_vorbis | Vorbis channel map. |
  2224. | ma_standard_channel_map_sound4 | FreeBSD's sound(4). |
  2225. | ma_standard_channel_map_sndio | sndio channel map. http://www.sndio.org/tips.html. |
  2226. | ma_standard_channel_map_webaudio | https://webaudio.github.io/web-audio-api/#ChannelOrdering |
  2227. +-----------------------------------+-----------------------------------------------------------+
  2228. Below are the channel maps used by default in miniaudio (`ma_standard_channel_map_default`):
  2229. +---------------+---------------------------------+
  2230. | Channel Count | Mapping |
  2231. +---------------+---------------------------------+
  2232. | 1 (Mono) | 0: MA_CHANNEL_MONO |
  2233. +---------------+---------------------------------+
  2234. | 2 (Stereo) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2235. | | 1: MA_CHANNEL_FRONT_RIGHT |
  2236. +---------------+---------------------------------+
  2237. | 3 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2238. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2239. | | 2: MA_CHANNEL_FRONT_CENTER |
  2240. +---------------+---------------------------------+
  2241. | 4 (Surround) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2242. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2243. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2244. | | 3: MA_CHANNEL_BACK_CENTER |
  2245. +---------------+---------------------------------+
  2246. | 5 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2247. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2248. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2249. | | 3: MA_CHANNEL_BACK_LEFT <br> |
  2250. | | 4: MA_CHANNEL_BACK_RIGHT |
  2251. +---------------+---------------------------------+
  2252. | 6 (5.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2253. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2254. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2255. | | 3: MA_CHANNEL_LFE <br> |
  2256. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2257. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2258. +---------------+---------------------------------+
  2259. | 7 | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2260. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2261. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2262. | | 3: MA_CHANNEL_LFE <br> |
  2263. | | 4: MA_CHANNEL_BACK_CENTER <br> |
  2264. | | 4: MA_CHANNEL_SIDE_LEFT <br> |
  2265. | | 5: MA_CHANNEL_SIDE_RIGHT |
  2266. +---------------+---------------------------------+
  2267. | 8 (7.1) | 0: MA_CHANNEL_FRONT_LEFT <br> |
  2268. | | 1: MA_CHANNEL_FRONT_RIGHT <br> |
  2269. | | 2: MA_CHANNEL_FRONT_CENTER <br> |
  2270. | | 3: MA_CHANNEL_LFE <br> |
  2271. | | 4: MA_CHANNEL_BACK_LEFT <br> |
  2272. | | 5: MA_CHANNEL_BACK_RIGHT <br> |
  2273. | | 6: MA_CHANNEL_SIDE_LEFT <br> |
  2274. | | 7: MA_CHANNEL_SIDE_RIGHT |
  2275. +---------------+---------------------------------+
  2276. | Other | All channels set to 0. This |
  2277. | | is equivalent to the same |
  2278. | | mapping as the device. |
  2279. +---------------+---------------------------------+
  2280. 10.3. Resampling
  2281. ----------------
  2282. Resampling is achieved with the `ma_resampler` object. To create a resampler object, do something
  2283. like the following:
  2284. ```c
  2285. ma_resampler_config config = ma_resampler_config_init(
  2286. ma_format_s16,
  2287. channels,
  2288. sampleRateIn,
  2289. sampleRateOut,
  2290. ma_resample_algorithm_linear);
  2291. ma_resampler resampler;
  2292. ma_result result = ma_resampler_init(&config, &resampler);
  2293. if (result != MA_SUCCESS) {
  2294. // An error occurred...
  2295. }
  2296. ```
  2297. Do the following to uninitialize the resampler:
  2298. ```c
  2299. ma_resampler_uninit(&resampler);
  2300. ```
  2301. The following example shows how data can be processed
  2302. ```c
  2303. ma_uint64 frameCountIn = 1000;
  2304. ma_uint64 frameCountOut = 2000;
  2305. ma_result result = ma_resampler_process_pcm_frames(&resampler, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2306. if (result != MA_SUCCESS) {
  2307. // An error occurred...
  2308. }
  2309. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the
  2310. // number of output frames written.
  2311. ```
  2312. To initialize the resampler you first need to set up a config (`ma_resampler_config`) with
  2313. `ma_resampler_config_init()`. You need to specify the sample format you want to use, the number of
  2314. channels, the input and output sample rate, and the algorithm.
  2315. The sample format can be either `ma_format_s16` or `ma_format_f32`. If you need a different format
  2316. you will need to perform pre- and post-conversions yourself where necessary. Note that the format
  2317. is the same for both input and output. The format cannot be changed after initialization.
  2318. The resampler supports multiple channels and is always interleaved (both input and output). The
  2319. channel count cannot be changed after initialization.
  2320. The sample rates can be anything other than zero, and are always specified in hertz. They should be
  2321. set to something like 44100, etc. The sample rate is the only configuration property that can be
  2322. changed after initialization.
  2323. The miniaudio resampler has built-in support for the following algorithms:
  2324. +-----------+------------------------------+
  2325. | Algorithm | Enum Token |
  2326. +-----------+------------------------------+
  2327. | Linear | ma_resample_algorithm_linear |
  2328. | Custom | ma_resample_algorithm_custom |
  2329. +-----------+------------------------------+
  2330. The algorithm cannot be changed after initialization.
  2331. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2332. De-interleaved processing is not supported. To process frames, use
  2333. `ma_resampler_process_pcm_frames()`. On input, this function takes the number of output frames you
  2334. can fit in the output buffer and the number of input frames contained in the input buffer. On
  2335. output these variables contain the number of output frames that were written to the output buffer
  2336. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2337. input buffer in which case it will be treated as an infinitely large buffer of zeros. The output
  2338. buffer can also be NULL, in which case the processing will be treated as seek.
  2339. The sample rate can be changed dynamically on the fly. You can change this with explicit sample
  2340. rates with `ma_resampler_set_rate()` and also with a decimal ratio with
  2341. `ma_resampler_set_rate_ratio()`. The ratio is in/out.
  2342. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2343. number of frames. You can calculate this with `ma_resampler_get_required_input_frame_count()`.
  2344. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2345. number of input frames. You can do this with `ma_resampler_get_expected_output_frame_count()`.
  2346. Due to the nature of how resampling works, the resampler introduces some latency. This can be
  2347. retrieved in terms of both the input rate and the output rate with
  2348. `ma_resampler_get_input_latency()` and `ma_resampler_get_output_latency()`.
  2349. 10.3.1. Resampling Algorithms
  2350. -----------------------------
  2351. The choice of resampling algorithm depends on your situation and requirements.
  2352. 10.3.1.1. Linear Resampling
  2353. ---------------------------
  2354. The linear resampler is the fastest, but comes at the expense of poorer quality. There is, however,
  2355. some control over the quality of the linear resampler which may make it a suitable option depending
  2356. on your requirements.
  2357. The linear resampler performs low-pass filtering before or after downsampling or upsampling,
  2358. depending on the sample rates you're converting between. When decreasing the sample rate, the
  2359. low-pass filter will be applied before downsampling. When increasing the rate it will be performed
  2360. after upsampling. By default a fourth order low-pass filter will be applied. This can be configured
  2361. via the `lpfOrder` configuration variable. Setting this to 0 will disable filtering.
  2362. The low-pass filter has a cutoff frequency which defaults to half the sample rate of the lowest of
  2363. the input and output sample rates (Nyquist Frequency).
  2364. The API for the linear resampler is the same as the main resampler API, only it's called
  2365. `ma_linear_resampler`.
  2366. 10.3.2. Custom Resamplers
  2367. -------------------------
  2368. You can implement a custom resampler by using the `ma_resample_algorithm_custom` resampling
  2369. algorithm and setting a vtable in the resampler config:
  2370. ```c
  2371. ma_resampler_config config = ma_resampler_config_init(..., ma_resample_algorithm_custom);
  2372. config.pBackendVTable = &g_customResamplerVTable;
  2373. ```
  2374. Custom resamplers are useful if the stock algorithms are not appropriate for your use case. You
  2375. need to implement the required functions in `ma_resampling_backend_vtable`. Note that not all
  2376. functions in the vtable need to be implemented, but if it's possible to implement, they should be.
  2377. You can use the `ma_linear_resampler` object for an example on how to implement the vtable. The
  2378. `onGetHeapSize` callback is used to calculate the size of any internal heap allocation the custom
  2379. resampler will need to make given the supplied config. When you initialize the resampler via the
  2380. `onInit` callback, you'll be given a pointer to a heap allocation which is where you should store
  2381. the heap allocated data. You should not free this data in `onUninit` because miniaudio will manage
  2382. it for you.
  2383. The `onProcess` callback is where the actual resampling takes place. On input, `pFrameCountIn`
  2384. points to a variable containing the number of frames in the `pFramesIn` buffer and
  2385. `pFrameCountOut` points to a variable containing the capacity in frames of the `pFramesOut` buffer.
  2386. On output, `pFrameCountIn` should be set to the number of input frames that were fully consumed,
  2387. whereas `pFrameCountOut` should be set to the number of frames that were written to `pFramesOut`.
  2388. The `onSetRate` callback is optional and is used for dynamically changing the sample rate. If
  2389. dynamic rate changes are not supported, you can set this callback to NULL.
  2390. The `onGetInputLatency` and `onGetOutputLatency` functions are used for retrieving the latency in
  2391. input and output rates respectively. These can be NULL in which case latency calculations will be
  2392. assumed to be NULL.
  2393. The `onGetRequiredInputFrameCount` callback is used to give miniaudio a hint as to how many input
  2394. frames are required to be available to produce the given number of output frames. Likewise, the
  2395. `onGetExpectedOutputFrameCount` callback is used to determine how many output frames will be
  2396. produced given the specified number of input frames. miniaudio will use these as a hint, but they
  2397. are optional and can be set to NULL if you're unable to implement them.
  2398. 10.4. General Data Conversion
  2399. -----------------------------
  2400. The `ma_data_converter` API can be used to wrap sample format conversion, channel conversion and
  2401. resampling into one operation. This is what miniaudio uses internally to convert between the format
  2402. requested when the device was initialized and the format of the backend's native device. The API
  2403. for general data conversion is very similar to the resampling API. Create a `ma_data_converter`
  2404. object like this:
  2405. ```c
  2406. ma_data_converter_config config = ma_data_converter_config_init(
  2407. inputFormat,
  2408. outputFormat,
  2409. inputChannels,
  2410. outputChannels,
  2411. inputSampleRate,
  2412. outputSampleRate
  2413. );
  2414. ma_data_converter converter;
  2415. ma_result result = ma_data_converter_init(&config, NULL, &converter);
  2416. if (result != MA_SUCCESS) {
  2417. // An error occurred...
  2418. }
  2419. ```
  2420. In the example above we use `ma_data_converter_config_init()` to initialize the config, however
  2421. there's many more properties that can be configured, such as channel maps and resampling quality.
  2422. Something like the following may be more suitable depending on your requirements:
  2423. ```c
  2424. ma_data_converter_config config = ma_data_converter_config_init_default();
  2425. config.formatIn = inputFormat;
  2426. config.formatOut = outputFormat;
  2427. config.channelsIn = inputChannels;
  2428. config.channelsOut = outputChannels;
  2429. config.sampleRateIn = inputSampleRate;
  2430. config.sampleRateOut = outputSampleRate;
  2431. ma_channel_map_init_standard(ma_standard_channel_map_flac, config.channelMapIn, sizeof(config.channelMapIn)/sizeof(config.channelMapIn[0]), config.channelCountIn);
  2432. config.resampling.linear.lpfOrder = MA_MAX_FILTER_ORDER;
  2433. ```
  2434. Do the following to uninitialize the data converter:
  2435. ```c
  2436. ma_data_converter_uninit(&converter, NULL);
  2437. ```
  2438. The following example shows how data can be processed
  2439. ```c
  2440. ma_uint64 frameCountIn = 1000;
  2441. ma_uint64 frameCountOut = 2000;
  2442. ma_result result = ma_data_converter_process_pcm_frames(&converter, pFramesIn, &frameCountIn, pFramesOut, &frameCountOut);
  2443. if (result != MA_SUCCESS) {
  2444. // An error occurred...
  2445. }
  2446. // At this point, frameCountIn contains the number of input frames that were consumed and frameCountOut contains the number
  2447. // of output frames written.
  2448. ```
  2449. The data converter supports multiple channels and is always interleaved (both input and output).
  2450. The channel count cannot be changed after initialization.
  2451. Sample rates can be anything other than zero, and are always specified in hertz. They should be set
  2452. to something like 44100, etc. The sample rate is the only configuration property that can be
  2453. changed after initialization, but only if the `resampling.allowDynamicSampleRate` member of
  2454. `ma_data_converter_config` is set to `MA_TRUE`. To change the sample rate, use
  2455. `ma_data_converter_set_rate()` or `ma_data_converter_set_rate_ratio()`. The ratio must be in/out.
  2456. The resampling algorithm cannot be changed after initialization.
  2457. Processing always happens on a per PCM frame basis and always assumes interleaved input and output.
  2458. De-interleaved processing is not supported. To process frames, use
  2459. `ma_data_converter_process_pcm_frames()`. On input, this function takes the number of output frames
  2460. you can fit in the output buffer and the number of input frames contained in the input buffer. On
  2461. output these variables contain the number of output frames that were written to the output buffer
  2462. and the number of input frames that were consumed in the process. You can pass in NULL for the
  2463. input buffer in which case it will be treated as an infinitely large
  2464. buffer of zeros. The output buffer can also be NULL, in which case the processing will be treated
  2465. as seek.
  2466. Sometimes it's useful to know exactly how many input frames will be required to output a specific
  2467. number of frames. You can calculate this with `ma_data_converter_get_required_input_frame_count()`.
  2468. Likewise, it's sometimes useful to know exactly how many frames would be output given a certain
  2469. number of input frames. You can do this with `ma_data_converter_get_expected_output_frame_count()`.
  2470. Due to the nature of how resampling works, the data converter introduces some latency if resampling
  2471. is required. This can be retrieved in terms of both the input rate and the output rate with
  2472. `ma_data_converter_get_input_latency()` and `ma_data_converter_get_output_latency()`.
  2473. 11. Filtering
  2474. =============
  2475. 11.1. Biquad Filtering
  2476. ----------------------
  2477. Biquad filtering is achieved with the `ma_biquad` API. Example:
  2478. ```c
  2479. ma_biquad_config config = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  2480. ma_result result = ma_biquad_init(&config, &biquad);
  2481. if (result != MA_SUCCESS) {
  2482. // Error.
  2483. }
  2484. ...
  2485. ma_biquad_process_pcm_frames(&biquad, pFramesOut, pFramesIn, frameCount);
  2486. ```
  2487. Biquad filtering is implemented using transposed direct form 2. The numerator coefficients are b0,
  2488. b1 and b2, and the denominator coefficients are a0, a1 and a2. The a0 coefficient is required and
  2489. coefficients must not be pre-normalized.
  2490. Supported formats are `ma_format_s16` and `ma_format_f32`. If you need to use a different format
  2491. you need to convert it yourself beforehand. When using `ma_format_s16` the biquad filter will use
  2492. fixed point arithmetic. When using `ma_format_f32`, floating point arithmetic will be used.
  2493. Input and output frames are always interleaved.
  2494. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2495. buffers, like so:
  2496. ```c
  2497. ma_biquad_process_pcm_frames(&biquad, pMyData, pMyData, frameCount);
  2498. ```
  2499. If you need to change the values of the coefficients, but maintain the values in the registers you
  2500. can do so with `ma_biquad_reinit()`. This is useful if you need to change the properties of the
  2501. filter while keeping the values of registers valid to avoid glitching. Do not use
  2502. `ma_biquad_init()` for this as it will do a full initialization which involves clearing the
  2503. registers to 0. Note that changing the format or channel count after initialization is invalid and
  2504. will result in an error.
  2505. 11.2. Low-Pass Filtering
  2506. ------------------------
  2507. Low-pass filtering is achieved with the following APIs:
  2508. +---------+------------------------------------------+
  2509. | API | Description |
  2510. +---------+------------------------------------------+
  2511. | ma_lpf1 | First order low-pass filter |
  2512. | ma_lpf2 | Second order low-pass filter |
  2513. | ma_lpf | High order low-pass filter (Butterworth) |
  2514. +---------+------------------------------------------+
  2515. Low-pass filter example:
  2516. ```c
  2517. ma_lpf_config config = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  2518. ma_result result = ma_lpf_init(&config, &lpf);
  2519. if (result != MA_SUCCESS) {
  2520. // Error.
  2521. }
  2522. ...
  2523. ma_lpf_process_pcm_frames(&lpf, pFramesOut, pFramesIn, frameCount);
  2524. ```
  2525. Supported formats are `ma_format_s16` and` ma_format_f32`. If you need to use a different format
  2526. you need to convert it yourself beforehand. Input and output frames are always interleaved.
  2527. Filtering can be applied in-place by passing in the same pointer for both the input and output
  2528. buffers, like so:
  2529. ```c
  2530. ma_lpf_process_pcm_frames(&lpf, pMyData, pMyData, frameCount);
  2531. ```
  2532. The maximum filter order is limited to `MA_MAX_FILTER_ORDER` which is set to 8. If you need more,
  2533. you can chain first and second order filters together.
  2534. ```c
  2535. for (iFilter = 0; iFilter < filterCount; iFilter += 1) {
  2536. ma_lpf2_process_pcm_frames(&lpf2[iFilter], pMyData, pMyData, frameCount);
  2537. }
  2538. ```
  2539. If you need to change the configuration of the filter, but need to maintain the state of internal
  2540. registers you can do so with `ma_lpf_reinit()`. This may be useful if you need to change the sample
  2541. rate and/or cutoff frequency dynamically while maintaing smooth transitions. Note that changing the
  2542. format or channel count after initialization is invalid and will result in an error.
  2543. The `ma_lpf` object supports a configurable order, but if you only need a first order filter you
  2544. may want to consider using `ma_lpf1`. Likewise, if you only need a second order filter you can use
  2545. `ma_lpf2`. The advantage of this is that they're lighter weight and a bit more efficient.
  2546. If an even filter order is specified, a series of second order filters will be processed in a
  2547. chain. If an odd filter order is specified, a first order filter will be applied, followed by a
  2548. series of second order filters in a chain.
  2549. 11.3. High-Pass Filtering
  2550. -------------------------
  2551. High-pass filtering is achieved with the following APIs:
  2552. +---------+-------------------------------------------+
  2553. | API | Description |
  2554. +---------+-------------------------------------------+
  2555. | ma_hpf1 | First order high-pass filter |
  2556. | ma_hpf2 | Second order high-pass filter |
  2557. | ma_hpf | High order high-pass filter (Butterworth) |
  2558. +---------+-------------------------------------------+
  2559. High-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_hpf1`,
  2560. `ma_hpf2` and `ma_hpf`. See example code for low-pass filters for example usage.
  2561. 11.4. Band-Pass Filtering
  2562. -------------------------
  2563. Band-pass filtering is achieved with the following APIs:
  2564. +---------+-------------------------------+
  2565. | API | Description |
  2566. +---------+-------------------------------+
  2567. | ma_bpf2 | Second order band-pass filter |
  2568. | ma_bpf | High order band-pass filter |
  2569. +---------+-------------------------------+
  2570. Band-pass filters work exactly the same as low-pass filters, only the APIs are called `ma_bpf2` and
  2571. `ma_hpf`. See example code for low-pass filters for example usage. Note that the order for
  2572. band-pass filters must be an even number which means there is no first order band-pass filter,
  2573. unlike low-pass and high-pass filters.
  2574. 11.5. Notch Filtering
  2575. ---------------------
  2576. Notch filtering is achieved with the following APIs:
  2577. +-----------+------------------------------------------+
  2578. | API | Description |
  2579. +-----------+------------------------------------------+
  2580. | ma_notch2 | Second order notching filter |
  2581. +-----------+------------------------------------------+
  2582. 11.6. Peaking EQ Filtering
  2583. -------------------------
  2584. Peaking filtering is achieved with the following APIs:
  2585. +----------+------------------------------------------+
  2586. | API | Description |
  2587. +----------+------------------------------------------+
  2588. | ma_peak2 | Second order peaking filter |
  2589. +----------+------------------------------------------+
  2590. 11.7. Low Shelf Filtering
  2591. -------------------------
  2592. Low shelf filtering is achieved with the following APIs:
  2593. +-------------+------------------------------------------+
  2594. | API | Description |
  2595. +-------------+------------------------------------------+
  2596. | ma_loshelf2 | Second order low shelf filter |
  2597. +-------------+------------------------------------------+
  2598. Where a high-pass filter is used to eliminate lower frequencies, a low shelf filter can be used to
  2599. just turn them down rather than eliminate them entirely.
  2600. 11.8. High Shelf Filtering
  2601. --------------------------
  2602. High shelf filtering is achieved with the following APIs:
  2603. +-------------+------------------------------------------+
  2604. | API | Description |
  2605. +-------------+------------------------------------------+
  2606. | ma_hishelf2 | Second order high shelf filter |
  2607. +-------------+------------------------------------------+
  2608. The high shelf filter has the same API as the low shelf filter, only you would use `ma_hishelf`
  2609. instead of `ma_loshelf`. Where a low shelf filter is used to adjust the volume of low frequencies,
  2610. the high shelf filter does the same thing for high frequencies.
  2611. 12. Waveform and Noise Generation
  2612. =================================
  2613. 12.1. Waveforms
  2614. ---------------
  2615. miniaudio supports generation of sine, square, triangle and sawtooth waveforms. This is achieved
  2616. with the `ma_waveform` API. Example:
  2617. ```c
  2618. ma_waveform_config config = ma_waveform_config_init(
  2619. FORMAT,
  2620. CHANNELS,
  2621. SAMPLE_RATE,
  2622. ma_waveform_type_sine,
  2623. amplitude,
  2624. frequency);
  2625. ma_waveform waveform;
  2626. ma_result result = ma_waveform_init(&config, &waveform);
  2627. if (result != MA_SUCCESS) {
  2628. // Error.
  2629. }
  2630. ...
  2631. ma_waveform_read_pcm_frames(&waveform, pOutput, frameCount);
  2632. ```
  2633. The amplitude, frequency, type, and sample rate can be changed dynamically with
  2634. `ma_waveform_set_amplitude()`, `ma_waveform_set_frequency()`, `ma_waveform_set_type()`, and
  2635. `ma_waveform_set_sample_rate()` respectively.
  2636. You can invert the waveform by setting the amplitude to a negative value. You can use this to
  2637. control whether or not a sawtooth has a positive or negative ramp, for example.
  2638. Below are the supported waveform types:
  2639. +---------------------------+
  2640. | Enum Name |
  2641. +---------------------------+
  2642. | ma_waveform_type_sine |
  2643. | ma_waveform_type_square |
  2644. | ma_waveform_type_triangle |
  2645. | ma_waveform_type_sawtooth |
  2646. +---------------------------+
  2647. 12.2. Noise
  2648. -----------
  2649. miniaudio supports generation of white, pink and Brownian noise via the `ma_noise` API. Example:
  2650. ```c
  2651. ma_noise_config config = ma_noise_config_init(
  2652. FORMAT,
  2653. CHANNELS,
  2654. ma_noise_type_white,
  2655. SEED,
  2656. amplitude);
  2657. ma_noise noise;
  2658. ma_result result = ma_noise_init(&config, &noise);
  2659. if (result != MA_SUCCESS) {
  2660. // Error.
  2661. }
  2662. ...
  2663. ma_noise_read_pcm_frames(&noise, pOutput, frameCount);
  2664. ```
  2665. The noise API uses simple LCG random number generation. It supports a custom seed which is useful
  2666. for things like automated testing requiring reproducibility. Setting the seed to zero will default
  2667. to `MA_DEFAULT_LCG_SEED`.
  2668. The amplitude, seed, and type can be changed dynamically with `ma_noise_set_amplitude()`,
  2669. `ma_noise_set_seed()`, and `ma_noise_set_type()` respectively.
  2670. By default, the noise API will use different values for different channels. So, for example, the
  2671. left side in a stereo stream will be different to the right side. To instead have each channel use
  2672. the same random value, set the `duplicateChannels` member of the noise config to true, like so:
  2673. ```c
  2674. config.duplicateChannels = MA_TRUE;
  2675. ```
  2676. Below are the supported noise types.
  2677. +------------------------+
  2678. | Enum Name |
  2679. +------------------------+
  2680. | ma_noise_type_white |
  2681. | ma_noise_type_pink |
  2682. | ma_noise_type_brownian |
  2683. +------------------------+
  2684. 13. Audio Buffers
  2685. =================
  2686. miniaudio supports reading from a buffer of raw audio data via the `ma_audio_buffer` API. This can
  2687. read from memory that's managed by the application, but can also handle the memory management for
  2688. you internally. Memory management is flexible and should support most use cases.
  2689. Audio buffers are initialised using the standard configuration system used everywhere in miniaudio:
  2690. ```c
  2691. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2692. format,
  2693. channels,
  2694. sizeInFrames,
  2695. pExistingData,
  2696. &allocationCallbacks);
  2697. ma_audio_buffer buffer;
  2698. result = ma_audio_buffer_init(&config, &buffer);
  2699. if (result != MA_SUCCESS) {
  2700. // Error.
  2701. }
  2702. ...
  2703. ma_audio_buffer_uninit(&buffer);
  2704. ```
  2705. In the example above, the memory pointed to by `pExistingData` will *not* be copied and is how an
  2706. application can do self-managed memory allocation. If you would rather make a copy of the data, use
  2707. `ma_audio_buffer_init_copy()`. To uninitialize the buffer, use `ma_audio_buffer_uninit()`.
  2708. Sometimes it can be convenient to allocate the memory for the `ma_audio_buffer` structure and the
  2709. raw audio data in a contiguous block of memory. That is, the raw audio data will be located
  2710. immediately after the `ma_audio_buffer` structure. To do this, use
  2711. `ma_audio_buffer_alloc_and_init()`:
  2712. ```c
  2713. ma_audio_buffer_config config = ma_audio_buffer_config_init(
  2714. format,
  2715. channels,
  2716. sizeInFrames,
  2717. pExistingData,
  2718. &allocationCallbacks);
  2719. ma_audio_buffer* pBuffer
  2720. result = ma_audio_buffer_alloc_and_init(&config, &pBuffer);
  2721. if (result != MA_SUCCESS) {
  2722. // Error
  2723. }
  2724. ...
  2725. ma_audio_buffer_uninit_and_free(&buffer);
  2726. ```
  2727. If you initialize the buffer with `ma_audio_buffer_alloc_and_init()` you should uninitialize it
  2728. with `ma_audio_buffer_uninit_and_free()`. In the example above, the memory pointed to by
  2729. `pExistingData` will be copied into the buffer, which is contrary to the behavior of
  2730. `ma_audio_buffer_init()`.
  2731. An audio buffer has a playback cursor just like a decoder. As you read frames from the buffer, the
  2732. cursor moves forward. The last parameter (`loop`) can be used to determine if the buffer should
  2733. loop. The return value is the number of frames actually read. If this is less than the number of
  2734. frames requested it means the end has been reached. This should never happen if the `loop`
  2735. parameter is set to true. If you want to manually loop back to the start, you can do so with with
  2736. `ma_audio_buffer_seek_to_pcm_frame(pAudioBuffer, 0)`. Below is an example for reading data from an
  2737. audio buffer.
  2738. ```c
  2739. ma_uint64 framesRead = ma_audio_buffer_read_pcm_frames(pAudioBuffer, pFramesOut, desiredFrameCount, isLooping);
  2740. if (framesRead < desiredFrameCount) {
  2741. // If not looping, this means the end has been reached. This should never happen in looping mode with valid input.
  2742. }
  2743. ```
  2744. Sometimes you may want to avoid the cost of data movement between the internal buffer and the
  2745. output buffer. Instead you can use memory mapping to retrieve a pointer to a segment of data:
  2746. ```c
  2747. void* pMappedFrames;
  2748. ma_uint64 frameCount = frameCountToTryMapping;
  2749. ma_result result = ma_audio_buffer_map(pAudioBuffer, &pMappedFrames, &frameCount);
  2750. if (result == MA_SUCCESS) {
  2751. // Map was successful. The value in frameCount will be how many frames were _actually_ mapped, which may be
  2752. // less due to the end of the buffer being reached.
  2753. ma_copy_pcm_frames(pFramesOut, pMappedFrames, frameCount, pAudioBuffer->format, pAudioBuffer->channels);
  2754. // You must unmap the buffer.
  2755. ma_audio_buffer_unmap(pAudioBuffer, frameCount);
  2756. }
  2757. ```
  2758. When you use memory mapping, the read cursor is increment by the frame count passed in to
  2759. `ma_audio_buffer_unmap()`. If you decide not to process every frame you can pass in a value smaller
  2760. than the value returned by `ma_audio_buffer_map()`. The disadvantage to using memory mapping is
  2761. that it does not handle looping for you. You can determine if the buffer is at the end for the
  2762. purpose of looping with `ma_audio_buffer_at_end()` or by inspecting the return value of
  2763. `ma_audio_buffer_unmap()` and checking if it equals `MA_AT_END`. You should not treat `MA_AT_END`
  2764. as an error when returned by `ma_audio_buffer_unmap()`.
  2765. 14. Ring Buffers
  2766. ================
  2767. miniaudio supports lock free (single producer, single consumer) ring buffers which are exposed via
  2768. the `ma_rb` and `ma_pcm_rb` APIs. The `ma_rb` API operates on bytes, whereas the `ma_pcm_rb`
  2769. operates on PCM frames. They are otherwise identical as `ma_pcm_rb` is just a wrapper around
  2770. `ma_rb`.
  2771. Unlike most other APIs in miniaudio, ring buffers support both interleaved and deinterleaved
  2772. streams. The caller can also allocate their own backing memory for the ring buffer to use
  2773. internally for added flexibility. Otherwise the ring buffer will manage it's internal memory for
  2774. you.
  2775. The examples below use the PCM frame variant of the ring buffer since that's most likely the one
  2776. you will want to use. To initialize a ring buffer, do something like the following:
  2777. ```c
  2778. ma_pcm_rb rb;
  2779. ma_result result = ma_pcm_rb_init(FORMAT, CHANNELS, BUFFER_SIZE_IN_FRAMES, NULL, NULL, &rb);
  2780. if (result != MA_SUCCESS) {
  2781. // Error
  2782. }
  2783. ```
  2784. The `ma_pcm_rb_init()` function takes the sample format and channel count as parameters because
  2785. it's the PCM varient of the ring buffer API. For the regular ring buffer that operates on bytes you
  2786. would call `ma_rb_init()` which leaves these out and just takes the size of the buffer in bytes
  2787. instead of frames. The fourth parameter is an optional pre-allocated buffer and the fifth parameter
  2788. is a pointer to a `ma_allocation_callbacks` structure for custom memory allocation routines.
  2789. Passing in `NULL` for this results in `MA_MALLOC()` and `MA_FREE()` being used.
  2790. Use `ma_pcm_rb_init_ex()` if you need a deinterleaved buffer. The data for each sub-buffer is
  2791. offset from each other based on the stride. To manage your sub-buffers you can use
  2792. `ma_pcm_rb_get_subbuffer_stride()`, `ma_pcm_rb_get_subbuffer_offset()` and
  2793. `ma_pcm_rb_get_subbuffer_ptr()`.
  2794. Use `ma_pcm_rb_acquire_read()` and `ma_pcm_rb_acquire_write()` to retrieve a pointer to a section
  2795. of the ring buffer. You specify the number of frames you need, and on output it will set to what
  2796. was actually acquired. If the read or write pointer is positioned such that the number of frames
  2797. requested will require a loop, it will be clamped to the end of the buffer. Therefore, the number
  2798. of frames you're given may be less than the number you requested.
  2799. After calling `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()`, you do your work on the
  2800. buffer and then "commit" it with `ma_pcm_rb_commit_read()` or `ma_pcm_rb_commit_write()`. This is
  2801. where the read/write pointers are updated. When you commit you need to pass in the buffer that was
  2802. returned by the earlier call to `ma_pcm_rb_acquire_read()` or `ma_pcm_rb_acquire_write()` and is
  2803. only used for validation. The number of frames passed to `ma_pcm_rb_commit_read()` and
  2804. `ma_pcm_rb_commit_write()` is what's used to increment the pointers, and can be less that what was
  2805. originally requested.
  2806. If you want to correct for drift between the write pointer and the read pointer you can use a
  2807. combination of `ma_pcm_rb_pointer_distance()`, `ma_pcm_rb_seek_read()` and
  2808. `ma_pcm_rb_seek_write()`. Note that you can only move the pointers forward, and you should only
  2809. move the read pointer forward via the consumer thread, and the write pointer forward by the
  2810. producer thread. If there is too much space between the pointers, move the read pointer forward. If
  2811. there is too little space between the pointers, move the write pointer forward.
  2812. You can use a ring buffer at the byte level instead of the PCM frame level by using the `ma_rb`
  2813. API. This is exactly the same, only you will use the `ma_rb` functions instead of `ma_pcm_rb` and
  2814. instead of frame counts you will pass around byte counts.
  2815. The maximum size of the buffer in bytes is `0x7FFFFFFF-(MA_SIMD_ALIGNMENT-1)` due to the most
  2816. significant bit being used to encode a loop flag and the internally managed buffers always being
  2817. aligned to `MA_SIMD_ALIGNMENT`.
  2818. Note that the ring buffer is only thread safe when used by a single consumer thread and single
  2819. producer thread.
  2820. 15. Backends
  2821. ============
  2822. The following backends are supported by miniaudio. These are listed in order of default priority.
  2823. When no backend is specified when initializing a context or device, miniaudio will attempt to use
  2824. each of these backends in the order listed in the table below.
  2825. Note that backends that are not usable by the build target will not be included in the build. For
  2826. example, ALSA, which is specific to Linux, will not be included in the Windows build.
  2827. +-------------+-----------------------+--------------------------------------------------------+
  2828. | Name | Enum Name | Supported Operating Systems |
  2829. +-------------+-----------------------+--------------------------------------------------------+
  2830. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  2831. | DirectSound | ma_backend_dsound | Windows XP+ |
  2832. | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
  2833. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  2834. | sndio | ma_backend_sndio | OpenBSD |
  2835. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  2836. | OSS | ma_backend_oss | FreeBSD |
  2837. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  2838. | ALSA | ma_backend_alsa | Linux |
  2839. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  2840. | AAudio | ma_backend_aaudio | Android 8+ |
  2841. | OpenSL ES | ma_backend_opensl | Android (API level 16+) |
  2842. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  2843. | Custom | ma_backend_custom | Cross Platform |
  2844. | Null | ma_backend_null | Cross Platform (not used on Web) |
  2845. +-------------+-----------------------+--------------------------------------------------------+
  2846. Some backends have some nuance details you may want to be aware of.
  2847. 15.1. WASAPI
  2848. ------------
  2849. - Low-latency shared mode will be disabled when using an application-defined sample rate which is
  2850. different to the device's native sample rate. To work around this, set `wasapi.noAutoConvertSRC`
  2851. to true in the device config. This is due to IAudioClient3_InitializeSharedAudioStream() failing
  2852. when the `AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM` flag is specified. Setting wasapi.noAutoConvertSRC
  2853. will result in miniaudio's internal resampler being used instead which will in turn enable the
  2854. use of low-latency shared mode.
  2855. 15.2. PulseAudio
  2856. ----------------
  2857. - If you experience bad glitching/noise on Arch Linux, consider this fix from the Arch wiki:
  2858. https://wiki.archlinux.org/index.php/PulseAudio/Troubleshooting#Glitches,_skips_or_crackling.
  2859. Alternatively, consider using a different backend such as ALSA.
  2860. 15.3. Android
  2861. -------------
  2862. - To capture audio on Android, remember to add the RECORD_AUDIO permission to your manifest:
  2863. `<uses-permission android:name="android.permission.RECORD_AUDIO" />`
  2864. - With OpenSL|ES, only a single ma_context can be active at any given time. This is due to a
  2865. limitation with OpenSL|ES.
  2866. - With AAudio, only default devices are enumerated. This is due to AAudio not having an enumeration
  2867. API (devices are enumerated through Java). You can however perform your own device enumeration
  2868. through Java and then set the ID in the ma_device_id structure (ma_device_id.aaudio) and pass it
  2869. to ma_device_init().
  2870. - The backend API will perform resampling where possible. The reason for this as opposed to using
  2871. miniaudio's built-in resampler is to take advantage of any potential device-specific
  2872. optimizations the driver may implement.
  2873. 15.4. UWP
  2874. ---------
  2875. - UWP only supports default playback and capture devices.
  2876. - UWP requires the Microphone capability to be enabled in the application's manifest (Package.appxmanifest):
  2877. ```
  2878. <Package ...>
  2879. ...
  2880. <Capabilities>
  2881. <DeviceCapability Name="microphone" />
  2882. </Capabilities>
  2883. </Package>
  2884. ```
  2885. 15.5. Web Audio / Emscripten
  2886. ----------------------------
  2887. - You cannot use `-std=c*` compiler flags, nor `-ansi`. This only applies to the Emscripten build.
  2888. - The first time a context is initialized it will create a global object called "miniaudio" whose
  2889. primary purpose is to act as a factory for device objects.
  2890. - Currently the Web Audio backend uses ScriptProcessorNode's, but this may need to change later as
  2891. they've been deprecated.
  2892. - Google has implemented a policy in their browsers that prevent automatic media output without
  2893. first receiving some kind of user input. The following web page has additional details:
  2894. https://developers.google.com/web/updates/2017/09/autoplay-policy-changes. Starting the device
  2895. may fail if you try to start playback without first handling some kind of user input.
  2896. 16. Optimization Tips
  2897. =====================
  2898. 16.1. High Level API
  2899. --------------------
  2900. - If a sound does not require doppler or pitch shifting, consider disabling pitching by
  2901. initializing the sound with the `MA_SOUND_FLAG_NO_PITCH` flag.
  2902. - If a sound does not require spatialization, disable it by initialzing the sound with the
  2903. `MA_SOUND_FLAG_NO_SPATIALIZATION` flag. It can be renabled again post-initialization with
  2904. `ma_sound_set_spatialization_enabled()`.
  2905. 17. Miscellaneous Notes
  2906. =======================
  2907. - Automatic stream routing is enabled on a per-backend basis. Support is explicitly enabled for
  2908. WASAPI and Core Audio, however other backends such as PulseAudio may naturally support it, though
  2909. not all have been tested.
  2910. - The contents of the output buffer passed into the data callback will always be pre-initialized to
  2911. silence unless the `noPreSilencedOutputBuffer` config variable in `ma_device_config` is set to
  2912. true, in which case it'll be undefined which will require you to write something to the entire
  2913. buffer.
  2914. - By default miniaudio will automatically clip samples. This only applies when the playback sample
  2915. format is configured as `ma_format_f32`. If you are doing clipping yourself, you can disable this
  2916. overhead by setting `noClip` to true in the device config.
  2917. - Note that GCC and Clang requires `-msse2`, `-mavx2`, etc. for SIMD optimizations.
  2918. - The sndio backend is currently only enabled on OpenBSD builds.
  2919. - The audio(4) backend is supported on OpenBSD, but you may need to disable sndiod before you can
  2920. use it.
  2921. - When compiling with VC6 and earlier, decoding is restricted to files less than 2GB in size. This
  2922. is due to 64-bit file APIs not being available.
  2923. */
  2924. #ifndef miniaudio_h
  2925. #define miniaudio_h
  2926. #ifdef __cplusplus
  2927. extern "C" {
  2928. #endif
  2929. #define MA_STRINGIFY(x) #x
  2930. #define MA_XSTRINGIFY(x) MA_STRINGIFY(x)
  2931. #define MA_VERSION_MAJOR 0
  2932. #define MA_VERSION_MINOR 11
  2933. #define MA_VERSION_REVISION 11
  2934. #define MA_VERSION_STRING MA_XSTRINGIFY(MA_VERSION_MAJOR) "." MA_XSTRINGIFY(MA_VERSION_MINOR) "." MA_XSTRINGIFY(MA_VERSION_REVISION)
  2935. #if defined(_MSC_VER) && !defined(__clang__)
  2936. #pragma warning(push)
  2937. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  2938. #pragma warning(disable:4214) /* nonstandard extension used: bit field types other than int */
  2939. #pragma warning(disable:4324) /* structure was padded due to alignment specifier */
  2940. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  2941. #pragma GCC diagnostic push
  2942. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  2943. #if defined(__clang__)
  2944. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  2945. #endif
  2946. #endif
  2947. #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__)
  2948. #define MA_SIZEOF_PTR 8
  2949. #else
  2950. #define MA_SIZEOF_PTR 4
  2951. #endif
  2952. #include <stddef.h> /* For size_t. */
  2953. /* Sized types. */
  2954. #if defined(MA_USE_STDINT)
  2955. #include <stdint.h>
  2956. typedef int8_t ma_int8;
  2957. typedef uint8_t ma_uint8;
  2958. typedef int16_t ma_int16;
  2959. typedef uint16_t ma_uint16;
  2960. typedef int32_t ma_int32;
  2961. typedef uint32_t ma_uint32;
  2962. typedef int64_t ma_int64;
  2963. typedef uint64_t ma_uint64;
  2964. #else
  2965. typedef signed char ma_int8;
  2966. typedef unsigned char ma_uint8;
  2967. typedef signed short ma_int16;
  2968. typedef unsigned short ma_uint16;
  2969. typedef signed int ma_int32;
  2970. typedef unsigned int ma_uint32;
  2971. #if defined(_MSC_VER) && !defined(__clang__)
  2972. typedef signed __int64 ma_int64;
  2973. typedef unsigned __int64 ma_uint64;
  2974. #else
  2975. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  2976. #pragma GCC diagnostic push
  2977. #pragma GCC diagnostic ignored "-Wlong-long"
  2978. #if defined(__clang__)
  2979. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  2980. #endif
  2981. #endif
  2982. typedef signed long long ma_int64;
  2983. typedef unsigned long long ma_uint64;
  2984. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  2985. #pragma GCC diagnostic pop
  2986. #endif
  2987. #endif
  2988. #endif /* MA_USE_STDINT */
  2989. #if MA_SIZEOF_PTR == 8
  2990. typedef ma_uint64 ma_uintptr;
  2991. #else
  2992. typedef ma_uint32 ma_uintptr;
  2993. #endif
  2994. typedef ma_uint8 ma_bool8;
  2995. typedef ma_uint32 ma_bool32;
  2996. #define MA_TRUE 1
  2997. #define MA_FALSE 0
  2998. typedef void* ma_handle;
  2999. typedef void* ma_ptr;
  3000. typedef void (* ma_proc)(void);
  3001. #if defined(_MSC_VER) && !defined(_WCHAR_T_DEFINED)
  3002. typedef ma_uint16 wchar_t;
  3003. #endif
  3004. /* Define NULL for some compilers. */
  3005. #ifndef NULL
  3006. #define NULL 0
  3007. #endif
  3008. #if defined(SIZE_MAX)
  3009. #define MA_SIZE_MAX SIZE_MAX
  3010. #else
  3011. #define MA_SIZE_MAX 0xFFFFFFFF /* When SIZE_MAX is not defined by the standard library just default to the maximum 32-bit unsigned integer. */
  3012. #endif
  3013. /* Platform/backend detection. */
  3014. #ifdef _WIN32
  3015. #define MA_WIN32
  3016. #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)))
  3017. #define MA_WIN32_UWP
  3018. #elif defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_GAMES) && WINAPI_FAMILY == WINAPI_FAMILY_GAMES)
  3019. #define MA_WIN32_GDK
  3020. #else
  3021. #define MA_WIN32_DESKTOP
  3022. #endif
  3023. #else
  3024. #define MA_POSIX
  3025. /*
  3026. Use the MA_NO_PTHREAD_IN_HEADER option at your own risk. This is intentionally undocumented.
  3027. You can use this to avoid including pthread.h in the header section. The downside is that it
  3028. results in some fixed sized structures being declared for the various types that are used in
  3029. miniaudio. The risk here is that these types might be too small for a given platform. This
  3030. risk is yours to take and no support will be offered if you enable this option.
  3031. */
  3032. #ifndef MA_NO_PTHREAD_IN_HEADER
  3033. #include <pthread.h> /* Unfortunate #include, but needed for pthread_t, pthread_mutex_t and pthread_cond_t types. */
  3034. typedef pthread_t ma_pthread_t;
  3035. typedef pthread_mutex_t ma_pthread_mutex_t;
  3036. typedef pthread_cond_t ma_pthread_cond_t;
  3037. #else
  3038. typedef ma_uintptr ma_pthread_t;
  3039. typedef union ma_pthread_mutex_t { char __data[40]; ma_uint64 __alignment; } ma_pthread_mutex_t;
  3040. typedef union ma_pthread_cond_t { char __data[48]; ma_uint64 __alignment; } ma_pthread_cond_t;
  3041. #endif
  3042. #ifdef __unix__
  3043. #define MA_UNIX
  3044. #if defined(__DragonFly__) || defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
  3045. #define MA_BSD
  3046. #endif
  3047. #endif
  3048. #ifdef __linux__
  3049. #define MA_LINUX
  3050. #endif
  3051. #ifdef __APPLE__
  3052. #define MA_APPLE
  3053. #endif
  3054. #ifdef __ANDROID__
  3055. #define MA_ANDROID
  3056. #endif
  3057. #ifdef __EMSCRIPTEN__
  3058. #define MA_EMSCRIPTEN
  3059. #endif
  3060. #endif
  3061. #ifdef _MSC_VER
  3062. #define MA_INLINE __forceinline
  3063. #elif defined(__GNUC__)
  3064. /*
  3065. I've had a bug report where GCC is emitting warnings about functions possibly not being inlineable. This warning happens when
  3066. the __attribute__((always_inline)) attribute is defined without an "inline" statement. I think therefore there must be some
  3067. case where "__inline__" is not always defined, thus the compiler emitting these warnings. When using -std=c89 or -ansi on the
  3068. command line, we cannot use the "inline" keyword and instead need to use "__inline__". In an attempt to work around this issue
  3069. I am using "__inline__" only when we're compiling in strict ANSI mode.
  3070. */
  3071. #if defined(__STRICT_ANSI__)
  3072. #define MA_GNUC_INLINE_HINT __inline__
  3073. #else
  3074. #define MA_GNUC_INLINE_HINT inline
  3075. #endif
  3076. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  3077. #define MA_INLINE MA_GNUC_INLINE_HINT __attribute__((always_inline))
  3078. #else
  3079. #define MA_INLINE MA_GNUC_INLINE_HINT
  3080. #endif
  3081. #elif defined(__WATCOMC__)
  3082. #define MA_INLINE __inline
  3083. #else
  3084. #define MA_INLINE
  3085. #endif
  3086. #if !defined(MA_API)
  3087. #if defined(MA_DLL)
  3088. #if defined(_WIN32)
  3089. #define MA_DLL_IMPORT __declspec(dllimport)
  3090. #define MA_DLL_EXPORT __declspec(dllexport)
  3091. #define MA_DLL_PRIVATE static
  3092. #else
  3093. #if defined(__GNUC__) && __GNUC__ >= 4
  3094. #define MA_DLL_IMPORT __attribute__((visibility("default")))
  3095. #define MA_DLL_EXPORT __attribute__((visibility("default")))
  3096. #define MA_DLL_PRIVATE __attribute__((visibility("hidden")))
  3097. #else
  3098. #define MA_DLL_IMPORT
  3099. #define MA_DLL_EXPORT
  3100. #define MA_DLL_PRIVATE static
  3101. #endif
  3102. #endif
  3103. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  3104. #define MA_API MA_DLL_EXPORT
  3105. #else
  3106. #define MA_API MA_DLL_IMPORT
  3107. #endif
  3108. #define MA_PRIVATE MA_DLL_PRIVATE
  3109. #else
  3110. #define MA_API extern
  3111. #define MA_PRIVATE static
  3112. #endif
  3113. #endif
  3114. /* SIMD alignment in bytes. Currently set to 32 bytes in preparation for future AVX optimizations. */
  3115. #define MA_SIMD_ALIGNMENT 32
  3116. /*
  3117. Logging Levels
  3118. ==============
  3119. Log levels are only used to give logging callbacks some context as to the severity of a log message
  3120. so they can do filtering. All log levels will be posted to registered logging callbacks. If you
  3121. don't want to output a certain log level you can discriminate against the log level in the callback.
  3122. MA_LOG_LEVEL_DEBUG
  3123. Used for debugging. Useful for debug and test builds, but should be disabled in release builds.
  3124. MA_LOG_LEVEL_INFO
  3125. Informational logging. Useful for debugging. This will never be called from within the data
  3126. callback.
  3127. MA_LOG_LEVEL_WARNING
  3128. Warnings. You should enable this in you development builds and action them when encounted. These
  3129. logs usually indicate a potential problem or misconfiguration, but still allow you to keep
  3130. running. This will never be called from within the data callback.
  3131. MA_LOG_LEVEL_ERROR
  3132. Error logging. This will be fired when an operation fails and is subsequently aborted. This can
  3133. be fired from within the data callback, in which case the device will be stopped. You should
  3134. always have this log level enabled.
  3135. */
  3136. typedef enum
  3137. {
  3138. MA_LOG_LEVEL_DEBUG = 4,
  3139. MA_LOG_LEVEL_INFO = 3,
  3140. MA_LOG_LEVEL_WARNING = 2,
  3141. MA_LOG_LEVEL_ERROR = 1
  3142. } ma_log_level;
  3143. /*
  3144. Variables needing to be accessed atomically should be declared with this macro for two reasons:
  3145. 1) It allows people who read the code to identify a variable as such; and
  3146. 2) It forces alignment on platforms where it's required or optimal.
  3147. Note that for x86/64, alignment is not strictly necessary, but does have some performance
  3148. implications. Where supported by the compiler, alignment will be used, but otherwise if the CPU
  3149. architecture does not require it, it will simply leave it unaligned. This is the case with old
  3150. versions of Visual Studio, which I've confirmed with at least VC6.
  3151. */
  3152. #if !defined(_MSC_VER) && defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
  3153. #include <stdalign.h>
  3154. #define MA_ATOMIC(alignment, type) alignas(alignment) type
  3155. #else
  3156. #if defined(__GNUC__)
  3157. /* GCC-style compilers. */
  3158. #define MA_ATOMIC(alignment, type) type __attribute__((aligned(alignment)))
  3159. #elif defined(_MSC_VER) && _MSC_VER > 1200 /* 1200 = VC6. Alignment not supported, but not necessary because x86 is the only supported target. */
  3160. /* MSVC. */
  3161. #define MA_ATOMIC(alignment, type) __declspec(align(alignment)) type
  3162. #else
  3163. /* Other compilers. */
  3164. #define MA_ATOMIC(alignment, type) type
  3165. #endif
  3166. #endif
  3167. typedef struct ma_context ma_context;
  3168. typedef struct ma_device ma_device;
  3169. typedef ma_uint8 ma_channel;
  3170. typedef enum
  3171. {
  3172. MA_CHANNEL_NONE = 0,
  3173. MA_CHANNEL_MONO = 1,
  3174. MA_CHANNEL_FRONT_LEFT = 2,
  3175. MA_CHANNEL_FRONT_RIGHT = 3,
  3176. MA_CHANNEL_FRONT_CENTER = 4,
  3177. MA_CHANNEL_LFE = 5,
  3178. MA_CHANNEL_BACK_LEFT = 6,
  3179. MA_CHANNEL_BACK_RIGHT = 7,
  3180. MA_CHANNEL_FRONT_LEFT_CENTER = 8,
  3181. MA_CHANNEL_FRONT_RIGHT_CENTER = 9,
  3182. MA_CHANNEL_BACK_CENTER = 10,
  3183. MA_CHANNEL_SIDE_LEFT = 11,
  3184. MA_CHANNEL_SIDE_RIGHT = 12,
  3185. MA_CHANNEL_TOP_CENTER = 13,
  3186. MA_CHANNEL_TOP_FRONT_LEFT = 14,
  3187. MA_CHANNEL_TOP_FRONT_CENTER = 15,
  3188. MA_CHANNEL_TOP_FRONT_RIGHT = 16,
  3189. MA_CHANNEL_TOP_BACK_LEFT = 17,
  3190. MA_CHANNEL_TOP_BACK_CENTER = 18,
  3191. MA_CHANNEL_TOP_BACK_RIGHT = 19,
  3192. MA_CHANNEL_AUX_0 = 20,
  3193. MA_CHANNEL_AUX_1 = 21,
  3194. MA_CHANNEL_AUX_2 = 22,
  3195. MA_CHANNEL_AUX_3 = 23,
  3196. MA_CHANNEL_AUX_4 = 24,
  3197. MA_CHANNEL_AUX_5 = 25,
  3198. MA_CHANNEL_AUX_6 = 26,
  3199. MA_CHANNEL_AUX_7 = 27,
  3200. MA_CHANNEL_AUX_8 = 28,
  3201. MA_CHANNEL_AUX_9 = 29,
  3202. MA_CHANNEL_AUX_10 = 30,
  3203. MA_CHANNEL_AUX_11 = 31,
  3204. MA_CHANNEL_AUX_12 = 32,
  3205. MA_CHANNEL_AUX_13 = 33,
  3206. MA_CHANNEL_AUX_14 = 34,
  3207. MA_CHANNEL_AUX_15 = 35,
  3208. MA_CHANNEL_AUX_16 = 36,
  3209. MA_CHANNEL_AUX_17 = 37,
  3210. MA_CHANNEL_AUX_18 = 38,
  3211. MA_CHANNEL_AUX_19 = 39,
  3212. MA_CHANNEL_AUX_20 = 40,
  3213. MA_CHANNEL_AUX_21 = 41,
  3214. MA_CHANNEL_AUX_22 = 42,
  3215. MA_CHANNEL_AUX_23 = 43,
  3216. MA_CHANNEL_AUX_24 = 44,
  3217. MA_CHANNEL_AUX_25 = 45,
  3218. MA_CHANNEL_AUX_26 = 46,
  3219. MA_CHANNEL_AUX_27 = 47,
  3220. MA_CHANNEL_AUX_28 = 48,
  3221. MA_CHANNEL_AUX_29 = 49,
  3222. MA_CHANNEL_AUX_30 = 50,
  3223. MA_CHANNEL_AUX_31 = 51,
  3224. MA_CHANNEL_LEFT = MA_CHANNEL_FRONT_LEFT,
  3225. MA_CHANNEL_RIGHT = MA_CHANNEL_FRONT_RIGHT,
  3226. MA_CHANNEL_POSITION_COUNT = (MA_CHANNEL_AUX_31 + 1)
  3227. } _ma_channel_position; /* Do not use `_ma_channel_position` directly. Use `ma_channel` instead. */
  3228. typedef enum
  3229. {
  3230. MA_SUCCESS = 0,
  3231. MA_ERROR = -1, /* A generic error. */
  3232. MA_INVALID_ARGS = -2,
  3233. MA_INVALID_OPERATION = -3,
  3234. MA_OUT_OF_MEMORY = -4,
  3235. MA_OUT_OF_RANGE = -5,
  3236. MA_ACCESS_DENIED = -6,
  3237. MA_DOES_NOT_EXIST = -7,
  3238. MA_ALREADY_EXISTS = -8,
  3239. MA_TOO_MANY_OPEN_FILES = -9,
  3240. MA_INVALID_FILE = -10,
  3241. MA_TOO_BIG = -11,
  3242. MA_PATH_TOO_LONG = -12,
  3243. MA_NAME_TOO_LONG = -13,
  3244. MA_NOT_DIRECTORY = -14,
  3245. MA_IS_DIRECTORY = -15,
  3246. MA_DIRECTORY_NOT_EMPTY = -16,
  3247. MA_AT_END = -17,
  3248. MA_NO_SPACE = -18,
  3249. MA_BUSY = -19,
  3250. MA_IO_ERROR = -20,
  3251. MA_INTERRUPT = -21,
  3252. MA_UNAVAILABLE = -22,
  3253. MA_ALREADY_IN_USE = -23,
  3254. MA_BAD_ADDRESS = -24,
  3255. MA_BAD_SEEK = -25,
  3256. MA_BAD_PIPE = -26,
  3257. MA_DEADLOCK = -27,
  3258. MA_TOO_MANY_LINKS = -28,
  3259. MA_NOT_IMPLEMENTED = -29,
  3260. MA_NO_MESSAGE = -30,
  3261. MA_BAD_MESSAGE = -31,
  3262. MA_NO_DATA_AVAILABLE = -32,
  3263. MA_INVALID_DATA = -33,
  3264. MA_TIMEOUT = -34,
  3265. MA_NO_NETWORK = -35,
  3266. MA_NOT_UNIQUE = -36,
  3267. MA_NOT_SOCKET = -37,
  3268. MA_NO_ADDRESS = -38,
  3269. MA_BAD_PROTOCOL = -39,
  3270. MA_PROTOCOL_UNAVAILABLE = -40,
  3271. MA_PROTOCOL_NOT_SUPPORTED = -41,
  3272. MA_PROTOCOL_FAMILY_NOT_SUPPORTED = -42,
  3273. MA_ADDRESS_FAMILY_NOT_SUPPORTED = -43,
  3274. MA_SOCKET_NOT_SUPPORTED = -44,
  3275. MA_CONNECTION_RESET = -45,
  3276. MA_ALREADY_CONNECTED = -46,
  3277. MA_NOT_CONNECTED = -47,
  3278. MA_CONNECTION_REFUSED = -48,
  3279. MA_NO_HOST = -49,
  3280. MA_IN_PROGRESS = -50,
  3281. MA_CANCELLED = -51,
  3282. MA_MEMORY_ALREADY_MAPPED = -52,
  3283. /* General miniaudio-specific errors. */
  3284. MA_FORMAT_NOT_SUPPORTED = -100,
  3285. MA_DEVICE_TYPE_NOT_SUPPORTED = -101,
  3286. MA_SHARE_MODE_NOT_SUPPORTED = -102,
  3287. MA_NO_BACKEND = -103,
  3288. MA_NO_DEVICE = -104,
  3289. MA_API_NOT_FOUND = -105,
  3290. MA_INVALID_DEVICE_CONFIG = -106,
  3291. MA_LOOP = -107,
  3292. /* State errors. */
  3293. MA_DEVICE_NOT_INITIALIZED = -200,
  3294. MA_DEVICE_ALREADY_INITIALIZED = -201,
  3295. MA_DEVICE_NOT_STARTED = -202,
  3296. MA_DEVICE_NOT_STOPPED = -203,
  3297. /* Operation errors. */
  3298. MA_FAILED_TO_INIT_BACKEND = -300,
  3299. MA_FAILED_TO_OPEN_BACKEND_DEVICE = -301,
  3300. MA_FAILED_TO_START_BACKEND_DEVICE = -302,
  3301. MA_FAILED_TO_STOP_BACKEND_DEVICE = -303
  3302. } ma_result;
  3303. #define MA_MIN_CHANNELS 1
  3304. #ifndef MA_MAX_CHANNELS
  3305. #define MA_MAX_CHANNELS 254
  3306. #endif
  3307. #ifndef MA_MAX_FILTER_ORDER
  3308. #define MA_MAX_FILTER_ORDER 8
  3309. #endif
  3310. typedef enum
  3311. {
  3312. ma_stream_format_pcm = 0
  3313. } ma_stream_format;
  3314. typedef enum
  3315. {
  3316. ma_stream_layout_interleaved = 0,
  3317. ma_stream_layout_deinterleaved
  3318. } ma_stream_layout;
  3319. typedef enum
  3320. {
  3321. ma_dither_mode_none = 0,
  3322. ma_dither_mode_rectangle,
  3323. ma_dither_mode_triangle
  3324. } ma_dither_mode;
  3325. typedef enum
  3326. {
  3327. /*
  3328. I like to keep these explicitly defined because they're used as a key into a lookup table. When items are
  3329. added to this, make sure there are no gaps and that they're added to the lookup table in ma_get_bytes_per_sample().
  3330. */
  3331. ma_format_unknown = 0, /* Mainly used for indicating an error, but also used as the default for the output format for decoders. */
  3332. ma_format_u8 = 1,
  3333. ma_format_s16 = 2, /* Seems to be the most widely supported format. */
  3334. ma_format_s24 = 3, /* Tightly packed. 3 bytes per sample. */
  3335. ma_format_s32 = 4,
  3336. ma_format_f32 = 5,
  3337. ma_format_count
  3338. } ma_format;
  3339. typedef enum
  3340. {
  3341. /* Standard rates need to be in priority order. */
  3342. ma_standard_sample_rate_48000 = 48000, /* Most common */
  3343. ma_standard_sample_rate_44100 = 44100,
  3344. ma_standard_sample_rate_32000 = 32000, /* Lows */
  3345. ma_standard_sample_rate_24000 = 24000,
  3346. ma_standard_sample_rate_22050 = 22050,
  3347. ma_standard_sample_rate_88200 = 88200, /* Highs */
  3348. ma_standard_sample_rate_96000 = 96000,
  3349. ma_standard_sample_rate_176400 = 176400,
  3350. ma_standard_sample_rate_192000 = 192000,
  3351. ma_standard_sample_rate_16000 = 16000, /* Extreme lows */
  3352. ma_standard_sample_rate_11025 = 11250,
  3353. ma_standard_sample_rate_8000 = 8000,
  3354. ma_standard_sample_rate_352800 = 352800, /* Extreme highs */
  3355. ma_standard_sample_rate_384000 = 384000,
  3356. ma_standard_sample_rate_min = ma_standard_sample_rate_8000,
  3357. ma_standard_sample_rate_max = ma_standard_sample_rate_384000,
  3358. ma_standard_sample_rate_count = 14 /* Need to maintain the count manually. Make sure this is updated if items are added to enum. */
  3359. } ma_standard_sample_rate;
  3360. typedef enum
  3361. {
  3362. ma_channel_mix_mode_rectangular = 0, /* Simple averaging based on the plane(s) the channel is sitting on. */
  3363. ma_channel_mix_mode_simple, /* Drop excess channels; zeroed out extra channels. */
  3364. ma_channel_mix_mode_custom_weights, /* Use custom weights specified in ma_channel_converter_config. */
  3365. ma_channel_mix_mode_default = ma_channel_mix_mode_rectangular
  3366. } ma_channel_mix_mode;
  3367. typedef enum
  3368. {
  3369. ma_standard_channel_map_microsoft,
  3370. ma_standard_channel_map_alsa,
  3371. ma_standard_channel_map_rfc3551, /* Based off AIFF. */
  3372. ma_standard_channel_map_flac,
  3373. ma_standard_channel_map_vorbis,
  3374. ma_standard_channel_map_sound4, /* FreeBSD's sound(4). */
  3375. ma_standard_channel_map_sndio, /* www.sndio.org/tips.html */
  3376. 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. */
  3377. ma_standard_channel_map_default = ma_standard_channel_map_microsoft
  3378. } ma_standard_channel_map;
  3379. typedef enum
  3380. {
  3381. ma_performance_profile_low_latency = 0,
  3382. ma_performance_profile_conservative
  3383. } ma_performance_profile;
  3384. typedef struct
  3385. {
  3386. void* pUserData;
  3387. void* (* onMalloc)(size_t sz, void* pUserData);
  3388. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  3389. void (* onFree)(void* p, void* pUserData);
  3390. } ma_allocation_callbacks;
  3391. typedef struct
  3392. {
  3393. ma_int32 state;
  3394. } ma_lcg;
  3395. /* Spinlocks are 32-bit for compatibility reasons. */
  3396. typedef ma_uint32 ma_spinlock;
  3397. #ifndef MA_NO_THREADING
  3398. /* Thread priorities should be ordered such that the default priority of the worker thread is 0. */
  3399. typedef enum
  3400. {
  3401. ma_thread_priority_idle = -5,
  3402. ma_thread_priority_lowest = -4,
  3403. ma_thread_priority_low = -3,
  3404. ma_thread_priority_normal = -2,
  3405. ma_thread_priority_high = -1,
  3406. ma_thread_priority_highest = 0,
  3407. ma_thread_priority_realtime = 1,
  3408. ma_thread_priority_default = 0
  3409. } ma_thread_priority;
  3410. #if defined(MA_WIN32)
  3411. typedef ma_handle ma_thread;
  3412. #endif
  3413. #if defined(MA_POSIX)
  3414. typedef ma_pthread_t ma_thread;
  3415. #endif
  3416. #if defined(MA_WIN32)
  3417. typedef ma_handle ma_mutex;
  3418. #endif
  3419. #if defined(MA_POSIX)
  3420. typedef ma_pthread_mutex_t ma_mutex;
  3421. #endif
  3422. #if defined(MA_WIN32)
  3423. typedef ma_handle ma_event;
  3424. #endif
  3425. #if defined(MA_POSIX)
  3426. typedef struct
  3427. {
  3428. ma_uint32 value;
  3429. ma_pthread_mutex_t lock;
  3430. ma_pthread_cond_t cond;
  3431. } ma_event;
  3432. #endif /* MA_POSIX */
  3433. #if defined(MA_WIN32)
  3434. typedef ma_handle ma_semaphore;
  3435. #endif
  3436. #if defined(MA_POSIX)
  3437. typedef struct
  3438. {
  3439. int value;
  3440. ma_pthread_mutex_t lock;
  3441. ma_pthread_cond_t cond;
  3442. } ma_semaphore;
  3443. #endif /* MA_POSIX */
  3444. #else
  3445. /* 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. */
  3446. #ifndef MA_NO_DEVICE_IO
  3447. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  3448. #endif
  3449. #endif /* MA_NO_THREADING */
  3450. /*
  3451. Retrieves the version of miniaudio as separated integers. Each component can be NULL if it's not required.
  3452. */
  3453. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision);
  3454. /*
  3455. Retrieves the version of miniaudio as a string which can be useful for logging purposes.
  3456. */
  3457. MA_API const char* ma_version_string(void);
  3458. /**************************************************************************************************************************************************************
  3459. Logging
  3460. **************************************************************************************************************************************************************/
  3461. #include <stdarg.h> /* For va_list. */
  3462. #if defined(__has_attribute)
  3463. #if __has_attribute(format)
  3464. #define MA_ATTRIBUTE_FORMAT(fmt, va) __attribute__((format(printf, fmt, va)))
  3465. #endif
  3466. #endif
  3467. #ifndef MA_ATTRIBUTE_FORMAT
  3468. #define MA_ATTRIBUTE_FORMAT(fmt,va)
  3469. #endif
  3470. #ifndef MA_MAX_LOG_CALLBACKS
  3471. #define MA_MAX_LOG_CALLBACKS 4
  3472. #endif
  3473. /*
  3474. The callback for handling log messages.
  3475. Parameters
  3476. ----------
  3477. pUserData (in)
  3478. The user data pointer that was passed into ma_log_register_callback().
  3479. logLevel (in)
  3480. The log level. This can be one of the following:
  3481. +----------------------+
  3482. | Log Level |
  3483. +----------------------+
  3484. | MA_LOG_LEVEL_DEBUG |
  3485. | MA_LOG_LEVEL_INFO |
  3486. | MA_LOG_LEVEL_WARNING |
  3487. | MA_LOG_LEVEL_ERROR |
  3488. +----------------------+
  3489. pMessage (in)
  3490. The log message.
  3491. Remarks
  3492. -------
  3493. Do not modify the state of the device from inside the callback.
  3494. */
  3495. typedef void (* ma_log_callback_proc)(void* pUserData, ma_uint32 level, const char* pMessage);
  3496. typedef struct
  3497. {
  3498. ma_log_callback_proc onLog;
  3499. void* pUserData;
  3500. } ma_log_callback;
  3501. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData);
  3502. typedef struct
  3503. {
  3504. ma_log_callback callbacks[MA_MAX_LOG_CALLBACKS];
  3505. ma_uint32 callbackCount;
  3506. ma_allocation_callbacks allocationCallbacks; /* Need to store these persistently because ma_log_postv() might need to allocate a buffer on the heap. */
  3507. #ifndef MA_NO_THREADING
  3508. ma_mutex lock; /* For thread safety just to make it easier and safer for the logging implementation. */
  3509. #endif
  3510. } ma_log;
  3511. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog);
  3512. MA_API void ma_log_uninit(ma_log* pLog);
  3513. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback);
  3514. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback);
  3515. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage);
  3516. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args);
  3517. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...) MA_ATTRIBUTE_FORMAT(3, 4);
  3518. /**************************************************************************************************************************************************************
  3519. Biquad Filtering
  3520. **************************************************************************************************************************************************************/
  3521. typedef union
  3522. {
  3523. float f32;
  3524. ma_int32 s32;
  3525. } ma_biquad_coefficient;
  3526. typedef struct
  3527. {
  3528. ma_format format;
  3529. ma_uint32 channels;
  3530. double b0;
  3531. double b1;
  3532. double b2;
  3533. double a0;
  3534. double a1;
  3535. double a2;
  3536. } ma_biquad_config;
  3537. 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);
  3538. typedef struct
  3539. {
  3540. ma_format format;
  3541. ma_uint32 channels;
  3542. ma_biquad_coefficient b0;
  3543. ma_biquad_coefficient b1;
  3544. ma_biquad_coefficient b2;
  3545. ma_biquad_coefficient a1;
  3546. ma_biquad_coefficient a2;
  3547. ma_biquad_coefficient* pR1;
  3548. ma_biquad_coefficient* pR2;
  3549. /* Memory management. */
  3550. void* _pHeap;
  3551. ma_bool32 _ownsHeap;
  3552. } ma_biquad;
  3553. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes);
  3554. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ);
  3555. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ);
  3556. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks);
  3557. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ);
  3558. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ);
  3559. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3560. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ);
  3561. /**************************************************************************************************************************************************************
  3562. Low-Pass Filtering
  3563. **************************************************************************************************************************************************************/
  3564. typedef struct
  3565. {
  3566. ma_format format;
  3567. ma_uint32 channels;
  3568. ma_uint32 sampleRate;
  3569. double cutoffFrequency;
  3570. double q;
  3571. } ma_lpf1_config, ma_lpf2_config;
  3572. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3573. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3574. typedef struct
  3575. {
  3576. ma_format format;
  3577. ma_uint32 channels;
  3578. ma_biquad_coefficient a;
  3579. ma_biquad_coefficient* pR1;
  3580. /* Memory management. */
  3581. void* _pHeap;
  3582. ma_bool32 _ownsHeap;
  3583. } ma_lpf1;
  3584. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3585. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF);
  3586. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF);
  3587. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3588. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF);
  3589. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF);
  3590. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3591. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF);
  3592. typedef struct
  3593. {
  3594. ma_biquad bq; /* The second order low-pass filter is implemented as a biquad filter. */
  3595. } ma_lpf2;
  3596. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3597. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pHPF);
  3598. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF);
  3599. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3600. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF);
  3601. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF);
  3602. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3603. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF);
  3604. typedef struct
  3605. {
  3606. ma_format format;
  3607. ma_uint32 channels;
  3608. ma_uint32 sampleRate;
  3609. double cutoffFrequency;
  3610. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3611. } ma_lpf_config;
  3612. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3613. typedef struct
  3614. {
  3615. ma_format format;
  3616. ma_uint32 channels;
  3617. ma_uint32 sampleRate;
  3618. ma_uint32 lpf1Count;
  3619. ma_uint32 lpf2Count;
  3620. ma_lpf1* pLPF1;
  3621. ma_lpf2* pLPF2;
  3622. /* Memory management. */
  3623. void* _pHeap;
  3624. ma_bool32 _ownsHeap;
  3625. } ma_lpf;
  3626. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes);
  3627. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF);
  3628. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF);
  3629. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3630. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF);
  3631. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF);
  3632. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3633. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF);
  3634. /**************************************************************************************************************************************************************
  3635. High-Pass Filtering
  3636. **************************************************************************************************************************************************************/
  3637. typedef struct
  3638. {
  3639. ma_format format;
  3640. ma_uint32 channels;
  3641. ma_uint32 sampleRate;
  3642. double cutoffFrequency;
  3643. double q;
  3644. } ma_hpf1_config, ma_hpf2_config;
  3645. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency);
  3646. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3647. typedef struct
  3648. {
  3649. ma_format format;
  3650. ma_uint32 channels;
  3651. ma_biquad_coefficient a;
  3652. ma_biquad_coefficient* pR1;
  3653. /* Memory management. */
  3654. void* _pHeap;
  3655. ma_bool32 _ownsHeap;
  3656. } ma_hpf1;
  3657. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes);
  3658. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF);
  3659. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pHPF);
  3660. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3661. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF);
  3662. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3663. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF);
  3664. typedef struct
  3665. {
  3666. ma_biquad bq; /* The second order high-pass filter is implemented as a biquad filter. */
  3667. } ma_hpf2;
  3668. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3669. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF);
  3670. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF);
  3671. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3672. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF);
  3673. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3674. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF);
  3675. typedef struct
  3676. {
  3677. ma_format format;
  3678. ma_uint32 channels;
  3679. ma_uint32 sampleRate;
  3680. double cutoffFrequency;
  3681. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3682. } ma_hpf_config;
  3683. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3684. typedef struct
  3685. {
  3686. ma_format format;
  3687. ma_uint32 channels;
  3688. ma_uint32 sampleRate;
  3689. ma_uint32 hpf1Count;
  3690. ma_uint32 hpf2Count;
  3691. ma_hpf1* pHPF1;
  3692. ma_hpf2* pHPF2;
  3693. /* Memory management. */
  3694. void* _pHeap;
  3695. ma_bool32 _ownsHeap;
  3696. } ma_hpf;
  3697. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes);
  3698. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF);
  3699. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF);
  3700. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3701. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF);
  3702. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3703. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF);
  3704. /**************************************************************************************************************************************************************
  3705. Band-Pass Filtering
  3706. **************************************************************************************************************************************************************/
  3707. typedef struct
  3708. {
  3709. ma_format format;
  3710. ma_uint32 channels;
  3711. ma_uint32 sampleRate;
  3712. double cutoffFrequency;
  3713. double q;
  3714. } ma_bpf2_config;
  3715. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q);
  3716. typedef struct
  3717. {
  3718. ma_biquad bq; /* The second order band-pass filter is implemented as a biquad filter. */
  3719. } ma_bpf2;
  3720. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes);
  3721. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF);
  3722. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF);
  3723. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3724. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF);
  3725. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3726. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF);
  3727. typedef struct
  3728. {
  3729. ma_format format;
  3730. ma_uint32 channels;
  3731. ma_uint32 sampleRate;
  3732. double cutoffFrequency;
  3733. ma_uint32 order; /* If set to 0, will be treated as a passthrough (no filtering will be applied). */
  3734. } ma_bpf_config;
  3735. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  3736. typedef struct
  3737. {
  3738. ma_format format;
  3739. ma_uint32 channels;
  3740. ma_uint32 bpf2Count;
  3741. ma_bpf2* pBPF2;
  3742. /* Memory management. */
  3743. void* _pHeap;
  3744. ma_bool32 _ownsHeap;
  3745. } ma_bpf;
  3746. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes);
  3747. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF);
  3748. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF);
  3749. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks);
  3750. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF);
  3751. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3752. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF);
  3753. /**************************************************************************************************************************************************************
  3754. Notching Filter
  3755. **************************************************************************************************************************************************************/
  3756. typedef struct
  3757. {
  3758. ma_format format;
  3759. ma_uint32 channels;
  3760. ma_uint32 sampleRate;
  3761. double q;
  3762. double frequency;
  3763. } ma_notch2_config, ma_notch_config;
  3764. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  3765. typedef struct
  3766. {
  3767. ma_biquad bq;
  3768. } ma_notch2;
  3769. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes);
  3770. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter);
  3771. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter);
  3772. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3773. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter);
  3774. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3775. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter);
  3776. /**************************************************************************************************************************************************************
  3777. Peaking EQ Filter
  3778. **************************************************************************************************************************************************************/
  3779. typedef struct
  3780. {
  3781. ma_format format;
  3782. ma_uint32 channels;
  3783. ma_uint32 sampleRate;
  3784. double gainDB;
  3785. double q;
  3786. double frequency;
  3787. } ma_peak2_config, ma_peak_config;
  3788. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  3789. typedef struct
  3790. {
  3791. ma_biquad bq;
  3792. } ma_peak2;
  3793. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes);
  3794. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter);
  3795. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter);
  3796. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3797. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter);
  3798. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3799. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter);
  3800. /**************************************************************************************************************************************************************
  3801. Low Shelf Filter
  3802. **************************************************************************************************************************************************************/
  3803. typedef struct
  3804. {
  3805. ma_format format;
  3806. ma_uint32 channels;
  3807. ma_uint32 sampleRate;
  3808. double gainDB;
  3809. double shelfSlope;
  3810. double frequency;
  3811. } ma_loshelf2_config, ma_loshelf_config;
  3812. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3813. typedef struct
  3814. {
  3815. ma_biquad bq;
  3816. } ma_loshelf2;
  3817. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3818. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter);
  3819. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter);
  3820. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3821. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter);
  3822. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3823. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter);
  3824. /**************************************************************************************************************************************************************
  3825. High Shelf Filter
  3826. **************************************************************************************************************************************************************/
  3827. typedef struct
  3828. {
  3829. ma_format format;
  3830. ma_uint32 channels;
  3831. ma_uint32 sampleRate;
  3832. double gainDB;
  3833. double shelfSlope;
  3834. double frequency;
  3835. } ma_hishelf2_config, ma_hishelf_config;
  3836. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency);
  3837. typedef struct
  3838. {
  3839. ma_biquad bq;
  3840. } ma_hishelf2;
  3841. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes);
  3842. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter);
  3843. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter);
  3844. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks);
  3845. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter);
  3846. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3847. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter);
  3848. /*
  3849. Delay
  3850. */
  3851. typedef struct
  3852. {
  3853. ma_uint32 channels;
  3854. ma_uint32 sampleRate;
  3855. ma_uint32 delayInFrames;
  3856. ma_bool32 delayStart; /* Set to true to delay the start of the output; false otherwise. */
  3857. float wet; /* 0..1. Default = 1. */
  3858. float dry; /* 0..1. Default = 1. */
  3859. float decay; /* 0..1. Default = 0 (no feedback). Feedback decay. Use this for echo. */
  3860. } ma_delay_config;
  3861. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  3862. typedef struct
  3863. {
  3864. ma_delay_config config;
  3865. ma_uint32 cursor; /* Feedback is written to this cursor. Always equal or in front of the read cursor. */
  3866. ma_uint32 bufferSizeInFrames;
  3867. float* pBuffer;
  3868. } ma_delay;
  3869. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay);
  3870. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks);
  3871. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount);
  3872. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value);
  3873. MA_API float ma_delay_get_wet(const ma_delay* pDelay);
  3874. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value);
  3875. MA_API float ma_delay_get_dry(const ma_delay* pDelay);
  3876. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value);
  3877. MA_API float ma_delay_get_decay(const ma_delay* pDelay);
  3878. /* Gainer for smooth volume changes. */
  3879. typedef struct
  3880. {
  3881. ma_uint32 channels;
  3882. ma_uint32 smoothTimeInFrames;
  3883. } ma_gainer_config;
  3884. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames);
  3885. typedef struct
  3886. {
  3887. ma_gainer_config config;
  3888. ma_uint32 t;
  3889. float* pOldGains;
  3890. float* pNewGains;
  3891. /* Memory management. */
  3892. void* _pHeap;
  3893. ma_bool32 _ownsHeap;
  3894. } ma_gainer;
  3895. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes);
  3896. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer);
  3897. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer);
  3898. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks);
  3899. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3900. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain);
  3901. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains);
  3902. /* Stereo panner. */
  3903. typedef enum
  3904. {
  3905. 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. */
  3906. ma_pan_mode_pan /* A true pan. The sound from one side will "move" to the other side and blend with it. */
  3907. } ma_pan_mode;
  3908. typedef struct
  3909. {
  3910. ma_format format;
  3911. ma_uint32 channels;
  3912. ma_pan_mode mode;
  3913. float pan;
  3914. } ma_panner_config;
  3915. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels);
  3916. typedef struct
  3917. {
  3918. ma_format format;
  3919. ma_uint32 channels;
  3920. ma_pan_mode mode;
  3921. float pan; /* -1..1 where 0 is no pan, -1 is left side, +1 is right side. Defaults to 0. */
  3922. } ma_panner;
  3923. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner);
  3924. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3925. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode);
  3926. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner);
  3927. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan);
  3928. MA_API float ma_panner_get_pan(const ma_panner* pPanner);
  3929. /* Fader. */
  3930. typedef struct
  3931. {
  3932. ma_format format;
  3933. ma_uint32 channels;
  3934. ma_uint32 sampleRate;
  3935. } ma_fader_config;
  3936. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  3937. typedef struct
  3938. {
  3939. ma_fader_config config;
  3940. float volumeBeg; /* If volumeBeg and volumeEnd is equal to 1, no fading happens (ma_fader_process_pcm_frames() will run as a passthrough). */
  3941. float volumeEnd;
  3942. ma_uint64 lengthInFrames; /* The total length of the fade. */
  3943. ma_uint64 cursorInFrames; /* The current time in frames. Incremented by ma_fader_process_pcm_frames(). */
  3944. } ma_fader;
  3945. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader);
  3946. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  3947. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate);
  3948. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames);
  3949. MA_API float ma_fader_get_current_volume(ma_fader* pFader);
  3950. /* Spatializer. */
  3951. typedef struct
  3952. {
  3953. float x;
  3954. float y;
  3955. float z;
  3956. } ma_vec3f;
  3957. typedef enum
  3958. {
  3959. ma_attenuation_model_none, /* No distance attenuation and no spatialization. */
  3960. ma_attenuation_model_inverse, /* Equivalent to OpenAL's AL_INVERSE_DISTANCE_CLAMPED. */
  3961. ma_attenuation_model_linear, /* Linear attenuation. Equivalent to OpenAL's AL_LINEAR_DISTANCE_CLAMPED. */
  3962. ma_attenuation_model_exponential /* Exponential attenuation. Equivalent to OpenAL's AL_EXPONENT_DISTANCE_CLAMPED. */
  3963. } ma_attenuation_model;
  3964. typedef enum
  3965. {
  3966. ma_positioning_absolute,
  3967. ma_positioning_relative
  3968. } ma_positioning;
  3969. typedef enum
  3970. {
  3971. ma_handedness_right,
  3972. ma_handedness_left
  3973. } ma_handedness;
  3974. typedef struct
  3975. {
  3976. ma_uint32 channelsOut;
  3977. ma_channel* pChannelMapOut;
  3978. 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. */
  3979. float coneInnerAngleInRadians;
  3980. float coneOuterAngleInRadians;
  3981. float coneOuterGain;
  3982. float speedOfSound;
  3983. ma_vec3f worldUp;
  3984. } ma_spatializer_listener_config;
  3985. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut);
  3986. typedef struct
  3987. {
  3988. ma_spatializer_listener_config config;
  3989. ma_vec3f position; /* The absolute position of the listener. */
  3990. ma_vec3f direction; /* The direction the listener is facing. The world up vector is config.worldUp. */
  3991. ma_vec3f velocity;
  3992. ma_bool32 isEnabled;
  3993. /* Memory management. */
  3994. ma_bool32 _ownsHeap;
  3995. void* _pHeap;
  3996. } ma_spatializer_listener;
  3997. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes);
  3998. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener);
  3999. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener);
  4000. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks);
  4001. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener);
  4002. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4003. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4004. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z);
  4005. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener);
  4006. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z);
  4007. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener);
  4008. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z);
  4009. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener);
  4010. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound);
  4011. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener);
  4012. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z);
  4013. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener);
  4014. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled);
  4015. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener);
  4016. typedef struct
  4017. {
  4018. ma_uint32 channelsIn;
  4019. ma_uint32 channelsOut;
  4020. ma_channel* pChannelMapIn;
  4021. ma_attenuation_model attenuationModel;
  4022. ma_positioning positioning;
  4023. 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. */
  4024. float minGain;
  4025. float maxGain;
  4026. float minDistance;
  4027. float maxDistance;
  4028. float rolloff;
  4029. float coneInnerAngleInRadians;
  4030. float coneOuterAngleInRadians;
  4031. float coneOuterGain;
  4032. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4033. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4034. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4035. } ma_spatializer_config;
  4036. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut);
  4037. typedef struct
  4038. {
  4039. ma_uint32 channelsIn;
  4040. ma_uint32 channelsOut;
  4041. ma_channel* pChannelMapIn;
  4042. ma_attenuation_model attenuationModel;
  4043. ma_positioning positioning;
  4044. 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. */
  4045. float minGain;
  4046. float maxGain;
  4047. float minDistance;
  4048. float maxDistance;
  4049. float rolloff;
  4050. float coneInnerAngleInRadians;
  4051. float coneOuterAngleInRadians;
  4052. float coneOuterGain;
  4053. float dopplerFactor; /* Set to 0 to disable doppler effect. */
  4054. float directionalAttenuationFactor; /* Set to 0 to disable directional attenuation. */
  4055. ma_uint32 gainSmoothTimeInFrames; /* When the gain of a channel changes during spatialization, the transition will be linearly interpolated over this number of frames. */
  4056. ma_vec3f position;
  4057. ma_vec3f direction;
  4058. ma_vec3f velocity; /* For doppler effect. */
  4059. 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. */
  4060. ma_gainer gainer; /* For smooth gain transitions. */
  4061. 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. */
  4062. /* Memory management. */
  4063. void* _pHeap;
  4064. ma_bool32 _ownsHeap;
  4065. } ma_spatializer;
  4066. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes);
  4067. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer);
  4068. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer);
  4069. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks);
  4070. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4071. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer);
  4072. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer);
  4073. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel);
  4074. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer);
  4075. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning);
  4076. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer);
  4077. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff);
  4078. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer);
  4079. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain);
  4080. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer);
  4081. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain);
  4082. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer);
  4083. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance);
  4084. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer);
  4085. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance);
  4086. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer);
  4087. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  4088. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  4089. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor);
  4090. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer);
  4091. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor);
  4092. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer);
  4093. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z);
  4094. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer);
  4095. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z);
  4096. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer);
  4097. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z);
  4098. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer);
  4099. 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);
  4100. /************************************************************************************************************************************************************
  4101. *************************************************************************************************************************************************************
  4102. DATA CONVERSION
  4103. ===============
  4104. This section contains the APIs for data conversion. You will find everything here for channel mapping, sample format conversion, resampling, etc.
  4105. *************************************************************************************************************************************************************
  4106. ************************************************************************************************************************************************************/
  4107. /**************************************************************************************************************************************************************
  4108. Resampling
  4109. **************************************************************************************************************************************************************/
  4110. typedef struct
  4111. {
  4112. ma_format format;
  4113. ma_uint32 channels;
  4114. ma_uint32 sampleRateIn;
  4115. ma_uint32 sampleRateOut;
  4116. ma_uint32 lpfOrder; /* The low-pass filter order. Setting this to 0 will disable low-pass filtering. */
  4117. double lpfNyquistFactor; /* 0..1. Defaults to 1. 1 = Half the sampling frequency (Nyquist Frequency), 0.5 = Quarter the sampling frequency (half Nyquest Frequency), etc. */
  4118. } ma_linear_resampler_config;
  4119. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4120. typedef struct
  4121. {
  4122. ma_linear_resampler_config config;
  4123. ma_uint32 inAdvanceInt;
  4124. ma_uint32 inAdvanceFrac;
  4125. ma_uint32 inTimeInt;
  4126. ma_uint32 inTimeFrac;
  4127. union
  4128. {
  4129. float* f32;
  4130. ma_int16* s16;
  4131. } x0; /* The previous input frame. */
  4132. union
  4133. {
  4134. float* f32;
  4135. ma_int16* s16;
  4136. } x1; /* The next input frame. */
  4137. ma_lpf lpf;
  4138. /* Memory management. */
  4139. void* _pHeap;
  4140. ma_bool32 _ownsHeap;
  4141. } ma_linear_resampler;
  4142. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4143. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler);
  4144. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler);
  4145. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4146. 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);
  4147. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4148. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut);
  4149. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler);
  4150. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler);
  4151. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4152. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4153. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler);
  4154. typedef struct ma_resampler_config ma_resampler_config;
  4155. typedef void ma_resampling_backend;
  4156. typedef struct
  4157. {
  4158. ma_result (* onGetHeapSize )(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4159. ma_result (* onInit )(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend);
  4160. void (* onUninit )(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  4161. ma_result (* onProcess )(void* pUserData, ma_resampling_backend* pBackend, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4162. ma_result (* onSetRate )(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut); /* Optional. Rate changes will be disabled. */
  4163. ma_uint64 (* onGetInputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4164. ma_uint64 (* onGetOutputLatency )(void* pUserData, const ma_resampling_backend* pBackend); /* Optional. Latency will be reported as 0. */
  4165. ma_result (* onGetRequiredInputFrameCount )(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4166. ma_result (* onGetExpectedOutputFrameCount)(void* pUserData, const ma_resampling_backend* pBackend, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount); /* Optional. Latency mitigation will be disabled. */
  4167. ma_result (* onReset )(void* pUserData, ma_resampling_backend* pBackend);
  4168. } ma_resampling_backend_vtable;
  4169. typedef enum
  4170. {
  4171. ma_resample_algorithm_linear = 0, /* Fastest, lowest quality. Optional low-pass filtering. Default. */
  4172. ma_resample_algorithm_custom,
  4173. } ma_resample_algorithm;
  4174. struct ma_resampler_config
  4175. {
  4176. ma_format format; /* Must be either ma_format_f32 or ma_format_s16. */
  4177. ma_uint32 channels;
  4178. ma_uint32 sampleRateIn;
  4179. ma_uint32 sampleRateOut;
  4180. ma_resample_algorithm algorithm; /* When set to ma_resample_algorithm_custom, pBackendVTable will be used. */
  4181. ma_resampling_backend_vtable* pBackendVTable;
  4182. void* pBackendUserData;
  4183. struct
  4184. {
  4185. ma_uint32 lpfOrder;
  4186. } linear;
  4187. };
  4188. 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);
  4189. typedef struct
  4190. {
  4191. ma_resampling_backend* pBackend;
  4192. ma_resampling_backend_vtable* pBackendVTable;
  4193. void* pBackendUserData;
  4194. ma_format format;
  4195. ma_uint32 channels;
  4196. ma_uint32 sampleRateIn;
  4197. ma_uint32 sampleRateOut;
  4198. union
  4199. {
  4200. ma_linear_resampler linear;
  4201. } state; /* State for stock resamplers so we can avoid a malloc. For stock resamplers, pBackend will point here. */
  4202. /* Memory management. */
  4203. void* _pHeap;
  4204. ma_bool32 _ownsHeap;
  4205. } ma_resampler;
  4206. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes);
  4207. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler);
  4208. /*
  4209. Initializes a new resampler object from a config.
  4210. */
  4211. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler);
  4212. /*
  4213. Uninitializes a resampler.
  4214. */
  4215. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks);
  4216. /*
  4217. Converts the given input data.
  4218. Both the input and output frames must be in the format specified in the config when the resampler was initilized.
  4219. On input, [pFrameCountOut] contains the number of output frames to process. On output it contains the number of output frames that
  4220. were actually processed, which may be less than the requested amount which will happen if there's not enough input data. You can use
  4221. ma_resampler_get_expected_output_frame_count() to know how many output frames will be processed for a given number of input frames.
  4222. On input, [pFrameCountIn] contains the number of input frames contained in [pFramesIn]. On output it contains the number of whole
  4223. input frames that were actually processed. You can use ma_resampler_get_required_input_frame_count() to know how many input frames
  4224. you should provide for a given number of output frames. [pFramesIn] can be NULL, in which case zeroes will be used instead.
  4225. If [pFramesOut] is NULL, a seek is performed. In this case, if [pFrameCountOut] is not NULL it will seek by the specified number of
  4226. output frames. Otherwise, if [pFramesCountOut] is NULL and [pFrameCountIn] is not NULL, it will seek by the specified number of input
  4227. frames. When seeking, [pFramesIn] is allowed to NULL, in which case the internal timing state will be updated, but no input will be
  4228. processed. In this case, any internal filter state will be updated as if zeroes were passed in.
  4229. It is an error for [pFramesOut] to be non-NULL and [pFrameCountOut] to be NULL.
  4230. It is an error for both [pFrameCountOut] and [pFrameCountIn] to be NULL.
  4231. */
  4232. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut);
  4233. /*
  4234. Sets the input and output sample sample rate.
  4235. */
  4236. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4237. /*
  4238. Sets the input and output sample rate as a ratio.
  4239. The ration is in/out.
  4240. */
  4241. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio);
  4242. /*
  4243. Retrieves the latency introduced by the resampler in input frames.
  4244. */
  4245. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler);
  4246. /*
  4247. Retrieves the latency introduced by the resampler in output frames.
  4248. */
  4249. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler);
  4250. /*
  4251. Calculates the number of whole input frames that would need to be read from the client in order to output the specified
  4252. number of output frames.
  4253. The returned value does not include cached input frames. It only returns the number of extra frames that would need to be
  4254. read from the input buffer in order to output the specified number of output frames.
  4255. */
  4256. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4257. /*
  4258. Calculates the number of whole output frames that would be output after fully reading and consuming the specified number of
  4259. input frames.
  4260. */
  4261. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4262. /*
  4263. Resets the resampler's timer and clears it's internal cache.
  4264. */
  4265. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler);
  4266. /**************************************************************************************************************************************************************
  4267. Channel Conversion
  4268. **************************************************************************************************************************************************************/
  4269. typedef enum
  4270. {
  4271. ma_channel_conversion_path_unknown,
  4272. ma_channel_conversion_path_passthrough,
  4273. ma_channel_conversion_path_mono_out, /* Converting to mono. */
  4274. ma_channel_conversion_path_mono_in, /* Converting from mono. */
  4275. 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. */
  4276. ma_channel_conversion_path_weights /* Blended based on weights. */
  4277. } ma_channel_conversion_path;
  4278. typedef enum
  4279. {
  4280. ma_mono_expansion_mode_duplicate = 0, /* The default. */
  4281. ma_mono_expansion_mode_average, /* Average the mono channel across all channels. */
  4282. ma_mono_expansion_mode_stereo_only, /* Duplicate to the left and right channels only and ignore the others. */
  4283. ma_mono_expansion_mode_default = ma_mono_expansion_mode_duplicate
  4284. } ma_mono_expansion_mode;
  4285. typedef struct
  4286. {
  4287. ma_format format;
  4288. ma_uint32 channelsIn;
  4289. ma_uint32 channelsOut;
  4290. const ma_channel* pChannelMapIn;
  4291. const ma_channel* pChannelMapOut;
  4292. ma_channel_mix_mode mixingMode;
  4293. 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. */
  4294. float** ppWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4295. } ma_channel_converter_config;
  4296. 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);
  4297. typedef struct
  4298. {
  4299. ma_format format;
  4300. ma_uint32 channelsIn;
  4301. ma_uint32 channelsOut;
  4302. ma_channel_mix_mode mixingMode;
  4303. ma_channel_conversion_path conversionPath;
  4304. ma_channel* pChannelMapIn;
  4305. ma_channel* pChannelMapOut;
  4306. ma_uint8* pShuffleTable; /* Indexed by output channel index. */
  4307. union
  4308. {
  4309. float** f32;
  4310. ma_int32** s16;
  4311. } weights; /* [in][out] */
  4312. /* Memory management. */
  4313. void* _pHeap;
  4314. ma_bool32 _ownsHeap;
  4315. } ma_channel_converter;
  4316. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4317. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter);
  4318. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter);
  4319. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4320. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount);
  4321. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4322. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4323. /**************************************************************************************************************************************************************
  4324. Data Conversion
  4325. **************************************************************************************************************************************************************/
  4326. typedef struct
  4327. {
  4328. ma_format formatIn;
  4329. ma_format formatOut;
  4330. ma_uint32 channelsIn;
  4331. ma_uint32 channelsOut;
  4332. ma_uint32 sampleRateIn;
  4333. ma_uint32 sampleRateOut;
  4334. ma_channel* pChannelMapIn;
  4335. ma_channel* pChannelMapOut;
  4336. ma_dither_mode ditherMode;
  4337. ma_channel_mix_mode channelMixMode;
  4338. 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. */
  4339. float** ppChannelWeights; /* [in][out]. Only used when mixingMode is set to ma_channel_mix_mode_custom_weights. */
  4340. ma_bool32 allowDynamicSampleRate;
  4341. ma_resampler_config resampling;
  4342. } ma_data_converter_config;
  4343. MA_API ma_data_converter_config ma_data_converter_config_init_default(void);
  4344. 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);
  4345. typedef enum
  4346. {
  4347. ma_data_converter_execution_path_passthrough, /* No conversion. */
  4348. ma_data_converter_execution_path_format_only, /* Only format conversion. */
  4349. ma_data_converter_execution_path_channels_only, /* Only channel conversion. */
  4350. ma_data_converter_execution_path_resample_only, /* Only resampling. */
  4351. ma_data_converter_execution_path_resample_first, /* All conversions, but resample as the first step. */
  4352. ma_data_converter_execution_path_channels_first /* All conversions, but channels as the first step. */
  4353. } ma_data_converter_execution_path;
  4354. typedef struct
  4355. {
  4356. ma_format formatIn;
  4357. ma_format formatOut;
  4358. ma_uint32 channelsIn;
  4359. ma_uint32 channelsOut;
  4360. ma_uint32 sampleRateIn;
  4361. ma_uint32 sampleRateOut;
  4362. ma_dither_mode ditherMode;
  4363. ma_data_converter_execution_path executionPath; /* The execution path the data converter will follow when processing. */
  4364. ma_channel_converter channelConverter;
  4365. ma_resampler resampler;
  4366. ma_bool8 hasPreFormatConversion;
  4367. ma_bool8 hasPostFormatConversion;
  4368. ma_bool8 hasChannelConverter;
  4369. ma_bool8 hasResampler;
  4370. ma_bool8 isPassthrough;
  4371. /* Memory management. */
  4372. ma_bool8 _ownsHeap;
  4373. void* _pHeap;
  4374. } ma_data_converter;
  4375. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes);
  4376. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter);
  4377. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter);
  4378. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks);
  4379. 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);
  4380. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut);
  4381. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut);
  4382. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter);
  4383. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter);
  4384. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount);
  4385. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount);
  4386. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4387. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap);
  4388. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter);
  4389. /************************************************************************************************************************************************************
  4390. Format Conversion
  4391. ************************************************************************************************************************************************************/
  4392. MA_API void ma_pcm_u8_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4393. MA_API void ma_pcm_u8_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4394. MA_API void ma_pcm_u8_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4395. MA_API void ma_pcm_u8_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4396. MA_API void ma_pcm_s16_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4397. MA_API void ma_pcm_s16_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4398. MA_API void ma_pcm_s16_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4399. MA_API void ma_pcm_s16_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4400. MA_API void ma_pcm_s24_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4401. MA_API void ma_pcm_s24_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4402. MA_API void ma_pcm_s24_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4403. MA_API void ma_pcm_s24_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4404. MA_API void ma_pcm_s32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4405. MA_API void ma_pcm_s32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4406. MA_API void ma_pcm_s32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4407. MA_API void ma_pcm_s32_to_f32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4408. MA_API void ma_pcm_f32_to_u8(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4409. MA_API void ma_pcm_f32_to_s16(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4410. MA_API void ma_pcm_f32_to_s24(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4411. MA_API void ma_pcm_f32_to_s32(void* pOut, const void* pIn, ma_uint64 count, ma_dither_mode ditherMode);
  4412. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode);
  4413. 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);
  4414. /*
  4415. Deinterleaves an interleaved buffer.
  4416. */
  4417. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames);
  4418. /*
  4419. Interleaves a group of deinterleaved buffers.
  4420. */
  4421. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames);
  4422. /************************************************************************************************************************************************************
  4423. Channel Maps
  4424. ************************************************************************************************************************************************************/
  4425. /*
  4426. This is used in the shuffle table to indicate that the channel index is undefined and should be ignored.
  4427. */
  4428. #define MA_CHANNEL_INDEX_NULL 255
  4429. /*
  4430. Retrieves the channel position of the specified channel in the given channel map.
  4431. The pChannelMap parameter can be null, in which case miniaudio's default channel map will be assumed.
  4432. */
  4433. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  4434. /*
  4435. Initializes a blank channel map.
  4436. When a blank channel map is specified anywhere it indicates that the native channel map should be used.
  4437. */
  4438. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels);
  4439. /*
  4440. Helper for retrieving a standard channel map.
  4441. The output channel map buffer must have a capacity of at least `channelMapCap`.
  4442. */
  4443. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels);
  4444. /*
  4445. Copies a channel map.
  4446. Both input and output channel map buffers must have a capacity of at at least `channels`.
  4447. */
  4448. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels);
  4449. /*
  4450. Copies a channel map if one is specified, otherwise copies the default channel map.
  4451. 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`.
  4452. */
  4453. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels);
  4454. /*
  4455. Determines whether or not a channel map is valid.
  4456. 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
  4457. is usually treated as a passthrough.
  4458. Invalid channel maps:
  4459. - A channel map with no channels
  4460. - A channel map with more than one channel and a mono channel
  4461. The channel map buffer must have a capacity of at least `channels`.
  4462. */
  4463. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels);
  4464. /*
  4465. Helper for comparing two channel maps for equality.
  4466. This assumes the channel count is the same between the two.
  4467. Both channels map buffers must have a capacity of at least `channels`.
  4468. */
  4469. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels);
  4470. /*
  4471. Helper for determining if a channel map is blank (all channels set to MA_CHANNEL_NONE).
  4472. The channel map buffer must have a capacity of at least `channels`.
  4473. */
  4474. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels);
  4475. /*
  4476. Helper for determining whether or not a channel is present in the given channel map.
  4477. The channel map buffer must have a capacity of at least `channels`.
  4478. */
  4479. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition);
  4480. /*
  4481. Find a channel position in the given channel map. Returns MA_TRUE if the channel is found; MA_FALSE otherwise. The
  4482. index of the channel is output to `pChannelIndex`.
  4483. The channel map buffer must have a capacity of at least `channels`.
  4484. */
  4485. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex);
  4486. /*
  4487. Generates a string representing the given channel map.
  4488. This is for printing and debugging purposes, not serialization/deserialization.
  4489. Returns the length of the string, not including the null terminator.
  4490. */
  4491. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap);
  4492. /*
  4493. Retrieves a human readable version of a channel position.
  4494. */
  4495. MA_API const char* ma_channel_position_to_string(ma_channel channel);
  4496. /************************************************************************************************************************************************************
  4497. Conversion Helpers
  4498. ************************************************************************************************************************************************************/
  4499. /*
  4500. 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
  4501. determine the required size of the output buffer. frameCountOut should be set to the capacity of pOut. If pOut is NULL, frameCountOut is
  4502. ignored.
  4503. A return value of 0 indicates an error.
  4504. This function is useful for one-off bulk conversions, but if you're streaming data you should use the ma_data_converter APIs instead.
  4505. */
  4506. 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);
  4507. 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);
  4508. /************************************************************************************************************************************************************
  4509. Ring Buffer
  4510. ************************************************************************************************************************************************************/
  4511. typedef struct
  4512. {
  4513. void* pBuffer;
  4514. ma_uint32 subbufferSizeInBytes;
  4515. ma_uint32 subbufferCount;
  4516. ma_uint32 subbufferStrideInBytes;
  4517. 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. */
  4518. 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. */
  4519. ma_bool8 ownsBuffer; /* Used to know whether or not miniaudio is responsible for free()-ing the buffer. */
  4520. ma_bool8 clearOnWriteAcquire; /* When set, clears the acquired write buffer before returning from ma_rb_acquire_write(). */
  4521. ma_allocation_callbacks allocationCallbacks;
  4522. } ma_rb;
  4523. 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);
  4524. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB);
  4525. MA_API void ma_rb_uninit(ma_rb* pRB);
  4526. MA_API void ma_rb_reset(ma_rb* pRB);
  4527. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4528. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes);
  4529. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut);
  4530. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes);
  4531. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes);
  4532. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes);
  4533. 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. */
  4534. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB);
  4535. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB);
  4536. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB);
  4537. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB);
  4538. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex);
  4539. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer);
  4540. typedef struct
  4541. {
  4542. ma_rb rb;
  4543. ma_format format;
  4544. ma_uint32 channels;
  4545. } ma_pcm_rb;
  4546. 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);
  4547. 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);
  4548. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB);
  4549. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB);
  4550. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4551. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4552. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut);
  4553. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames);
  4554. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4555. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames);
  4556. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB); /* Return value is in frames. */
  4557. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB);
  4558. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB);
  4559. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB);
  4560. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB);
  4561. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex);
  4562. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer);
  4563. /*
  4564. 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
  4565. capture device writes to it, and then a playback device reads from it.
  4566. At the moment this is just a simple naive implementation, but in the future I want to implement some dynamic resampling to seamlessly
  4567. handle desyncs. Note that the API is work in progress and may change at any time in any version.
  4568. 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
  4569. in frames. The internal sample rate of the capture device is also needed in order to calculate the size.
  4570. */
  4571. typedef struct
  4572. {
  4573. ma_pcm_rb rb;
  4574. } ma_duplex_rb;
  4575. 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);
  4576. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB);
  4577. /************************************************************************************************************************************************************
  4578. Miscellaneous Helpers
  4579. ************************************************************************************************************************************************************/
  4580. /*
  4581. Retrieves a human readable description of the given result code.
  4582. */
  4583. MA_API const char* ma_result_description(ma_result result);
  4584. /*
  4585. malloc()
  4586. */
  4587. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4588. /*
  4589. calloc()
  4590. */
  4591. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4592. /*
  4593. realloc()
  4594. */
  4595. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks);
  4596. /*
  4597. free()
  4598. */
  4599. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4600. /*
  4601. Performs an aligned malloc, with the assumption that the alignment is a power of 2.
  4602. */
  4603. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks);
  4604. /*
  4605. Free's an aligned malloc'd buffer.
  4606. */
  4607. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks);
  4608. /*
  4609. Retrieves a friendly name for a format.
  4610. */
  4611. MA_API const char* ma_get_format_name(ma_format format);
  4612. /*
  4613. Blends two frames in floating point format.
  4614. */
  4615. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels);
  4616. /*
  4617. Retrieves the size of a sample in bytes for the given format.
  4618. This API is efficient and is implemented using a lookup table.
  4619. Thread Safety: SAFE
  4620. This API is pure.
  4621. */
  4622. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format);
  4623. static MA_INLINE ma_uint32 ma_get_bytes_per_frame(ma_format format, ma_uint32 channels) { return ma_get_bytes_per_sample(format) * channels; }
  4624. /*
  4625. Converts a log level to a string.
  4626. */
  4627. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel);
  4628. /************************************************************************************************************************************************************
  4629. Synchronization
  4630. ************************************************************************************************************************************************************/
  4631. /*
  4632. Locks a spinlock.
  4633. */
  4634. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock);
  4635. /*
  4636. Locks a spinlock, but does not yield() when looping.
  4637. */
  4638. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock);
  4639. /*
  4640. Unlocks a spinlock.
  4641. */
  4642. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock);
  4643. #ifndef MA_NO_THREADING
  4644. /*
  4645. Creates a mutex.
  4646. A mutex must be created from a valid context. A mutex is initially unlocked.
  4647. */
  4648. MA_API ma_result ma_mutex_init(ma_mutex* pMutex);
  4649. /*
  4650. Deletes a mutex.
  4651. */
  4652. MA_API void ma_mutex_uninit(ma_mutex* pMutex);
  4653. /*
  4654. Locks a mutex with an infinite timeout.
  4655. */
  4656. MA_API void ma_mutex_lock(ma_mutex* pMutex);
  4657. /*
  4658. Unlocks a mutex.
  4659. */
  4660. MA_API void ma_mutex_unlock(ma_mutex* pMutex);
  4661. /*
  4662. Initializes an auto-reset event.
  4663. */
  4664. MA_API ma_result ma_event_init(ma_event* pEvent);
  4665. /*
  4666. Uninitializes an auto-reset event.
  4667. */
  4668. MA_API void ma_event_uninit(ma_event* pEvent);
  4669. /*
  4670. Waits for the specified auto-reset event to become signalled.
  4671. */
  4672. MA_API ma_result ma_event_wait(ma_event* pEvent);
  4673. /*
  4674. Signals the specified auto-reset event.
  4675. */
  4676. MA_API ma_result ma_event_signal(ma_event* pEvent);
  4677. #endif /* MA_NO_THREADING */
  4678. /*
  4679. Fence
  4680. =====
  4681. This locks while the counter is larger than 0. Counter can be incremented and decremented by any
  4682. thread, but care needs to be taken when waiting. It is possible for one thread to acquire the
  4683. fence just as another thread returns from ma_fence_wait().
  4684. The idea behind a fence is to allow you to wait for a group of operations to complete. When an
  4685. operation starts, the counter is incremented which locks the fence. When the operation completes,
  4686. the fence will be released which decrements the counter. ma_fence_wait() will block until the
  4687. counter hits zero.
  4688. If threading is disabled, ma_fence_wait() will spin on the counter.
  4689. */
  4690. typedef struct
  4691. {
  4692. #ifndef MA_NO_THREADING
  4693. ma_event e;
  4694. #endif
  4695. ma_uint32 counter;
  4696. } ma_fence;
  4697. MA_API ma_result ma_fence_init(ma_fence* pFence);
  4698. MA_API void ma_fence_uninit(ma_fence* pFence);
  4699. MA_API ma_result ma_fence_acquire(ma_fence* pFence); /* Increment counter. */
  4700. MA_API ma_result ma_fence_release(ma_fence* pFence); /* Decrement counter. */
  4701. MA_API ma_result ma_fence_wait(ma_fence* pFence); /* Wait for counter to reach 0. */
  4702. /*
  4703. Notification callback for asynchronous operations.
  4704. */
  4705. typedef void ma_async_notification;
  4706. typedef struct
  4707. {
  4708. void (* onSignal)(ma_async_notification* pNotification);
  4709. } ma_async_notification_callbacks;
  4710. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification);
  4711. /*
  4712. Simple polling notification.
  4713. This just sets a variable when the notification has been signalled which is then polled with ma_async_notification_poll_is_signalled()
  4714. */
  4715. typedef struct
  4716. {
  4717. ma_async_notification_callbacks cb;
  4718. ma_bool32 signalled;
  4719. } ma_async_notification_poll;
  4720. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll);
  4721. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll);
  4722. /*
  4723. Event Notification
  4724. This uses an ma_event. If threading is disabled (MA_NO_THREADING), initialization will fail.
  4725. */
  4726. typedef struct
  4727. {
  4728. ma_async_notification_callbacks cb;
  4729. #ifndef MA_NO_THREADING
  4730. ma_event e;
  4731. #endif
  4732. } ma_async_notification_event;
  4733. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent);
  4734. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent);
  4735. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent);
  4736. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent);
  4737. /************************************************************************************************************************************************************
  4738. Job Queue
  4739. ************************************************************************************************************************************************************/
  4740. /*
  4741. Slot Allocator
  4742. --------------
  4743. 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
  4744. as the insertion point for an object.
  4745. Slots are reference counted to help mitigate the ABA problem in the lock-free queue we use for tracking jobs.
  4746. The slot index is stored in the low 32 bits. The reference counter is stored in the high 32 bits:
  4747. +-----------------+-----------------+
  4748. | 32 Bits | 32 Bits |
  4749. +-----------------+-----------------+
  4750. | Reference Count | Slot Index |
  4751. +-----------------+-----------------+
  4752. */
  4753. typedef struct
  4754. {
  4755. ma_uint32 capacity; /* The number of slots to make available. */
  4756. } ma_slot_allocator_config;
  4757. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity);
  4758. typedef struct
  4759. {
  4760. 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. */
  4761. } ma_slot_allocator_group;
  4762. typedef struct
  4763. {
  4764. ma_slot_allocator_group* pGroups; /* Slots are grouped in chunks of 32. */
  4765. ma_uint32* pSlots; /* 32 bits for reference counting for ABA mitigation. */
  4766. ma_uint32 count; /* Allocation count. */
  4767. ma_uint32 capacity;
  4768. /* Memory management. */
  4769. ma_bool32 _ownsHeap;
  4770. void* _pHeap;
  4771. } ma_slot_allocator;
  4772. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes);
  4773. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator);
  4774. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator);
  4775. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks);
  4776. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot);
  4777. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot);
  4778. typedef struct ma_job ma_job;
  4779. /*
  4780. Callback for processing a job. Each job type will have their own processing callback which will be
  4781. called by ma_job_process().
  4782. */
  4783. typedef ma_result (* ma_job_proc)(ma_job* pJob);
  4784. /* When a job type is added here an callback needs to be added go "g_jobVTable" in the implementation section. */
  4785. typedef enum
  4786. {
  4787. /* Miscellaneous. */
  4788. MA_JOB_TYPE_QUIT = 0,
  4789. MA_JOB_TYPE_CUSTOM,
  4790. /* Resource Manager. */
  4791. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE,
  4792. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE,
  4793. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE,
  4794. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER,
  4795. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER,
  4796. MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM,
  4797. MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM,
  4798. MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM,
  4799. MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM,
  4800. /* Device. */
  4801. MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE,
  4802. /* Count. Must always be last. */
  4803. MA_JOB_TYPE_COUNT
  4804. } ma_job_type;
  4805. struct ma_job
  4806. {
  4807. union
  4808. {
  4809. struct
  4810. {
  4811. ma_uint16 code; /* Job type. */
  4812. ma_uint16 slot; /* Index into a ma_slot_allocator. */
  4813. ma_uint32 refcount;
  4814. } breakup;
  4815. ma_uint64 allocation;
  4816. } toc; /* 8 bytes. We encode the job code into the slot allocation data to save space. */
  4817. MA_ATOMIC(8, ma_uint64) next; /* refcount + slot for the next item. Does not include the job code. */
  4818. 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. */
  4819. union
  4820. {
  4821. /* Miscellaneous. */
  4822. struct
  4823. {
  4824. ma_job_proc proc;
  4825. ma_uintptr data0;
  4826. ma_uintptr data1;
  4827. } custom;
  4828. /* Resource Manager */
  4829. union
  4830. {
  4831. struct
  4832. {
  4833. /*ma_resource_manager**/ void* pResourceManager;
  4834. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  4835. char* pFilePath;
  4836. wchar_t* pFilePathW;
  4837. ma_uint32 flags; /* Resource manager data source flags that were used when initializing the data buffer. */
  4838. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  4839. 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. */
  4840. ma_fence* pInitFence; /* Released when initialization of the decoder is complete. */
  4841. ma_fence* pDoneFence; /* Released if initialization of the decoder fails. Passed through to PAGE_DATA_BUFFER_NODE untouched if init is successful. */
  4842. } loadDataBufferNode;
  4843. struct
  4844. {
  4845. /*ma_resource_manager**/ void* pResourceManager;
  4846. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  4847. ma_async_notification* pDoneNotification;
  4848. ma_fence* pDoneFence;
  4849. } freeDataBufferNode;
  4850. struct
  4851. {
  4852. /*ma_resource_manager**/ void* pResourceManager;
  4853. /*ma_resource_manager_data_buffer_node**/ void* pDataBufferNode;
  4854. /*ma_decoder**/ void* pDecoder;
  4855. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  4856. ma_fence* pDoneFence; /* Passed through from LOAD_DATA_BUFFER_NODE and released when the data buffer completes decoding or an error occurs. */
  4857. } pageDataBufferNode;
  4858. struct
  4859. {
  4860. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  4861. ma_async_notification* pInitNotification; /* Signalled when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  4862. ma_async_notification* pDoneNotification; /* Signalled when the data buffer has been fully decoded. */
  4863. ma_fence* pInitFence; /* Released when the data buffer has been initialized and the format/channels/rate can be retrieved. */
  4864. ma_fence* pDoneFence; /* Released when the data buffer has been fully decoded. */
  4865. ma_uint64 rangeBegInPCMFrames;
  4866. ma_uint64 rangeEndInPCMFrames;
  4867. ma_uint64 loopPointBegInPCMFrames;
  4868. ma_uint64 loopPointEndInPCMFrames;
  4869. ma_uint32 isLooping;
  4870. } loadDataBuffer;
  4871. struct
  4872. {
  4873. /*ma_resource_manager_data_buffer**/ void* pDataBuffer;
  4874. ma_async_notification* pDoneNotification;
  4875. ma_fence* pDoneFence;
  4876. } freeDataBuffer;
  4877. struct
  4878. {
  4879. /*ma_resource_manager_data_stream**/ void* pDataStream;
  4880. char* pFilePath; /* Allocated when the job is posted, freed by the job thread after loading. */
  4881. wchar_t* pFilePathW; /* ^ As above ^. Only used if pFilePath is NULL. */
  4882. ma_uint64 initialSeekPoint;
  4883. ma_async_notification* pInitNotification; /* Signalled after the first two pages have been decoded and frames can be read from the stream. */
  4884. ma_fence* pInitFence;
  4885. } loadDataStream;
  4886. struct
  4887. {
  4888. /*ma_resource_manager_data_stream**/ void* pDataStream;
  4889. ma_async_notification* pDoneNotification;
  4890. ma_fence* pDoneFence;
  4891. } freeDataStream;
  4892. struct
  4893. {
  4894. /*ma_resource_manager_data_stream**/ void* pDataStream;
  4895. ma_uint32 pageIndex; /* The index of the page to decode into. */
  4896. } pageDataStream;
  4897. struct
  4898. {
  4899. /*ma_resource_manager_data_stream**/ void* pDataStream;
  4900. ma_uint64 frameIndex;
  4901. } seekDataStream;
  4902. } resourceManager;
  4903. /* Device. */
  4904. union
  4905. {
  4906. union
  4907. {
  4908. struct
  4909. {
  4910. /*ma_device**/ void* pDevice;
  4911. /*ma_device_type*/ ma_uint32 deviceType;
  4912. } reroute;
  4913. } aaudio;
  4914. } device;
  4915. } data;
  4916. };
  4917. MA_API ma_job ma_job_init(ma_uint16 code);
  4918. MA_API ma_result ma_job_process(ma_job* pJob);
  4919. /*
  4920. When set, ma_job_queue_next() will not wait and no semaphore will be signaled in
  4921. ma_job_queue_post(). ma_job_queue_next() will return MA_NO_DATA_AVAILABLE if nothing is available.
  4922. This flag should always be used for platforms that do not support multithreading.
  4923. */
  4924. typedef enum
  4925. {
  4926. MA_JOB_QUEUE_FLAG_NON_BLOCKING = 0x00000001
  4927. } ma_job_queue_flags;
  4928. typedef struct
  4929. {
  4930. ma_uint32 flags;
  4931. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. */
  4932. } ma_job_queue_config;
  4933. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity);
  4934. typedef struct
  4935. {
  4936. ma_uint32 flags; /* Flags passed in at initialization time. */
  4937. ma_uint32 capacity; /* The maximum number of jobs that can fit in the queue at a time. Set by the config. */
  4938. MA_ATOMIC(8, ma_uint64) head; /* The first item in the list. Required for removing from the top of the list. */
  4939. MA_ATOMIC(8, ma_uint64) tail; /* The last item in the list. Required for appending to the end of the list. */
  4940. #ifndef MA_NO_THREADING
  4941. ma_semaphore sem; /* Only used when MA_JOB_QUEUE_FLAG_NON_BLOCKING is unset. */
  4942. #endif
  4943. ma_slot_allocator allocator;
  4944. ma_job* pJobs;
  4945. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  4946. ma_spinlock lock;
  4947. #endif
  4948. /* Memory management. */
  4949. void* _pHeap;
  4950. ma_bool32 _ownsHeap;
  4951. } ma_job_queue;
  4952. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes);
  4953. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue);
  4954. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue);
  4955. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks);
  4956. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob);
  4957. 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. */
  4958. /************************************************************************************************************************************************************
  4959. *************************************************************************************************************************************************************
  4960. DEVICE I/O
  4961. ==========
  4962. This section contains the APIs for device playback and capture. Here is where you'll find ma_device_init(), etc.
  4963. *************************************************************************************************************************************************************
  4964. ************************************************************************************************************************************************************/
  4965. #ifndef MA_NO_DEVICE_IO
  4966. /* Some backends are only supported on certain platforms. */
  4967. #if defined(MA_WIN32)
  4968. #define MA_SUPPORT_WASAPI
  4969. #if defined(MA_WIN32_DESKTOP) /* DirectSound and WinMM backends are only supported on desktops. */
  4970. #define MA_SUPPORT_DSOUND
  4971. #define MA_SUPPORT_WINMM
  4972. #define MA_SUPPORT_JACK /* JACK is technically supported on Windows, but I don't know how many people use it in practice... */
  4973. #endif
  4974. #endif
  4975. #if defined(MA_UNIX)
  4976. #if defined(MA_LINUX)
  4977. #if !defined(MA_ANDROID) /* ALSA is not supported on Android. */
  4978. #define MA_SUPPORT_ALSA
  4979. #endif
  4980. #endif
  4981. #if !defined(MA_BSD) && !defined(MA_ANDROID) && !defined(MA_EMSCRIPTEN)
  4982. #define MA_SUPPORT_PULSEAUDIO
  4983. #define MA_SUPPORT_JACK
  4984. #endif
  4985. #if defined(__OpenBSD__) /* <-- Change this to "#if defined(MA_BSD)" to enable sndio on all BSD flavors. */
  4986. #define MA_SUPPORT_SNDIO /* sndio is only supported on OpenBSD for now. May be expanded later if there's demand. */
  4987. #endif
  4988. #if defined(__NetBSD__) || defined(__OpenBSD__)
  4989. #define MA_SUPPORT_AUDIO4 /* Only support audio(4) on platforms with known support. */
  4990. #endif
  4991. #if defined(__FreeBSD__) || defined(__DragonFly__)
  4992. #define MA_SUPPORT_OSS /* Only support OSS on specific platforms with known support. */
  4993. #endif
  4994. #endif
  4995. #if defined(MA_ANDROID)
  4996. #define MA_SUPPORT_AAUDIO
  4997. #define MA_SUPPORT_OPENSL
  4998. #endif
  4999. #if defined(MA_APPLE)
  5000. #define MA_SUPPORT_COREAUDIO
  5001. #endif
  5002. #if defined(MA_EMSCRIPTEN)
  5003. #define MA_SUPPORT_WEBAUDIO
  5004. #endif
  5005. /* All platforms should support custom backends. */
  5006. #define MA_SUPPORT_CUSTOM
  5007. /* Explicitly disable the Null backend for Emscripten because it uses a background thread which is not properly supported right now. */
  5008. #if !defined(MA_EMSCRIPTEN)
  5009. #define MA_SUPPORT_NULL
  5010. #endif
  5011. #if defined(MA_SUPPORT_WASAPI) && !defined(MA_NO_WASAPI) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WASAPI))
  5012. #define MA_HAS_WASAPI
  5013. #endif
  5014. #if defined(MA_SUPPORT_DSOUND) && !defined(MA_NO_DSOUND) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_DSOUND))
  5015. #define MA_HAS_DSOUND
  5016. #endif
  5017. #if defined(MA_SUPPORT_WINMM) && !defined(MA_NO_WINMM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WINMM))
  5018. #define MA_HAS_WINMM
  5019. #endif
  5020. #if defined(MA_SUPPORT_ALSA) && !defined(MA_NO_ALSA) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_ALSA))
  5021. #define MA_HAS_ALSA
  5022. #endif
  5023. #if defined(MA_SUPPORT_PULSEAUDIO) && !defined(MA_NO_PULSEAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_PULSEAUDIO))
  5024. #define MA_HAS_PULSEAUDIO
  5025. #endif
  5026. #if defined(MA_SUPPORT_JACK) && !defined(MA_NO_JACK) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_JACK))
  5027. #define MA_HAS_JACK
  5028. #endif
  5029. #if defined(MA_SUPPORT_COREAUDIO) && !defined(MA_NO_COREAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_COREAUDIO))
  5030. #define MA_HAS_COREAUDIO
  5031. #endif
  5032. #if defined(MA_SUPPORT_SNDIO) && !defined(MA_NO_SNDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_SNDIO))
  5033. #define MA_HAS_SNDIO
  5034. #endif
  5035. #if defined(MA_SUPPORT_AUDIO4) && !defined(MA_NO_AUDIO4) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AUDIO4))
  5036. #define MA_HAS_AUDIO4
  5037. #endif
  5038. #if defined(MA_SUPPORT_OSS) && !defined(MA_NO_OSS) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OSS))
  5039. #define MA_HAS_OSS
  5040. #endif
  5041. #if defined(MA_SUPPORT_AAUDIO) && !defined(MA_NO_AAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_AAUDIO))
  5042. #define MA_HAS_AAUDIO
  5043. #endif
  5044. #if defined(MA_SUPPORT_OPENSL) && !defined(MA_NO_OPENSL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_OPENSL))
  5045. #define MA_HAS_OPENSL
  5046. #endif
  5047. #if defined(MA_SUPPORT_WEBAUDIO) && !defined(MA_NO_WEBAUDIO) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_WEBAUDIO))
  5048. #define MA_HAS_WEBAUDIO
  5049. #endif
  5050. #if defined(MA_SUPPORT_CUSTOM) && !defined(MA_NO_CUSTOM) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_CUSTOM))
  5051. #define MA_HAS_CUSTOM
  5052. #endif
  5053. #if defined(MA_SUPPORT_NULL) && !defined(MA_NO_NULL) && (!defined(MA_ENABLE_ONLY_SPECIFIC_BACKENDS) || defined(MA_ENABLE_NULL))
  5054. #define MA_HAS_NULL
  5055. #endif
  5056. typedef enum
  5057. {
  5058. ma_device_state_uninitialized = 0,
  5059. ma_device_state_stopped = 1, /* The device's default state after initialization. */
  5060. ma_device_state_started = 2, /* The device is started and is requesting and/or delivering audio data. */
  5061. ma_device_state_starting = 3, /* Transitioning from a stopped state to started. */
  5062. ma_device_state_stopping = 4 /* Transitioning from a started state to stopped. */
  5063. } ma_device_state;
  5064. #ifdef MA_SUPPORT_WASAPI
  5065. /* We need a IMMNotificationClient object for WASAPI. */
  5066. typedef struct
  5067. {
  5068. void* lpVtbl;
  5069. ma_uint32 counter;
  5070. ma_device* pDevice;
  5071. } ma_IMMNotificationClient;
  5072. #endif
  5073. /* Backend enums must be in priority order. */
  5074. typedef enum
  5075. {
  5076. ma_backend_wasapi,
  5077. ma_backend_dsound,
  5078. ma_backend_winmm,
  5079. ma_backend_coreaudio,
  5080. ma_backend_sndio,
  5081. ma_backend_audio4,
  5082. ma_backend_oss,
  5083. ma_backend_pulseaudio,
  5084. ma_backend_alsa,
  5085. ma_backend_jack,
  5086. ma_backend_aaudio,
  5087. ma_backend_opensl,
  5088. ma_backend_webaudio,
  5089. ma_backend_custom, /* <-- Custom backend, with callbacks defined by the context config. */
  5090. ma_backend_null /* <-- Must always be the last item. Lowest priority, and used as the terminator for backend enumeration. */
  5091. } ma_backend;
  5092. #define MA_BACKEND_COUNT (ma_backend_null+1)
  5093. /*
  5094. Device job thread. This is used by backends that require asynchronous processing of certain
  5095. operations. It is not used by all backends.
  5096. The device job thread is made up of a thread and a job queue. You can post a job to the thread with
  5097. ma_device_job_thread_post(). The thread will do the processing of the job.
  5098. */
  5099. typedef struct
  5100. {
  5101. ma_bool32 noThread; /* Set this to true if you want to process jobs yourself. */
  5102. ma_uint32 jobQueueCapacity;
  5103. ma_uint32 jobQueueFlags;
  5104. } ma_device_job_thread_config;
  5105. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void);
  5106. typedef struct
  5107. {
  5108. ma_thread thread;
  5109. ma_job_queue jobQueue;
  5110. ma_bool32 _hasThread;
  5111. } ma_device_job_thread;
  5112. 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);
  5113. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks);
  5114. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob);
  5115. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob);
  5116. /* Device notification types. */
  5117. typedef enum
  5118. {
  5119. ma_device_notification_type_started,
  5120. ma_device_notification_type_stopped,
  5121. ma_device_notification_type_rerouted,
  5122. ma_device_notification_type_interruption_began,
  5123. ma_device_notification_type_interruption_ended
  5124. } ma_device_notification_type;
  5125. typedef struct
  5126. {
  5127. ma_device* pDevice;
  5128. ma_device_notification_type type;
  5129. union
  5130. {
  5131. struct
  5132. {
  5133. int _unused;
  5134. } started;
  5135. struct
  5136. {
  5137. int _unused;
  5138. } stopped;
  5139. struct
  5140. {
  5141. int _unused;
  5142. } rerouted;
  5143. struct
  5144. {
  5145. int _unused;
  5146. } interruption;
  5147. } data;
  5148. } ma_device_notification;
  5149. /*
  5150. The notification callback for when the application should be notified of a change to the device.
  5151. This callback is used for notifying the application of changes such as when the device has started,
  5152. stopped, rerouted or an interruption has occurred. Note that not all backends will post all
  5153. notification types. For example, some backends will perform automatic stream routing without any
  5154. kind of notification to the host program which means miniaudio will never know about it and will
  5155. never be able to fire the rerouted notification. You should keep this in mind when designing your
  5156. program.
  5157. The stopped notification will *not* get fired when a device is rerouted.
  5158. Parameters
  5159. ----------
  5160. pNotification (in)
  5161. A pointer to a structure containing information about the event. Use the `pDevice` member of
  5162. this object to retrieve the relevant device. The `type` member can be used to discriminate
  5163. against each of the notification types.
  5164. Remarks
  5165. -------
  5166. Do not restart or uninitialize the device from the callback.
  5167. Not all notifications will be triggered by all backends, however the started and stopped events
  5168. should be reliable for all backends. Some backends do not have a good way to detect device
  5169. stoppages due to unplugging the device which may result in the stopped callback not getting
  5170. fired. This has been observed with at least one BSD variant.
  5171. The rerouted notification is fired *after* the reroute has occurred. The stopped notification will
  5172. *not* get fired when a device is rerouted. The following backends are known to do automatic stream
  5173. rerouting, but do not have a way to be notified of the change:
  5174. * DirectSound
  5175. The interruption notifications are used on mobile platforms for detecting when audio is interrupted
  5176. due to things like an incoming phone call. Currently this is only implemented on iOS. None of the
  5177. Android backends will report this notification.
  5178. */
  5179. typedef void (* ma_device_notification_proc)(const ma_device_notification* pNotification);
  5180. /*
  5181. The callback for processing audio data from the device.
  5182. 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
  5183. 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
  5184. callback will be fired with a consistent frame count.
  5185. Parameters
  5186. ----------
  5187. pDevice (in)
  5188. A pointer to the relevant device.
  5189. pOutput (out)
  5190. 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
  5191. full-duplex device and null for a capture and loopback device.
  5192. pInput (in)
  5193. 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
  5194. playback device.
  5195. frameCount (in)
  5196. 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
  5197. `periodSizeInFrames` and `periodSizeInMilliseconds` members of the device config are just hints, and are not necessarily exactly what you'll get. You must
  5198. not assume this will always be the same value each time the callback is fired.
  5199. Remarks
  5200. -------
  5201. 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
  5202. callback. The following APIs cannot be called from inside the callback:
  5203. ma_device_init()
  5204. ma_device_init_ex()
  5205. ma_device_uninit()
  5206. ma_device_start()
  5207. ma_device_stop()
  5208. The proper way to stop the device is to call `ma_device_stop()` from a different thread, normally the main application thread.
  5209. */
  5210. typedef void (* ma_device_data_proc)(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  5211. /*
  5212. DEPRECATED. Use ma_device_notification_proc instead.
  5213. The callback for when the device has been stopped.
  5214. 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
  5215. such as being unplugged or an internal error occuring.
  5216. Parameters
  5217. ----------
  5218. pDevice (in)
  5219. A pointer to the device that has just stopped.
  5220. Remarks
  5221. -------
  5222. Do not restart or uninitialize the device from the callback.
  5223. */
  5224. typedef void (* ma_stop_proc)(ma_device* pDevice); /* DEPRECATED. Use ma_device_notification_proc instead. */
  5225. typedef enum
  5226. {
  5227. ma_device_type_playback = 1,
  5228. ma_device_type_capture = 2,
  5229. ma_device_type_duplex = ma_device_type_playback | ma_device_type_capture, /* 3 */
  5230. ma_device_type_loopback = 4
  5231. } ma_device_type;
  5232. typedef enum
  5233. {
  5234. ma_share_mode_shared = 0,
  5235. ma_share_mode_exclusive
  5236. } ma_share_mode;
  5237. /* iOS/tvOS/watchOS session categories. */
  5238. typedef enum
  5239. {
  5240. ma_ios_session_category_default = 0, /* AVAudioSessionCategoryPlayAndRecord. */
  5241. ma_ios_session_category_none, /* Leave the session category unchanged. */
  5242. ma_ios_session_category_ambient, /* AVAudioSessionCategoryAmbient */
  5243. ma_ios_session_category_solo_ambient, /* AVAudioSessionCategorySoloAmbient */
  5244. ma_ios_session_category_playback, /* AVAudioSessionCategoryPlayback */
  5245. ma_ios_session_category_record, /* AVAudioSessionCategoryRecord */
  5246. ma_ios_session_category_play_and_record, /* AVAudioSessionCategoryPlayAndRecord */
  5247. ma_ios_session_category_multi_route /* AVAudioSessionCategoryMultiRoute */
  5248. } ma_ios_session_category;
  5249. /* iOS/tvOS/watchOS session category options */
  5250. typedef enum
  5251. {
  5252. ma_ios_session_category_option_mix_with_others = 0x01, /* AVAudioSessionCategoryOptionMixWithOthers */
  5253. ma_ios_session_category_option_duck_others = 0x02, /* AVAudioSessionCategoryOptionDuckOthers */
  5254. ma_ios_session_category_option_allow_bluetooth = 0x04, /* AVAudioSessionCategoryOptionAllowBluetooth */
  5255. ma_ios_session_category_option_default_to_speaker = 0x08, /* AVAudioSessionCategoryOptionDefaultToSpeaker */
  5256. ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others = 0x11, /* AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers */
  5257. ma_ios_session_category_option_allow_bluetooth_a2dp = 0x20, /* AVAudioSessionCategoryOptionAllowBluetoothA2DP */
  5258. ma_ios_session_category_option_allow_air_play = 0x40, /* AVAudioSessionCategoryOptionAllowAirPlay */
  5259. } ma_ios_session_category_option;
  5260. /* OpenSL stream types. */
  5261. typedef enum
  5262. {
  5263. ma_opensl_stream_type_default = 0, /* Leaves the stream type unset. */
  5264. ma_opensl_stream_type_voice, /* SL_ANDROID_STREAM_VOICE */
  5265. ma_opensl_stream_type_system, /* SL_ANDROID_STREAM_SYSTEM */
  5266. ma_opensl_stream_type_ring, /* SL_ANDROID_STREAM_RING */
  5267. ma_opensl_stream_type_media, /* SL_ANDROID_STREAM_MEDIA */
  5268. ma_opensl_stream_type_alarm, /* SL_ANDROID_STREAM_ALARM */
  5269. ma_opensl_stream_type_notification /* SL_ANDROID_STREAM_NOTIFICATION */
  5270. } ma_opensl_stream_type;
  5271. /* OpenSL recording presets. */
  5272. typedef enum
  5273. {
  5274. ma_opensl_recording_preset_default = 0, /* Leaves the input preset unset. */
  5275. ma_opensl_recording_preset_generic, /* SL_ANDROID_RECORDING_PRESET_GENERIC */
  5276. ma_opensl_recording_preset_camcorder, /* SL_ANDROID_RECORDING_PRESET_CAMCORDER */
  5277. ma_opensl_recording_preset_voice_recognition, /* SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION */
  5278. ma_opensl_recording_preset_voice_communication, /* SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION */
  5279. ma_opensl_recording_preset_voice_unprocessed /* SL_ANDROID_RECORDING_PRESET_UNPROCESSED */
  5280. } ma_opensl_recording_preset;
  5281. /* WASAPI audio thread priority characteristics. */
  5282. typedef enum
  5283. {
  5284. ma_wasapi_usage_default = 0,
  5285. ma_wasapi_usage_games,
  5286. ma_wasapi_usage_pro_audio,
  5287. } ma_wasapi_usage;
  5288. /* AAudio usage types. */
  5289. typedef enum
  5290. {
  5291. ma_aaudio_usage_default = 0, /* Leaves the usage type unset. */
  5292. ma_aaudio_usage_media, /* AAUDIO_USAGE_MEDIA */
  5293. ma_aaudio_usage_voice_communication, /* AAUDIO_USAGE_VOICE_COMMUNICATION */
  5294. ma_aaudio_usage_voice_communication_signalling, /* AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING */
  5295. ma_aaudio_usage_alarm, /* AAUDIO_USAGE_ALARM */
  5296. ma_aaudio_usage_notification, /* AAUDIO_USAGE_NOTIFICATION */
  5297. ma_aaudio_usage_notification_ringtone, /* AAUDIO_USAGE_NOTIFICATION_RINGTONE */
  5298. ma_aaudio_usage_notification_event, /* AAUDIO_USAGE_NOTIFICATION_EVENT */
  5299. ma_aaudio_usage_assistance_accessibility, /* AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY */
  5300. ma_aaudio_usage_assistance_navigation_guidance, /* AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE */
  5301. ma_aaudio_usage_assistance_sonification, /* AAUDIO_USAGE_ASSISTANCE_SONIFICATION */
  5302. ma_aaudio_usage_game, /* AAUDIO_USAGE_GAME */
  5303. ma_aaudio_usage_assitant, /* AAUDIO_USAGE_ASSISTANT */
  5304. ma_aaudio_usage_emergency, /* AAUDIO_SYSTEM_USAGE_EMERGENCY */
  5305. ma_aaudio_usage_safety, /* AAUDIO_SYSTEM_USAGE_SAFETY */
  5306. ma_aaudio_usage_vehicle_status, /* AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS */
  5307. ma_aaudio_usage_announcement /* AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT */
  5308. } ma_aaudio_usage;
  5309. /* AAudio content types. */
  5310. typedef enum
  5311. {
  5312. ma_aaudio_content_type_default = 0, /* Leaves the content type unset. */
  5313. ma_aaudio_content_type_speech, /* AAUDIO_CONTENT_TYPE_SPEECH */
  5314. ma_aaudio_content_type_music, /* AAUDIO_CONTENT_TYPE_MUSIC */
  5315. ma_aaudio_content_type_movie, /* AAUDIO_CONTENT_TYPE_MOVIE */
  5316. ma_aaudio_content_type_sonification /* AAUDIO_CONTENT_TYPE_SONIFICATION */
  5317. } ma_aaudio_content_type;
  5318. /* AAudio input presets. */
  5319. typedef enum
  5320. {
  5321. ma_aaudio_input_preset_default = 0, /* Leaves the input preset unset. */
  5322. ma_aaudio_input_preset_generic, /* AAUDIO_INPUT_PRESET_GENERIC */
  5323. ma_aaudio_input_preset_camcorder, /* AAUDIO_INPUT_PRESET_CAMCORDER */
  5324. ma_aaudio_input_preset_voice_recognition, /* AAUDIO_INPUT_PRESET_VOICE_RECOGNITION */
  5325. ma_aaudio_input_preset_voice_communication, /* AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION */
  5326. ma_aaudio_input_preset_unprocessed, /* AAUDIO_INPUT_PRESET_UNPROCESSED */
  5327. ma_aaudio_input_preset_voice_performance /* AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE */
  5328. } ma_aaudio_input_preset;
  5329. typedef union
  5330. {
  5331. ma_int64 counter;
  5332. double counterD;
  5333. } ma_timer;
  5334. typedef union
  5335. {
  5336. wchar_t wasapi[64]; /* WASAPI uses a wchar_t string for identification. */
  5337. ma_uint8 dsound[16]; /* DirectSound uses a GUID for identification. */
  5338. /*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. */
  5339. char alsa[256]; /* ALSA uses a name string for identification. */
  5340. char pulse[256]; /* PulseAudio uses a name string for identification. */
  5341. int jack; /* JACK always uses default devices. */
  5342. char coreaudio[256]; /* Core Audio uses a string for identification. */
  5343. char sndio[256]; /* "snd/0", etc. */
  5344. char audio4[256]; /* "/dev/audio", etc. */
  5345. char oss[64]; /* "dev/dsp0", etc. "dev/dsp" for the default device. */
  5346. ma_int32 aaudio; /* AAudio uses a 32-bit integer for identification. */
  5347. ma_uint32 opensl; /* OpenSL|ES uses a 32-bit unsigned integer for identification. */
  5348. char webaudio[32]; /* Web Audio always uses default devices for now, but if this changes it'll be a GUID. */
  5349. union
  5350. {
  5351. int i;
  5352. char s[256];
  5353. void* p;
  5354. } custom; /* The custom backend could be anything. Give them a few options. */
  5355. int nullbackend; /* The null backend uses an integer for device IDs. */
  5356. } ma_device_id;
  5357. typedef struct ma_context_config ma_context_config;
  5358. typedef struct ma_device_config ma_device_config;
  5359. typedef struct ma_backend_callbacks ma_backend_callbacks;
  5360. #define MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE (1U << 1) /* If set, this is supported in exclusive mode. Otherwise not natively supported by exclusive mode. */
  5361. #ifndef MA_MAX_DEVICE_NAME_LENGTH
  5362. #define MA_MAX_DEVICE_NAME_LENGTH 255
  5363. #endif
  5364. typedef struct
  5365. {
  5366. /* Basic info. This is the only information guaranteed to be filled in during device enumeration. */
  5367. ma_device_id id;
  5368. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* +1 for null terminator. */
  5369. ma_bool32 isDefault;
  5370. ma_uint32 nativeDataFormatCount;
  5371. struct
  5372. {
  5373. ma_format format; /* Sample format. If set to ma_format_unknown, all sample formats are supported. */
  5374. ma_uint32 channels; /* If set to 0, all channels are supported. */
  5375. ma_uint32 sampleRate; /* If set to 0, all sample rates are supported. */
  5376. ma_uint32 flags; /* A combination of MA_DATA_FORMAT_FLAG_* flags. */
  5377. } 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. */
  5378. } ma_device_info;
  5379. struct ma_device_config
  5380. {
  5381. ma_device_type deviceType;
  5382. ma_uint32 sampleRate;
  5383. ma_uint32 periodSizeInFrames;
  5384. ma_uint32 periodSizeInMilliseconds;
  5385. ma_uint32 periods;
  5386. ma_performance_profile performanceProfile;
  5387. 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. */
  5388. ma_bool8 noClip; /* When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. Only applies when the playback sample format is f32. */
  5389. ma_bool8 noDisableDenormals; /* Do not disable denormals when firing the data callback. */
  5390. 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. */
  5391. ma_device_data_proc dataCallback;
  5392. ma_device_notification_proc notificationCallback;
  5393. ma_stop_proc stopCallback;
  5394. void* pUserData;
  5395. ma_resampler_config resampling;
  5396. struct
  5397. {
  5398. const ma_device_id* pDeviceID;
  5399. ma_format format;
  5400. ma_uint32 channels;
  5401. ma_channel* pChannelMap;
  5402. ma_channel_mix_mode channelMixMode;
  5403. 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. */
  5404. ma_share_mode shareMode;
  5405. } playback;
  5406. struct
  5407. {
  5408. const ma_device_id* pDeviceID;
  5409. ma_format format;
  5410. ma_uint32 channels;
  5411. ma_channel* pChannelMap;
  5412. ma_channel_mix_mode channelMixMode;
  5413. 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. */
  5414. ma_share_mode shareMode;
  5415. } capture;
  5416. struct
  5417. {
  5418. ma_wasapi_usage usage; /* When configured, uses Avrt APIs to set the thread characteristics. */
  5419. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  5420. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  5421. ma_bool8 noAutoStreamRouting; /* Disables automatic stream routing. */
  5422. ma_bool8 noHardwareOffloading; /* Disables WASAPI's hardware offloading feature. */
  5423. 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. */
  5424. ma_bool8 loopbackProcessExclude; /* When set to true, excludes the process specified by loopbackProcessID. By default, the process will be included. */
  5425. } wasapi;
  5426. struct
  5427. {
  5428. ma_bool32 noMMap; /* Disables MMap mode. */
  5429. ma_bool32 noAutoFormat; /* Opens the ALSA device with SND_PCM_NO_AUTO_FORMAT. */
  5430. ma_bool32 noAutoChannels; /* Opens the ALSA device with SND_PCM_NO_AUTO_CHANNELS. */
  5431. ma_bool32 noAutoResample; /* Opens the ALSA device with SND_PCM_NO_AUTO_RESAMPLE. */
  5432. } alsa;
  5433. struct
  5434. {
  5435. const char* pStreamNamePlayback;
  5436. const char* pStreamNameCapture;
  5437. } pulse;
  5438. struct
  5439. {
  5440. ma_bool32 allowNominalSampleRateChange; /* Desktop only. When enabled, allows changing of the sample rate at the operating system level. */
  5441. } coreaudio;
  5442. struct
  5443. {
  5444. ma_opensl_stream_type streamType;
  5445. ma_opensl_recording_preset recordingPreset;
  5446. } opensl;
  5447. struct
  5448. {
  5449. ma_aaudio_usage usage;
  5450. ma_aaudio_content_type contentType;
  5451. ma_aaudio_input_preset inputPreset;
  5452. ma_bool32 noAutoStartAfterReroute;
  5453. } aaudio;
  5454. };
  5455. /*
  5456. The callback for handling device enumeration. This is fired from `ma_context_enumerated_devices()`.
  5457. Parameters
  5458. ----------
  5459. pContext (in)
  5460. A pointer to the context performing the enumeration.
  5461. deviceType (in)
  5462. The type of the device being enumerated. This will always be either `ma_device_type_playback` or `ma_device_type_capture`.
  5463. pInfo (in)
  5464. 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,
  5465. 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
  5466. is too inefficient.
  5467. pUserData (in)
  5468. The user data pointer passed into `ma_context_enumerate_devices()`.
  5469. */
  5470. typedef ma_bool32 (* ma_enum_devices_callback_proc)(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData);
  5471. /*
  5472. Describes some basic details about a playback or capture device.
  5473. */
  5474. typedef struct
  5475. {
  5476. const ma_device_id* pDeviceID;
  5477. ma_share_mode shareMode;
  5478. ma_format format;
  5479. ma_uint32 channels;
  5480. ma_uint32 sampleRate;
  5481. ma_channel channelMap[MA_MAX_CHANNELS];
  5482. ma_uint32 periodSizeInFrames;
  5483. ma_uint32 periodSizeInMilliseconds;
  5484. ma_uint32 periodCount;
  5485. } ma_device_descriptor;
  5486. /*
  5487. 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
  5488. to many devices. A device is created from a context.
  5489. The general flow goes like this:
  5490. 1) A context is created with `onContextInit()`
  5491. 1a) Available devices can be enumerated with `onContextEnumerateDevices()` if required.
  5492. 1b) Detailed information about a device can be queried with `onContextGetDeviceInfo()` if required.
  5493. 2) A device is created from the context that was created in the first step using `onDeviceInit()`, and optionally a device ID that was
  5494. selected from device enumeration via `onContextEnumerateDevices()`.
  5495. 3) A device is started or stopped with `onDeviceStart()` / `onDeviceStop()`
  5496. 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
  5497. to `onDeviceInit()`. Conversion between the device's native format and the format requested by the application will be handled by
  5498. miniaudio internally.
  5499. Initialization of the context is quite simple. You need to do any necessary initialization of internal objects and then output the
  5500. callbacks defined in this structure.
  5501. Once the context has been initialized you can initialize a device. Before doing so, however, the application may want to know which
  5502. physical devices are available. This is where `onContextEnumerateDevices()` comes in. This is fairly simple. For each device, fire the
  5503. given callback with, at a minimum, the basic information filled out in `ma_device_info`. When the callback returns `MA_FALSE`, enumeration
  5504. needs to stop and the `onContextEnumerateDevices()` function returns with a success code.
  5505. Detailed device information can be retrieved from a device ID using `onContextGetDeviceInfo()`. This takes as input the device type and ID,
  5506. and on output returns detailed information about the device in `ma_device_info`. The `onContextGetDeviceInfo()` callback must handle the
  5507. case when the device ID is NULL, in which case information about the default device needs to be retrieved.
  5508. Once the context has been created and the device ID retrieved (if using anything other than the default device), the device can be created.
  5509. This is a little bit more complicated than initialization of the context due to it's more complicated configuration. When initializing a
  5510. device, a duplex device may be requested. This means a separate data format needs to be specified for both playback and capture. On input,
  5511. 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
  5512. the requested format. The conversion between the format requested by the application and the device's native format will be handled
  5513. internally by miniaudio.
  5514. 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
  5515. 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
  5516. sample rate. For the channel map, the default should be used when `ma_channel_map_is_blank()` returns true (all channels set to
  5517. `MA_CHANNEL_NONE`). On input, the `periodSizeInFrames` or `periodSizeInMilliseconds` option should always be set. The backend should
  5518. inspect both of these variables. If `periodSizeInFrames` is set, it should take priority, otherwise it needs to be derived from the period
  5519. size in milliseconds (`periodSizeInMilliseconds`) and the sample rate, keeping in mind that the sample rate may be 0, in which case the
  5520. sample rate will need to be determined before calculating the period size in frames. On output, all members of the `ma_device_descriptor`
  5521. object should be set to a valid value, except for `periodSizeInMilliseconds` which is optional (`periodSizeInFrames` *must* be set).
  5522. Starting and stopping of the device is done with `onDeviceStart()` and `onDeviceStop()` and should be self-explanatory. If the backend uses
  5523. asynchronous reading and writing, `onDeviceStart()` and `onDeviceStop()` should always be implemented.
  5524. The handling of data delivery between the application and the device is the most complicated part of the process. To make this a bit
  5525. easier, some helper callbacks are available. If the backend uses a blocking read/write style of API, the `onDeviceRead()` and
  5526. `onDeviceWrite()` callbacks can optionally be implemented. These are blocking and work just like reading and writing from a file. If the
  5527. backend uses a callback for data delivery, that callback must call `ma_device_handle_backend_data_callback()` from within it's callback.
  5528. This allows miniaudio to then process any necessary data conversion and then pass it to the miniaudio data callback.
  5529. If the backend requires absolute flexibility with it's data delivery, it can optionally implement the `onDeviceDataLoop()` callback
  5530. which will allow it to implement the logic that will run on the audio thread. This is much more advanced and is completely optional.
  5531. 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
  5532. encounted. Do not start or stop the device here. That will be handled from outside the `onDeviceDataLoop()` callback.
  5533. The invocation of the `onDeviceDataLoop()` callback will be handled by miniaudio. When you start the device, miniaudio will fire this
  5534. callback. When the device is stopped, the `ma_device_get_state() == ma_device_state_started` condition will fail and the loop will be terminated
  5535. which will then fall through to the part that stops the device. For an example on how to implement the `onDeviceDataLoop()` callback,
  5536. look at `ma_device_audio_thread__default_read_write()`. Implement the `onDeviceDataLoopWakeup()` callback if you need a mechanism to
  5537. wake up the audio thread.
  5538. If the backend supports an optimized retrieval of device information from an initialized `ma_device` object, it should implement the
  5539. `onDeviceGetInfo()` callback. This is optional, in which case it will fall back to `onContextGetDeviceInfo()` which is less efficient.
  5540. */
  5541. struct ma_backend_callbacks
  5542. {
  5543. ma_result (* onContextInit)(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks);
  5544. ma_result (* onContextUninit)(ma_context* pContext);
  5545. ma_result (* onContextEnumerateDevices)(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  5546. ma_result (* onContextGetDeviceInfo)(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_device_info* pDeviceInfo);
  5547. ma_result (* onDeviceInit)(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture);
  5548. ma_result (* onDeviceUninit)(ma_device* pDevice);
  5549. ma_result (* onDeviceStart)(ma_device* pDevice);
  5550. ma_result (* onDeviceStop)(ma_device* pDevice);
  5551. ma_result (* onDeviceRead)(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead);
  5552. ma_result (* onDeviceWrite)(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten);
  5553. ma_result (* onDeviceDataLoop)(ma_device* pDevice);
  5554. ma_result (* onDeviceDataLoopWakeup)(ma_device* pDevice);
  5555. ma_result (* onDeviceGetInfo)(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  5556. };
  5557. struct ma_context_config
  5558. {
  5559. ma_log* pLog;
  5560. ma_thread_priority threadPriority;
  5561. size_t threadStackSize;
  5562. void* pUserData;
  5563. ma_allocation_callbacks allocationCallbacks;
  5564. struct
  5565. {
  5566. ma_bool32 useVerboseDeviceEnumeration;
  5567. } alsa;
  5568. struct
  5569. {
  5570. const char* pApplicationName;
  5571. const char* pServerName;
  5572. ma_bool32 tryAutoSpawn; /* Enables autospawning of the PulseAudio daemon if necessary. */
  5573. } pulse;
  5574. struct
  5575. {
  5576. ma_ios_session_category sessionCategory;
  5577. ma_uint32 sessionCategoryOptions;
  5578. ma_bool32 noAudioSessionActivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization. */
  5579. ma_bool32 noAudioSessionDeactivate; /* iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization. */
  5580. } coreaudio;
  5581. struct
  5582. {
  5583. const char* pClientName;
  5584. ma_bool32 tryStartServer;
  5585. } jack;
  5586. ma_backend_callbacks custom;
  5587. };
  5588. /* WASAPI specific structure for some commands which must run on a common thread due to bugs in WASAPI. */
  5589. typedef struct
  5590. {
  5591. int code;
  5592. ma_event* pEvent; /* This will be signalled when the event is complete. */
  5593. union
  5594. {
  5595. struct
  5596. {
  5597. int _unused;
  5598. } quit;
  5599. struct
  5600. {
  5601. ma_device_type deviceType;
  5602. void* pAudioClient;
  5603. void** ppAudioClientService;
  5604. ma_result* pResult; /* The result from creating the audio client service. */
  5605. } createAudioClient;
  5606. struct
  5607. {
  5608. ma_device* pDevice;
  5609. ma_device_type deviceType;
  5610. } releaseAudioClient;
  5611. } data;
  5612. } ma_context_command__wasapi;
  5613. struct ma_context
  5614. {
  5615. ma_backend_callbacks callbacks;
  5616. ma_backend backend; /* DirectSound, ALSA, etc. */
  5617. ma_log* pLog;
  5618. ma_log log; /* Only used if the log is owned by the context. The pLog member will be set to &log in this case. */
  5619. ma_thread_priority threadPriority;
  5620. size_t threadStackSize;
  5621. void* pUserData;
  5622. ma_allocation_callbacks allocationCallbacks;
  5623. ma_mutex deviceEnumLock; /* Used to make ma_context_get_devices() thread safe. */
  5624. ma_mutex deviceInfoLock; /* Used to make ma_context_get_device_info() thread safe. */
  5625. ma_uint32 deviceInfoCapacity; /* Total capacity of pDeviceInfos. */
  5626. ma_uint32 playbackDeviceInfoCount;
  5627. ma_uint32 captureDeviceInfoCount;
  5628. ma_device_info* pDeviceInfos; /* Playback devices first, then capture. */
  5629. union
  5630. {
  5631. #ifdef MA_SUPPORT_WASAPI
  5632. struct
  5633. {
  5634. ma_thread commandThread;
  5635. ma_mutex commandLock;
  5636. ma_semaphore commandSem;
  5637. ma_uint32 commandIndex;
  5638. ma_uint32 commandCount;
  5639. ma_context_command__wasapi commands[4];
  5640. ma_handle hAvrt;
  5641. ma_proc AvSetMmThreadCharacteristicsW;
  5642. ma_proc AvRevertMmThreadcharacteristics;
  5643. ma_handle hMMDevapi;
  5644. ma_proc ActivateAudioInterfaceAsync;
  5645. } wasapi;
  5646. #endif
  5647. #ifdef MA_SUPPORT_DSOUND
  5648. struct
  5649. {
  5650. ma_handle hDSoundDLL;
  5651. ma_proc DirectSoundCreate;
  5652. ma_proc DirectSoundEnumerateA;
  5653. ma_proc DirectSoundCaptureCreate;
  5654. ma_proc DirectSoundCaptureEnumerateA;
  5655. } dsound;
  5656. #endif
  5657. #ifdef MA_SUPPORT_WINMM
  5658. struct
  5659. {
  5660. ma_handle hWinMM;
  5661. ma_proc waveOutGetNumDevs;
  5662. ma_proc waveOutGetDevCapsA;
  5663. ma_proc waveOutOpen;
  5664. ma_proc waveOutClose;
  5665. ma_proc waveOutPrepareHeader;
  5666. ma_proc waveOutUnprepareHeader;
  5667. ma_proc waveOutWrite;
  5668. ma_proc waveOutReset;
  5669. ma_proc waveInGetNumDevs;
  5670. ma_proc waveInGetDevCapsA;
  5671. ma_proc waveInOpen;
  5672. ma_proc waveInClose;
  5673. ma_proc waveInPrepareHeader;
  5674. ma_proc waveInUnprepareHeader;
  5675. ma_proc waveInAddBuffer;
  5676. ma_proc waveInStart;
  5677. ma_proc waveInReset;
  5678. } winmm;
  5679. #endif
  5680. #ifdef MA_SUPPORT_ALSA
  5681. struct
  5682. {
  5683. ma_handle asoundSO;
  5684. ma_proc snd_pcm_open;
  5685. ma_proc snd_pcm_close;
  5686. ma_proc snd_pcm_hw_params_sizeof;
  5687. ma_proc snd_pcm_hw_params_any;
  5688. ma_proc snd_pcm_hw_params_set_format;
  5689. ma_proc snd_pcm_hw_params_set_format_first;
  5690. ma_proc snd_pcm_hw_params_get_format_mask;
  5691. ma_proc snd_pcm_hw_params_set_channels;
  5692. ma_proc snd_pcm_hw_params_set_channels_near;
  5693. ma_proc snd_pcm_hw_params_set_channels_minmax;
  5694. ma_proc snd_pcm_hw_params_set_rate_resample;
  5695. ma_proc snd_pcm_hw_params_set_rate;
  5696. ma_proc snd_pcm_hw_params_set_rate_near;
  5697. ma_proc snd_pcm_hw_params_set_buffer_size_near;
  5698. ma_proc snd_pcm_hw_params_set_periods_near;
  5699. ma_proc snd_pcm_hw_params_set_access;
  5700. ma_proc snd_pcm_hw_params_get_format;
  5701. ma_proc snd_pcm_hw_params_get_channels;
  5702. ma_proc snd_pcm_hw_params_get_channels_min;
  5703. ma_proc snd_pcm_hw_params_get_channels_max;
  5704. ma_proc snd_pcm_hw_params_get_rate;
  5705. ma_proc snd_pcm_hw_params_get_rate_min;
  5706. ma_proc snd_pcm_hw_params_get_rate_max;
  5707. ma_proc snd_pcm_hw_params_get_buffer_size;
  5708. ma_proc snd_pcm_hw_params_get_periods;
  5709. ma_proc snd_pcm_hw_params_get_access;
  5710. ma_proc snd_pcm_hw_params_test_format;
  5711. ma_proc snd_pcm_hw_params_test_channels;
  5712. ma_proc snd_pcm_hw_params_test_rate;
  5713. ma_proc snd_pcm_hw_params;
  5714. ma_proc snd_pcm_sw_params_sizeof;
  5715. ma_proc snd_pcm_sw_params_current;
  5716. ma_proc snd_pcm_sw_params_get_boundary;
  5717. ma_proc snd_pcm_sw_params_set_avail_min;
  5718. ma_proc snd_pcm_sw_params_set_start_threshold;
  5719. ma_proc snd_pcm_sw_params_set_stop_threshold;
  5720. ma_proc snd_pcm_sw_params;
  5721. ma_proc snd_pcm_format_mask_sizeof;
  5722. ma_proc snd_pcm_format_mask_test;
  5723. ma_proc snd_pcm_get_chmap;
  5724. ma_proc snd_pcm_state;
  5725. ma_proc snd_pcm_prepare;
  5726. ma_proc snd_pcm_start;
  5727. ma_proc snd_pcm_drop;
  5728. ma_proc snd_pcm_drain;
  5729. ma_proc snd_pcm_reset;
  5730. ma_proc snd_device_name_hint;
  5731. ma_proc snd_device_name_get_hint;
  5732. ma_proc snd_card_get_index;
  5733. ma_proc snd_device_name_free_hint;
  5734. ma_proc snd_pcm_mmap_begin;
  5735. ma_proc snd_pcm_mmap_commit;
  5736. ma_proc snd_pcm_recover;
  5737. ma_proc snd_pcm_readi;
  5738. ma_proc snd_pcm_writei;
  5739. ma_proc snd_pcm_avail;
  5740. ma_proc snd_pcm_avail_update;
  5741. ma_proc snd_pcm_wait;
  5742. ma_proc snd_pcm_nonblock;
  5743. ma_proc snd_pcm_info;
  5744. ma_proc snd_pcm_info_sizeof;
  5745. ma_proc snd_pcm_info_get_name;
  5746. ma_proc snd_pcm_poll_descriptors;
  5747. ma_proc snd_pcm_poll_descriptors_count;
  5748. ma_proc snd_pcm_poll_descriptors_revents;
  5749. ma_proc snd_config_update_free_global;
  5750. ma_mutex internalDeviceEnumLock;
  5751. ma_bool32 useVerboseDeviceEnumeration;
  5752. } alsa;
  5753. #endif
  5754. #ifdef MA_SUPPORT_PULSEAUDIO
  5755. struct
  5756. {
  5757. ma_handle pulseSO;
  5758. ma_proc pa_mainloop_new;
  5759. ma_proc pa_mainloop_free;
  5760. ma_proc pa_mainloop_quit;
  5761. ma_proc pa_mainloop_get_api;
  5762. ma_proc pa_mainloop_iterate;
  5763. ma_proc pa_mainloop_wakeup;
  5764. ma_proc pa_threaded_mainloop_new;
  5765. ma_proc pa_threaded_mainloop_free;
  5766. ma_proc pa_threaded_mainloop_start;
  5767. ma_proc pa_threaded_mainloop_stop;
  5768. ma_proc pa_threaded_mainloop_lock;
  5769. ma_proc pa_threaded_mainloop_unlock;
  5770. ma_proc pa_threaded_mainloop_wait;
  5771. ma_proc pa_threaded_mainloop_signal;
  5772. ma_proc pa_threaded_mainloop_accept;
  5773. ma_proc pa_threaded_mainloop_get_retval;
  5774. ma_proc pa_threaded_mainloop_get_api;
  5775. ma_proc pa_threaded_mainloop_in_thread;
  5776. ma_proc pa_threaded_mainloop_set_name;
  5777. ma_proc pa_context_new;
  5778. ma_proc pa_context_unref;
  5779. ma_proc pa_context_connect;
  5780. ma_proc pa_context_disconnect;
  5781. ma_proc pa_context_set_state_callback;
  5782. ma_proc pa_context_get_state;
  5783. ma_proc pa_context_get_sink_info_list;
  5784. ma_proc pa_context_get_source_info_list;
  5785. ma_proc pa_context_get_sink_info_by_name;
  5786. ma_proc pa_context_get_source_info_by_name;
  5787. ma_proc pa_operation_unref;
  5788. ma_proc pa_operation_get_state;
  5789. ma_proc pa_channel_map_init_extend;
  5790. ma_proc pa_channel_map_valid;
  5791. ma_proc pa_channel_map_compatible;
  5792. ma_proc pa_stream_new;
  5793. ma_proc pa_stream_unref;
  5794. ma_proc pa_stream_connect_playback;
  5795. ma_proc pa_stream_connect_record;
  5796. ma_proc pa_stream_disconnect;
  5797. ma_proc pa_stream_get_state;
  5798. ma_proc pa_stream_get_sample_spec;
  5799. ma_proc pa_stream_get_channel_map;
  5800. ma_proc pa_stream_get_buffer_attr;
  5801. ma_proc pa_stream_set_buffer_attr;
  5802. ma_proc pa_stream_get_device_name;
  5803. ma_proc pa_stream_set_write_callback;
  5804. ma_proc pa_stream_set_read_callback;
  5805. ma_proc pa_stream_set_suspended_callback;
  5806. ma_proc pa_stream_set_moved_callback;
  5807. ma_proc pa_stream_is_suspended;
  5808. ma_proc pa_stream_flush;
  5809. ma_proc pa_stream_drain;
  5810. ma_proc pa_stream_is_corked;
  5811. ma_proc pa_stream_cork;
  5812. ma_proc pa_stream_trigger;
  5813. ma_proc pa_stream_begin_write;
  5814. ma_proc pa_stream_write;
  5815. ma_proc pa_stream_peek;
  5816. ma_proc pa_stream_drop;
  5817. ma_proc pa_stream_writable_size;
  5818. ma_proc pa_stream_readable_size;
  5819. /*pa_mainloop**/ ma_ptr pMainLoop;
  5820. /*pa_context**/ ma_ptr pPulseContext;
  5821. char* pApplicationName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  5822. char* pServerName; /* Set when the context is initialized. Used by devices for their local pa_context objects. */
  5823. } pulse;
  5824. #endif
  5825. #ifdef MA_SUPPORT_JACK
  5826. struct
  5827. {
  5828. ma_handle jackSO;
  5829. ma_proc jack_client_open;
  5830. ma_proc jack_client_close;
  5831. ma_proc jack_client_name_size;
  5832. ma_proc jack_set_process_callback;
  5833. ma_proc jack_set_buffer_size_callback;
  5834. ma_proc jack_on_shutdown;
  5835. ma_proc jack_get_sample_rate;
  5836. ma_proc jack_get_buffer_size;
  5837. ma_proc jack_get_ports;
  5838. ma_proc jack_activate;
  5839. ma_proc jack_deactivate;
  5840. ma_proc jack_connect;
  5841. ma_proc jack_port_register;
  5842. ma_proc jack_port_name;
  5843. ma_proc jack_port_get_buffer;
  5844. ma_proc jack_free;
  5845. char* pClientName;
  5846. ma_bool32 tryStartServer;
  5847. } jack;
  5848. #endif
  5849. #ifdef MA_SUPPORT_COREAUDIO
  5850. struct
  5851. {
  5852. ma_handle hCoreFoundation;
  5853. ma_proc CFStringGetCString;
  5854. ma_proc CFRelease;
  5855. ma_handle hCoreAudio;
  5856. ma_proc AudioObjectGetPropertyData;
  5857. ma_proc AudioObjectGetPropertyDataSize;
  5858. ma_proc AudioObjectSetPropertyData;
  5859. ma_proc AudioObjectAddPropertyListener;
  5860. ma_proc AudioObjectRemovePropertyListener;
  5861. ma_handle hAudioUnit; /* Could possibly be set to AudioToolbox on later versions of macOS. */
  5862. ma_proc AudioComponentFindNext;
  5863. ma_proc AudioComponentInstanceDispose;
  5864. ma_proc AudioComponentInstanceNew;
  5865. ma_proc AudioOutputUnitStart;
  5866. ma_proc AudioOutputUnitStop;
  5867. ma_proc AudioUnitAddPropertyListener;
  5868. ma_proc AudioUnitGetPropertyInfo;
  5869. ma_proc AudioUnitGetProperty;
  5870. ma_proc AudioUnitSetProperty;
  5871. ma_proc AudioUnitInitialize;
  5872. ma_proc AudioUnitRender;
  5873. /*AudioComponent*/ ma_ptr component;
  5874. 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(). */
  5875. } coreaudio;
  5876. #endif
  5877. #ifdef MA_SUPPORT_SNDIO
  5878. struct
  5879. {
  5880. ma_handle sndioSO;
  5881. ma_proc sio_open;
  5882. ma_proc sio_close;
  5883. ma_proc sio_setpar;
  5884. ma_proc sio_getpar;
  5885. ma_proc sio_getcap;
  5886. ma_proc sio_start;
  5887. ma_proc sio_stop;
  5888. ma_proc sio_read;
  5889. ma_proc sio_write;
  5890. ma_proc sio_onmove;
  5891. ma_proc sio_nfds;
  5892. ma_proc sio_pollfd;
  5893. ma_proc sio_revents;
  5894. ma_proc sio_eof;
  5895. ma_proc sio_setvol;
  5896. ma_proc sio_onvol;
  5897. ma_proc sio_initpar;
  5898. } sndio;
  5899. #endif
  5900. #ifdef MA_SUPPORT_AUDIO4
  5901. struct
  5902. {
  5903. int _unused;
  5904. } audio4;
  5905. #endif
  5906. #ifdef MA_SUPPORT_OSS
  5907. struct
  5908. {
  5909. int versionMajor;
  5910. int versionMinor;
  5911. } oss;
  5912. #endif
  5913. #ifdef MA_SUPPORT_AAUDIO
  5914. struct
  5915. {
  5916. ma_handle hAAudio; /* libaaudio.so */
  5917. ma_proc AAudio_createStreamBuilder;
  5918. ma_proc AAudioStreamBuilder_delete;
  5919. ma_proc AAudioStreamBuilder_setDeviceId;
  5920. ma_proc AAudioStreamBuilder_setDirection;
  5921. ma_proc AAudioStreamBuilder_setSharingMode;
  5922. ma_proc AAudioStreamBuilder_setFormat;
  5923. ma_proc AAudioStreamBuilder_setChannelCount;
  5924. ma_proc AAudioStreamBuilder_setSampleRate;
  5925. ma_proc AAudioStreamBuilder_setBufferCapacityInFrames;
  5926. ma_proc AAudioStreamBuilder_setFramesPerDataCallback;
  5927. ma_proc AAudioStreamBuilder_setDataCallback;
  5928. ma_proc AAudioStreamBuilder_setErrorCallback;
  5929. ma_proc AAudioStreamBuilder_setPerformanceMode;
  5930. ma_proc AAudioStreamBuilder_setUsage;
  5931. ma_proc AAudioStreamBuilder_setContentType;
  5932. ma_proc AAudioStreamBuilder_setInputPreset;
  5933. ma_proc AAudioStreamBuilder_openStream;
  5934. ma_proc AAudioStream_close;
  5935. ma_proc AAudioStream_getState;
  5936. ma_proc AAudioStream_waitForStateChange;
  5937. ma_proc AAudioStream_getFormat;
  5938. ma_proc AAudioStream_getChannelCount;
  5939. ma_proc AAudioStream_getSampleRate;
  5940. ma_proc AAudioStream_getBufferCapacityInFrames;
  5941. ma_proc AAudioStream_getFramesPerDataCallback;
  5942. ma_proc AAudioStream_getFramesPerBurst;
  5943. ma_proc AAudioStream_requestStart;
  5944. ma_proc AAudioStream_requestStop;
  5945. ma_device_job_thread jobThread; /* For processing operations outside of the error callback, specifically device disconnections and rerouting. */
  5946. } aaudio;
  5947. #endif
  5948. #ifdef MA_SUPPORT_OPENSL
  5949. struct
  5950. {
  5951. ma_handle libOpenSLES;
  5952. ma_handle SL_IID_ENGINE;
  5953. ma_handle SL_IID_AUDIOIODEVICECAPABILITIES;
  5954. ma_handle SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  5955. ma_handle SL_IID_RECORD;
  5956. ma_handle SL_IID_PLAY;
  5957. ma_handle SL_IID_OUTPUTMIX;
  5958. ma_handle SL_IID_ANDROIDCONFIGURATION;
  5959. ma_proc slCreateEngine;
  5960. } opensl;
  5961. #endif
  5962. #ifdef MA_SUPPORT_WEBAUDIO
  5963. struct
  5964. {
  5965. int _unused;
  5966. } webaudio;
  5967. #endif
  5968. #ifdef MA_SUPPORT_NULL
  5969. struct
  5970. {
  5971. int _unused;
  5972. } null_backend;
  5973. #endif
  5974. };
  5975. union
  5976. {
  5977. #ifdef MA_WIN32
  5978. struct
  5979. {
  5980. /*HMODULE*/ ma_handle hOle32DLL;
  5981. ma_proc CoInitializeEx;
  5982. ma_proc CoUninitialize;
  5983. ma_proc CoCreateInstance;
  5984. ma_proc CoTaskMemFree;
  5985. ma_proc PropVariantClear;
  5986. ma_proc StringFromGUID2;
  5987. /*HMODULE*/ ma_handle hUser32DLL;
  5988. ma_proc GetForegroundWindow;
  5989. ma_proc GetDesktopWindow;
  5990. /*HMODULE*/ ma_handle hAdvapi32DLL;
  5991. ma_proc RegOpenKeyExA;
  5992. ma_proc RegCloseKey;
  5993. ma_proc RegQueryValueExA;
  5994. } win32;
  5995. #endif
  5996. #ifdef MA_POSIX
  5997. struct
  5998. {
  5999. ma_handle pthreadSO;
  6000. ma_proc pthread_create;
  6001. ma_proc pthread_join;
  6002. ma_proc pthread_mutex_init;
  6003. ma_proc pthread_mutex_destroy;
  6004. ma_proc pthread_mutex_lock;
  6005. ma_proc pthread_mutex_unlock;
  6006. ma_proc pthread_cond_init;
  6007. ma_proc pthread_cond_destroy;
  6008. ma_proc pthread_cond_wait;
  6009. ma_proc pthread_cond_signal;
  6010. ma_proc pthread_attr_init;
  6011. ma_proc pthread_attr_destroy;
  6012. ma_proc pthread_attr_setschedpolicy;
  6013. ma_proc pthread_attr_getschedparam;
  6014. ma_proc pthread_attr_setschedparam;
  6015. } posix;
  6016. #endif
  6017. int _unused;
  6018. };
  6019. };
  6020. struct ma_device
  6021. {
  6022. ma_context* pContext;
  6023. ma_device_type type;
  6024. ma_uint32 sampleRate;
  6025. MA_ATOMIC(4, ma_device_state) state; /* The state of the device is variable and can change at any time on any thread. Must be used atomically. */
  6026. ma_device_data_proc onData; /* Set once at initialization time and should not be changed after. */
  6027. ma_device_notification_proc onNotification; /* Set once at initialization time and should not be changed after. */
  6028. ma_stop_proc onStop; /* DEPRECATED. Use the notification callback instead. Set once at initialization time and should not be changed after. */
  6029. void* pUserData; /* Application defined data. */
  6030. ma_mutex startStopLock;
  6031. ma_event wakeupEvent;
  6032. ma_event startEvent;
  6033. ma_event stopEvent;
  6034. ma_thread thread;
  6035. ma_result workResult; /* This is set by the worker thread after it's finished doing a job. */
  6036. 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(). */
  6037. ma_bool8 noPreSilencedOutputBuffer;
  6038. ma_bool8 noClip;
  6039. ma_bool8 noDisableDenormals;
  6040. ma_bool8 noFixedSizedCallback;
  6041. MA_ATOMIC(4, float) masterVolumeFactor; /* Linear 0..1. Can be read and written simultaneously by different threads. Must be used atomically. */
  6042. ma_duplex_rb duplexRB; /* Intermediary buffer for duplex device on asynchronous backends. */
  6043. struct
  6044. {
  6045. ma_resample_algorithm algorithm;
  6046. ma_resampling_backend_vtable* pBackendVTable;
  6047. void* pBackendUserData;
  6048. struct
  6049. {
  6050. ma_uint32 lpfOrder;
  6051. } linear;
  6052. } resampling;
  6053. struct
  6054. {
  6055. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6056. 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. */
  6057. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6058. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6059. ma_format format;
  6060. ma_uint32 channels;
  6061. ma_channel channelMap[MA_MAX_CHANNELS];
  6062. ma_format internalFormat;
  6063. ma_uint32 internalChannels;
  6064. ma_uint32 internalSampleRate;
  6065. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6066. ma_uint32 internalPeriodSizeInFrames;
  6067. ma_uint32 internalPeriods;
  6068. ma_channel_mix_mode channelMixMode;
  6069. ma_bool32 calculateLFEFromSpatialChannels;
  6070. ma_data_converter converter;
  6071. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6072. ma_uint32 intermediaryBufferCap;
  6073. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6074. void* pInputCache; /* In external format. Can be null. */
  6075. ma_uint64 inputCacheCap;
  6076. ma_uint64 inputCacheConsumed;
  6077. ma_uint64 inputCacheRemaining;
  6078. } playback;
  6079. struct
  6080. {
  6081. ma_device_id* pID; /* Set to NULL if using default ID, otherwise set to the address of "id". */
  6082. 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. */
  6083. char name[MA_MAX_DEVICE_NAME_LENGTH + 1]; /* Maybe temporary. Likely to be replaced with a query API. */
  6084. ma_share_mode shareMode; /* Set to whatever was passed in when the device was initialized. */
  6085. ma_format format;
  6086. ma_uint32 channels;
  6087. ma_channel channelMap[MA_MAX_CHANNELS];
  6088. ma_format internalFormat;
  6089. ma_uint32 internalChannels;
  6090. ma_uint32 internalSampleRate;
  6091. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  6092. ma_uint32 internalPeriodSizeInFrames;
  6093. ma_uint32 internalPeriods;
  6094. ma_channel_mix_mode channelMixMode;
  6095. ma_bool32 calculateLFEFromSpatialChannels;
  6096. ma_data_converter converter;
  6097. void* pIntermediaryBuffer; /* For implementing fixed sized buffer callbacks. Will be null if using variable sized callbacks. */
  6098. ma_uint32 intermediaryBufferCap;
  6099. ma_uint32 intermediaryBufferLen; /* How many valid frames are sitting in the intermediary buffer. */
  6100. } capture;
  6101. union
  6102. {
  6103. #ifdef MA_SUPPORT_WASAPI
  6104. struct
  6105. {
  6106. /*IAudioClient**/ ma_ptr pAudioClientPlayback;
  6107. /*IAudioClient**/ ma_ptr pAudioClientCapture;
  6108. /*IAudioRenderClient**/ ma_ptr pRenderClient;
  6109. /*IAudioCaptureClient**/ ma_ptr pCaptureClient;
  6110. /*IMMDeviceEnumerator**/ ma_ptr pDeviceEnumerator; /* Used for IMMNotificationClient notifications. Required for detecting default device changes. */
  6111. ma_IMMNotificationClient notificationClient;
  6112. /*HANDLE*/ ma_handle hEventPlayback; /* Auto reset. Initialized to signaled. */
  6113. /*HANDLE*/ ma_handle hEventCapture; /* Auto reset. Initialized to unsignaled. */
  6114. 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. */
  6115. ma_uint32 actualBufferSizeInFramesCapture;
  6116. ma_uint32 originalPeriodSizeInFrames;
  6117. ma_uint32 originalPeriodSizeInMilliseconds;
  6118. ma_uint32 originalPeriods;
  6119. ma_performance_profile originalPerformanceProfile;
  6120. ma_uint32 periodSizeInFramesPlayback;
  6121. ma_uint32 periodSizeInFramesCapture;
  6122. void* pMappedBufferCapture;
  6123. ma_uint32 mappedBufferCaptureCap;
  6124. ma_uint32 mappedBufferCaptureLen;
  6125. void* pMappedBufferPlayback;
  6126. ma_uint32 mappedBufferPlaybackCap;
  6127. ma_uint32 mappedBufferPlaybackLen;
  6128. MA_ATOMIC(4, ma_bool32) isStartedCapture; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6129. MA_ATOMIC(4, ma_bool32) isStartedPlayback; /* Can be read and written simultaneously across different threads. Must be used atomically, and must be 32-bit. */
  6130. ma_uint32 loopbackProcessID;
  6131. ma_bool8 loopbackProcessExclude;
  6132. ma_bool8 noAutoConvertSRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM. */
  6133. ma_bool8 noDefaultQualitySRC; /* When set to true, disables the use of AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY. */
  6134. ma_bool8 noHardwareOffloading;
  6135. ma_bool8 allowCaptureAutoStreamRouting;
  6136. ma_bool8 allowPlaybackAutoStreamRouting;
  6137. ma_bool8 isDetachedPlayback;
  6138. ma_bool8 isDetachedCapture;
  6139. ma_wasapi_usage usage;
  6140. void *hAvrtHandle;
  6141. } wasapi;
  6142. #endif
  6143. #ifdef MA_SUPPORT_DSOUND
  6144. struct
  6145. {
  6146. /*LPDIRECTSOUND*/ ma_ptr pPlayback;
  6147. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackPrimaryBuffer;
  6148. /*LPDIRECTSOUNDBUFFER*/ ma_ptr pPlaybackBuffer;
  6149. /*LPDIRECTSOUNDCAPTURE*/ ma_ptr pCapture;
  6150. /*LPDIRECTSOUNDCAPTUREBUFFER*/ ma_ptr pCaptureBuffer;
  6151. } dsound;
  6152. #endif
  6153. #ifdef MA_SUPPORT_WINMM
  6154. struct
  6155. {
  6156. /*HWAVEOUT*/ ma_handle hDevicePlayback;
  6157. /*HWAVEIN*/ ma_handle hDeviceCapture;
  6158. /*HANDLE*/ ma_handle hEventPlayback;
  6159. /*HANDLE*/ ma_handle hEventCapture;
  6160. ma_uint32 fragmentSizeInFrames;
  6161. ma_uint32 iNextHeaderPlayback; /* [0,periods). Used as an index into pWAVEHDRPlayback. */
  6162. ma_uint32 iNextHeaderCapture; /* [0,periods). Used as an index into pWAVEHDRCapture. */
  6163. ma_uint32 headerFramesConsumedPlayback; /* The number of PCM frames consumed in the buffer in pWAVEHEADER[iNextHeader]. */
  6164. ma_uint32 headerFramesConsumedCapture; /* ^^^ */
  6165. /*WAVEHDR**/ ma_uint8* pWAVEHDRPlayback; /* One instantiation for each period. */
  6166. /*WAVEHDR**/ ma_uint8* pWAVEHDRCapture; /* One instantiation for each period. */
  6167. ma_uint8* pIntermediaryBufferPlayback;
  6168. ma_uint8* pIntermediaryBufferCapture;
  6169. ma_uint8* _pHeapData; /* Used internally and is used for the heap allocated data for the intermediary buffer and the WAVEHDR structures. */
  6170. } winmm;
  6171. #endif
  6172. #ifdef MA_SUPPORT_ALSA
  6173. struct
  6174. {
  6175. /*snd_pcm_t**/ ma_ptr pPCMPlayback;
  6176. /*snd_pcm_t**/ ma_ptr pPCMCapture;
  6177. /*struct pollfd**/ void* pPollDescriptorsPlayback;
  6178. /*struct pollfd**/ void* pPollDescriptorsCapture;
  6179. int pollDescriptorCountPlayback;
  6180. int pollDescriptorCountCapture;
  6181. int wakeupfdPlayback; /* eventfd for waking up from poll() when the playback device is stopped. */
  6182. int wakeupfdCapture; /* eventfd for waking up from poll() when the capture device is stopped. */
  6183. ma_bool8 isUsingMMapPlayback;
  6184. ma_bool8 isUsingMMapCapture;
  6185. } alsa;
  6186. #endif
  6187. #ifdef MA_SUPPORT_PULSEAUDIO
  6188. struct
  6189. {
  6190. /*pa_mainloop**/ ma_ptr pMainLoop;
  6191. /*pa_context**/ ma_ptr pPulseContext;
  6192. /*pa_stream**/ ma_ptr pStreamPlayback;
  6193. /*pa_stream**/ ma_ptr pStreamCapture;
  6194. } pulse;
  6195. #endif
  6196. #ifdef MA_SUPPORT_JACK
  6197. struct
  6198. {
  6199. /*jack_client_t**/ ma_ptr pClient;
  6200. /*jack_port_t**/ ma_ptr* ppPortsPlayback;
  6201. /*jack_port_t**/ ma_ptr* ppPortsCapture;
  6202. float* pIntermediaryBufferPlayback; /* Typed as a float because JACK is always floating point. */
  6203. float* pIntermediaryBufferCapture;
  6204. } jack;
  6205. #endif
  6206. #ifdef MA_SUPPORT_COREAUDIO
  6207. struct
  6208. {
  6209. ma_uint32 deviceObjectIDPlayback;
  6210. ma_uint32 deviceObjectIDCapture;
  6211. /*AudioUnit*/ ma_ptr audioUnitPlayback;
  6212. /*AudioUnit*/ ma_ptr audioUnitCapture;
  6213. /*AudioBufferList**/ ma_ptr pAudioBufferList; /* Only used for input devices. */
  6214. ma_uint32 audioBufferCapInFrames; /* Only used for input devices. The capacity in frames of each buffer in pAudioBufferList. */
  6215. ma_event stopEvent;
  6216. ma_uint32 originalPeriodSizeInFrames;
  6217. ma_uint32 originalPeriodSizeInMilliseconds;
  6218. ma_uint32 originalPeriods;
  6219. ma_performance_profile originalPerformanceProfile;
  6220. ma_bool32 isDefaultPlaybackDevice;
  6221. ma_bool32 isDefaultCaptureDevice;
  6222. ma_bool32 isSwitchingPlaybackDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6223. ma_bool32 isSwitchingCaptureDevice; /* <-- Set to true when the default device has changed and miniaudio is in the process of switching. */
  6224. void* pNotificationHandler; /* Only used on mobile platforms. Obj-C object for handling route changes. */
  6225. } coreaudio;
  6226. #endif
  6227. #ifdef MA_SUPPORT_SNDIO
  6228. struct
  6229. {
  6230. ma_ptr handlePlayback;
  6231. ma_ptr handleCapture;
  6232. ma_bool32 isStartedPlayback;
  6233. ma_bool32 isStartedCapture;
  6234. } sndio;
  6235. #endif
  6236. #ifdef MA_SUPPORT_AUDIO4
  6237. struct
  6238. {
  6239. int fdPlayback;
  6240. int fdCapture;
  6241. } audio4;
  6242. #endif
  6243. #ifdef MA_SUPPORT_OSS
  6244. struct
  6245. {
  6246. int fdPlayback;
  6247. int fdCapture;
  6248. } oss;
  6249. #endif
  6250. #ifdef MA_SUPPORT_AAUDIO
  6251. struct
  6252. {
  6253. /*AAudioStream**/ ma_ptr pStreamPlayback;
  6254. /*AAudioStream**/ ma_ptr pStreamCapture;
  6255. ma_aaudio_usage usage;
  6256. ma_aaudio_content_type contentType;
  6257. ma_aaudio_input_preset inputPreset;
  6258. ma_bool32 noAutoStartAfterReroute;
  6259. } aaudio;
  6260. #endif
  6261. #ifdef MA_SUPPORT_OPENSL
  6262. struct
  6263. {
  6264. /*SLObjectItf*/ ma_ptr pOutputMixObj;
  6265. /*SLOutputMixItf*/ ma_ptr pOutputMix;
  6266. /*SLObjectItf*/ ma_ptr pAudioPlayerObj;
  6267. /*SLPlayItf*/ ma_ptr pAudioPlayer;
  6268. /*SLObjectItf*/ ma_ptr pAudioRecorderObj;
  6269. /*SLRecordItf*/ ma_ptr pAudioRecorder;
  6270. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueuePlayback;
  6271. /*SLAndroidSimpleBufferQueueItf*/ ma_ptr pBufferQueueCapture;
  6272. ma_bool32 isDrainingCapture;
  6273. ma_bool32 isDrainingPlayback;
  6274. ma_uint32 currentBufferIndexPlayback;
  6275. ma_uint32 currentBufferIndexCapture;
  6276. ma_uint8* pBufferPlayback; /* This is malloc()'d and is used for storing audio data. Typed as ma_uint8 for easy offsetting. */
  6277. ma_uint8* pBufferCapture;
  6278. } opensl;
  6279. #endif
  6280. #ifdef MA_SUPPORT_WEBAUDIO
  6281. struct
  6282. {
  6283. int indexPlayback; /* We use a factory on the JavaScript side to manage devices and use an index for JS/C interop. */
  6284. int indexCapture;
  6285. } webaudio;
  6286. #endif
  6287. #ifdef MA_SUPPORT_NULL
  6288. struct
  6289. {
  6290. ma_thread deviceThread;
  6291. ma_event operationEvent;
  6292. ma_event operationCompletionEvent;
  6293. ma_semaphore operationSemaphore;
  6294. ma_uint32 operation;
  6295. ma_result operationResult;
  6296. ma_timer timer;
  6297. double priorRunTime;
  6298. ma_uint32 currentPeriodFramesRemainingPlayback;
  6299. ma_uint32 currentPeriodFramesRemainingCapture;
  6300. ma_uint64 lastProcessedFramePlayback;
  6301. ma_uint64 lastProcessedFrameCapture;
  6302. MA_ATOMIC(4, ma_bool32) isStarted; /* Read and written by multiple threads. Must be used atomically, and must be 32-bit for compiler compatibility. */
  6303. } null_device;
  6304. #endif
  6305. };
  6306. };
  6307. #if defined(_MSC_VER) && !defined(__clang__)
  6308. #pragma warning(pop)
  6309. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  6310. #pragma GCC diagnostic pop /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  6311. #endif
  6312. /*
  6313. Initializes a `ma_context_config` object.
  6314. Return Value
  6315. ------------
  6316. A `ma_context_config` initialized to defaults.
  6317. Remarks
  6318. -------
  6319. 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
  6320. is updated and new members are added to `ma_context_config`. It also sets logical defaults.
  6321. You can override members of the returned object by changing it's members directly.
  6322. See Also
  6323. --------
  6324. ma_context_init()
  6325. */
  6326. MA_API ma_context_config ma_context_config_init(void);
  6327. /*
  6328. Initializes a context.
  6329. 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
  6330. device. There is one context to many devices, and a device is created from a context. A context is required to enumerate devices.
  6331. Parameters
  6332. ----------
  6333. backends (in, optional)
  6334. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  6335. backendCount (in, optional)
  6336. The number of items in `backend`. Ignored if `backend` is NULL.
  6337. pConfig (in, optional)
  6338. The context configuration.
  6339. pContext (in)
  6340. A pointer to the context object being initialized.
  6341. Return Value
  6342. ------------
  6343. MA_SUCCESS if successful; any other error code otherwise.
  6344. Thread Safety
  6345. -------------
  6346. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6347. Remarks
  6348. -------
  6349. When `backends` is NULL, the default priority order will be used. Below is a list of backends in priority order:
  6350. |-------------|-----------------------|--------------------------------------------------------|
  6351. | Name | Enum Name | Supported Operating Systems |
  6352. |-------------|-----------------------|--------------------------------------------------------|
  6353. | WASAPI | ma_backend_wasapi | Windows Vista+ |
  6354. | DirectSound | ma_backend_dsound | Windows XP+ |
  6355. | WinMM | ma_backend_winmm | Windows XP+ (may work on older versions, but untested) |
  6356. | Core Audio | ma_backend_coreaudio | macOS, iOS |
  6357. | ALSA | ma_backend_alsa | Linux |
  6358. | PulseAudio | ma_backend_pulseaudio | Cross Platform (disabled on Windows, BSD and Android) |
  6359. | JACK | ma_backend_jack | Cross Platform (disabled on BSD and Android) |
  6360. | sndio | ma_backend_sndio | OpenBSD |
  6361. | audio(4) | ma_backend_audio4 | NetBSD, OpenBSD |
  6362. | OSS | ma_backend_oss | FreeBSD |
  6363. | AAudio | ma_backend_aaudio | Android 8+ |
  6364. | OpenSL|ES | ma_backend_opensl | Android (API level 16+) |
  6365. | Web Audio | ma_backend_webaudio | Web (via Emscripten) |
  6366. | Null | ma_backend_null | Cross Platform (not used on Web) |
  6367. |-------------|-----------------------|--------------------------------------------------------|
  6368. The context can be configured via the `pConfig` argument. The config object is initialized with `ma_context_config_init()`. Individual configuration settings
  6369. can then be set directly on the structure. Below are the members of the `ma_context_config` object.
  6370. pLog
  6371. A pointer to the `ma_log` to post log messages to. Can be NULL if the application does not
  6372. require logging. See the `ma_log` API for details on how to use the logging system.
  6373. threadPriority
  6374. The desired priority to use for the audio thread. Allowable values include the following:
  6375. |--------------------------------------|
  6376. | Thread Priority |
  6377. |--------------------------------------|
  6378. | ma_thread_priority_idle |
  6379. | ma_thread_priority_lowest |
  6380. | ma_thread_priority_low |
  6381. | ma_thread_priority_normal |
  6382. | ma_thread_priority_high |
  6383. | ma_thread_priority_highest (default) |
  6384. | ma_thread_priority_realtime |
  6385. | ma_thread_priority_default |
  6386. |--------------------------------------|
  6387. threadStackSize
  6388. The desired size of the stack for the audio thread. Defaults to the operating system's default.
  6389. pUserData
  6390. A pointer to application-defined data. This can be accessed from the context object directly such as `context.pUserData`.
  6391. allocationCallbacks
  6392. Structure containing custom allocation callbacks. Leaving this at defaults will cause it to use MA_MALLOC, MA_REALLOC and MA_FREE. These allocation
  6393. callbacks will be used for anything tied to the context, including devices.
  6394. alsa.useVerboseDeviceEnumeration
  6395. ALSA will typically enumerate many different devices which can be intrusive and not user-friendly. To combat this, miniaudio will enumerate only unique
  6396. card/device pairs by default. The problem with this is that you lose a bit of flexibility and control. Setting alsa.useVerboseDeviceEnumeration makes
  6397. it so the ALSA backend includes all devices. Defaults to false.
  6398. pulse.pApplicationName
  6399. PulseAudio only. The application name to use when initializing the PulseAudio context with `pa_context_new()`.
  6400. pulse.pServerName
  6401. PulseAudio only. The name of the server to connect to with `pa_context_connect()`.
  6402. pulse.tryAutoSpawn
  6403. 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
  6404. 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
  6405. intrusive for the end user.
  6406. coreaudio.sessionCategory
  6407. iOS only. The session category to use for the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6408. |-----------------------------------------|-------------------------------------|
  6409. | miniaudio Token | Core Audio Token |
  6410. |-----------------------------------------|-------------------------------------|
  6411. | ma_ios_session_category_ambient | AVAudioSessionCategoryAmbient |
  6412. | ma_ios_session_category_solo_ambient | AVAudioSessionCategorySoloAmbient |
  6413. | ma_ios_session_category_playback | AVAudioSessionCategoryPlayback |
  6414. | ma_ios_session_category_record | AVAudioSessionCategoryRecord |
  6415. | ma_ios_session_category_play_and_record | AVAudioSessionCategoryPlayAndRecord |
  6416. | ma_ios_session_category_multi_route | AVAudioSessionCategoryMultiRoute |
  6417. | ma_ios_session_category_none | AVAudioSessionCategoryAmbient |
  6418. | ma_ios_session_category_default | AVAudioSessionCategoryAmbient |
  6419. |-----------------------------------------|-------------------------------------|
  6420. coreaudio.sessionCategoryOptions
  6421. iOS only. Session category options to use with the shared AudioSession instance. Below is a list of allowable values and their Core Audio equivalents.
  6422. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6423. | miniaudio Token | Core Audio Token |
  6424. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6425. | ma_ios_session_category_option_mix_with_others | AVAudioSessionCategoryOptionMixWithOthers |
  6426. | ma_ios_session_category_option_duck_others | AVAudioSessionCategoryOptionDuckOthers |
  6427. | ma_ios_session_category_option_allow_bluetooth | AVAudioSessionCategoryOptionAllowBluetooth |
  6428. | ma_ios_session_category_option_default_to_speaker | AVAudioSessionCategoryOptionDefaultToSpeaker |
  6429. | ma_ios_session_category_option_interrupt_spoken_audio_and_mix_with_others | AVAudioSessionCategoryOptionInterruptSpokenAudioAndMixWithOthers |
  6430. | ma_ios_session_category_option_allow_bluetooth_a2dp | AVAudioSessionCategoryOptionAllowBluetoothA2DP |
  6431. | ma_ios_session_category_option_allow_air_play | AVAudioSessionCategoryOptionAllowAirPlay |
  6432. |---------------------------------------------------------------------------|------------------------------------------------------------------|
  6433. coreaudio.noAudioSessionActivate
  6434. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:true] on initialization.
  6435. coreaudio.noAudioSessionDeactivate
  6436. iOS only. When set to true, does not perform an explicit [[AVAudioSession sharedInstace] setActive:false] on uninitialization.
  6437. jack.pClientName
  6438. The name of the client to pass to `jack_client_open()`.
  6439. jack.tryStartServer
  6440. Whether or not to try auto-starting the JACK server. Defaults to false.
  6441. 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
  6442. relevant backends every time it's initialized.
  6443. 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
  6444. reason for this is that a pointer to the context is stored in the `ma_device` structure.
  6445. Example 1 - Default Initialization
  6446. ----------------------------------
  6447. The example below shows how to initialize the context using the default configuration.
  6448. ```c
  6449. ma_context context;
  6450. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  6451. if (result != MA_SUCCESS) {
  6452. // Error.
  6453. }
  6454. ```
  6455. Example 2 - Custom Configuration
  6456. --------------------------------
  6457. The example below shows how to initialize the context using custom backend priorities and a custom configuration. In this hypothetical example, the program
  6458. 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
  6459. want an error to be returned if no valid backend is available which they achieve by excluding the Null backend.
  6460. 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.
  6461. ```c
  6462. ma_backend backends[] = {
  6463. ma_backend_alsa,
  6464. ma_backend_pulseaudio,
  6465. ma_backend_wasapi,
  6466. ma_backend_dsound
  6467. };
  6468. ma_log log;
  6469. ma_log_init(&log);
  6470. ma_log_register_callback(&log, ma_log_callback_init(my_log_callbac, pMyLogUserData));
  6471. ma_context_config config = ma_context_config_init();
  6472. config.pLog = &log; // Specify a custom log object in the config so any logs that are posted from ma_context_init() are captured.
  6473. ma_context context;
  6474. ma_result result = ma_context_init(backends, sizeof(backends)/sizeof(backends[0]), &config, &context);
  6475. if (result != MA_SUCCESS) {
  6476. // Error.
  6477. if (result == MA_NO_BACKEND) {
  6478. // Couldn't find an appropriate backend.
  6479. }
  6480. }
  6481. // You could also attach a log callback post-initialization:
  6482. ma_log_register_callback(ma_context_get_log(&context), ma_log_callback_init(my_log_callback, pMyLogUserData));
  6483. ```
  6484. See Also
  6485. --------
  6486. ma_context_config_init()
  6487. ma_context_uninit()
  6488. */
  6489. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext);
  6490. /*
  6491. Uninitializes a context.
  6492. Return Value
  6493. ------------
  6494. MA_SUCCESS if successful; any other error code otherwise.
  6495. Thread Safety
  6496. -------------
  6497. Unsafe. Do not call this function across multiple threads as some backends read and write to global state.
  6498. Remarks
  6499. -------
  6500. Results are undefined if you call this while any device created by this context is still active.
  6501. See Also
  6502. --------
  6503. ma_context_init()
  6504. */
  6505. MA_API ma_result ma_context_uninit(ma_context* pContext);
  6506. /*
  6507. Retrieves the size of the ma_context object.
  6508. This is mainly for the purpose of bindings to know how much memory to allocate.
  6509. */
  6510. MA_API size_t ma_context_sizeof(void);
  6511. /*
  6512. Retrieves a pointer to the log object associated with this context.
  6513. Remarks
  6514. -------
  6515. Pass the returned pointer to `ma_log_post()`, `ma_log_postv()` or `ma_log_postf()` to post a log
  6516. message.
  6517. You can attach your own logging callback to the log with `ma_log_register_callback()`
  6518. Return Value
  6519. ------------
  6520. A pointer to the `ma_log` object that the context uses to post log messages. If some error occurs,
  6521. NULL will be returned.
  6522. */
  6523. MA_API ma_log* ma_context_get_log(ma_context* pContext);
  6524. /*
  6525. Enumerates over every device (both playback and capture).
  6526. 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
  6527. an internal heap allocation, or it simply suits your code better.
  6528. 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
  6529. 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,
  6530. but don't call it from within the enumeration callback.
  6531. Returning false from the callback will stop enumeration. Returning true will continue enumeration.
  6532. Parameters
  6533. ----------
  6534. pContext (in)
  6535. A pointer to the context performing the enumeration.
  6536. callback (in)
  6537. The callback to fire for each enumerated device.
  6538. pUserData (in)
  6539. A pointer to application-defined data passed to the callback.
  6540. Return Value
  6541. ------------
  6542. MA_SUCCESS if successful; any other error code otherwise.
  6543. Thread Safety
  6544. -------------
  6545. Safe. This is guarded using a simple mutex lock.
  6546. Remarks
  6547. -------
  6548. Do _not_ assume the first enumerated device of a given type is the default device.
  6549. Some backends and platforms may only support default playback and capture devices.
  6550. 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,
  6551. do not try to call `ma_context_get_device_info()` from within the callback.
  6552. Consider using `ma_context_get_devices()` for a simpler and safer API, albeit at the expense of an internal heap allocation.
  6553. Example 1 - Simple Enumeration
  6554. ------------------------------
  6555. ma_bool32 ma_device_enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  6556. {
  6557. printf("Device Name: %s\n", pInfo->name);
  6558. return MA_TRUE;
  6559. }
  6560. ma_result result = ma_context_enumerate_devices(&context, my_device_enum_callback, pMyUserData);
  6561. if (result != MA_SUCCESS) {
  6562. // Error.
  6563. }
  6564. See Also
  6565. --------
  6566. ma_context_get_devices()
  6567. */
  6568. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData);
  6569. /*
  6570. Retrieves basic information about every active playback and/or capture device.
  6571. This function will allocate memory internally for the device lists and return a pointer to them through the `ppPlaybackDeviceInfos` and `ppCaptureDeviceInfos`
  6572. 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.
  6573. Parameters
  6574. ----------
  6575. pContext (in)
  6576. A pointer to the context performing the enumeration.
  6577. ppPlaybackDeviceInfos (out)
  6578. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for playback devices.
  6579. pPlaybackDeviceCount (out)
  6580. A pointer to an unsigned integer that will receive the number of playback devices.
  6581. ppCaptureDeviceInfos (out)
  6582. A pointer to a pointer that will receive the address of a buffer containing the list of `ma_device_info` structures for capture devices.
  6583. pCaptureDeviceCount (out)
  6584. A pointer to an unsigned integer that will receive the number of capture devices.
  6585. Return Value
  6586. ------------
  6587. MA_SUCCESS if successful; any other error code otherwise.
  6588. Thread Safety
  6589. -------------
  6590. Unsafe. Since each call to this function invalidates the pointers from the previous call, you should not be calling this simultaneously across multiple
  6591. threads. Instead, you need to make a copy of the returned data with your own higher level synchronization.
  6592. Remarks
  6593. -------
  6594. It is _not_ safe to assume the first device in the list is the default device.
  6595. You can pass in NULL for the playback or capture lists in which case they'll be ignored.
  6596. 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.
  6597. See Also
  6598. --------
  6599. ma_context_get_devices()
  6600. */
  6601. 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);
  6602. /*
  6603. Retrieves information about a device of the given type, with the specified ID and share mode.
  6604. Parameters
  6605. ----------
  6606. pContext (in)
  6607. A pointer to the context performing the query.
  6608. deviceType (in)
  6609. The type of the device being queried. Must be either `ma_device_type_playback` or `ma_device_type_capture`.
  6610. pDeviceID (in)
  6611. The ID of the device being queried.
  6612. pDeviceInfo (out)
  6613. A pointer to the `ma_device_info` structure that will receive the device information.
  6614. Return Value
  6615. ------------
  6616. MA_SUCCESS if successful; any other error code otherwise.
  6617. Thread Safety
  6618. -------------
  6619. Safe. This is guarded using a simple mutex lock.
  6620. Remarks
  6621. -------
  6622. Do _not_ call this from within the `ma_context_enumerate_devices()` callback.
  6623. 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
  6624. 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
  6625. 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
  6626. the requested share mode is unsupported.
  6627. This leaves pDeviceInfo unmodified in the result of an error.
  6628. */
  6629. 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);
  6630. /*
  6631. Determines if the given context supports loopback mode.
  6632. Parameters
  6633. ----------
  6634. pContext (in)
  6635. A pointer to the context getting queried.
  6636. Return Value
  6637. ------------
  6638. MA_TRUE if the context supports loopback mode; MA_FALSE otherwise.
  6639. */
  6640. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext);
  6641. /*
  6642. Initializes a device config with default settings.
  6643. Parameters
  6644. ----------
  6645. deviceType (in)
  6646. The type of the device this config is being initialized for. This must set to one of the following:
  6647. |-------------------------|
  6648. | Device Type |
  6649. |-------------------------|
  6650. | ma_device_type_playback |
  6651. | ma_device_type_capture |
  6652. | ma_device_type_duplex |
  6653. | ma_device_type_loopback |
  6654. |-------------------------|
  6655. Return Value
  6656. ------------
  6657. A new device config object with default settings. You will typically want to adjust the config after this function returns. See remarks.
  6658. Thread Safety
  6659. -------------
  6660. Safe.
  6661. Callback Safety
  6662. ---------------
  6663. Safe, but don't try initializing a device in a callback.
  6664. Remarks
  6665. -------
  6666. 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
  6667. 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
  6668. before initializing the device.
  6669. See `ma_device_init()` for details on specific configuration options.
  6670. Example 1 - Simple Configuration
  6671. --------------------------------
  6672. 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
  6673. 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
  6674. to the `ma_device_config` structure.
  6675. ```c
  6676. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  6677. config.playback.format = ma_format_f32;
  6678. config.playback.channels = 2;
  6679. config.sampleRate = 48000;
  6680. config.dataCallback = ma_data_callback;
  6681. config.pUserData = pMyUserData;
  6682. ```
  6683. See Also
  6684. --------
  6685. ma_device_init()
  6686. ma_device_init_ex()
  6687. */
  6688. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType);
  6689. /*
  6690. Initializes a device.
  6691. 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
  6692. 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
  6693. 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
  6694. device is done via a callback which is fired by miniaudio at periodic time intervals.
  6695. 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
  6696. or milliseconds, whichever is more convenient. Generally speaking, the smaller the period, the lower the latency at the expense of higher CPU usage and
  6697. 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
  6698. 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
  6699. 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
  6700. backend is ultimately responsible for what it gives you. You cannot assume you will get exactly what you ask for.
  6701. 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
  6702. 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
  6703. 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.
  6704. Parameters
  6705. ----------
  6706. pContext (in, optional)
  6707. A pointer to the context that owns the device. This can be null, in which case it creates a default context internally.
  6708. pConfig (in)
  6709. A pointer to the device configuration. Cannot be null. See remarks for details.
  6710. pDevice (out)
  6711. A pointer to the device object being initialized.
  6712. Return Value
  6713. ------------
  6714. MA_SUCCESS if successful; any other error code otherwise.
  6715. Thread Safety
  6716. -------------
  6717. 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
  6718. calling this at the same time as `ma_device_uninit()`.
  6719. Callback Safety
  6720. ---------------
  6721. Unsafe. It is not safe to call this inside any callback.
  6722. Remarks
  6723. -------
  6724. Setting `pContext` to NULL will result in miniaudio creating a default context internally and is equivalent to passing in a context initialized like so:
  6725. ```c
  6726. ma_context_init(NULL, 0, NULL, &context);
  6727. ```
  6728. 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
  6729. device.pContext for the initialization of other devices.
  6730. The device can be configured via the `pConfig` argument. The config object is initialized with `ma_device_config_init()`. Individual configuration settings can
  6731. then be set directly on the structure. Below are the members of the `ma_device_config` object.
  6732. deviceType
  6733. Must be `ma_device_type_playback`, `ma_device_type_capture`, `ma_device_type_duplex` of `ma_device_type_loopback`.
  6734. sampleRate
  6735. 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.
  6736. periodSizeInFrames
  6737. 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
  6738. be used depending on the selected performance profile. This value affects latency. See below for details.
  6739. periodSizeInMilliseconds
  6740. 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
  6741. used depending on the selected performance profile. The value affects latency. See below for details.
  6742. periods
  6743. The number of periods making up the device's entire buffer. The total buffer size is `periodSizeInFrames` or `periodSizeInMilliseconds` multiplied by
  6744. this value. This is just a hint as backends will be the ones who ultimately decide how your periods will be configured.
  6745. performanceProfile
  6746. A hint to miniaudio as to the performance requirements of your program. Can be either `ma_performance_profile_low_latency` (default) or
  6747. `ma_performance_profile_conservative`. This mainly affects the size of default buffers and can usually be left at it's default value.
  6748. noPreSilencedOutputBuffer
  6749. 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
  6750. 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
  6751. callback will write to every sample in the output buffer, or if you are doing your own clearing.
  6752. noClip
  6753. When set to true, the contents of the output buffer passed into the data callback will be clipped after returning. When set to false (default), the
  6754. contents of the output buffer are left alone after returning and it will be left up to the backend itself to decide whether or not the clip. This only
  6755. applies when the playback sample format is f32.
  6756. noDisableDenormals
  6757. By default, miniaudio will disable denormals when the data callback is called. Setting this to true will prevent the disabling of denormals.
  6758. noFixedSizedCallback
  6759. 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
  6760. consistent frame count as specified by `periodSizeInFrames` or `periodSizeInMilliseconds`. When set to true, miniaudio will fire the callback with
  6761. whatever the backend requests, which could be anything.
  6762. dataCallback
  6763. The callback to fire whenever data is ready to be delivered to or from the device.
  6764. notificationCallback
  6765. The callback to fire when something has changed with the device, such as whether or not it has been started or stopped.
  6766. pUserData
  6767. The user data pointer to use with the device. You can access this directly from the device object like `device.pUserData`.
  6768. resampling.algorithm
  6769. The resampling algorithm to use when miniaudio needs to perform resampling between the rate specified by `sampleRate` and the device's native rate. The
  6770. default value is `ma_resample_algorithm_linear`, and the quality can be configured with `resampling.linear.lpfOrder`.
  6771. resampling.pBackendVTable
  6772. A pointer to an optional vtable that can be used for plugging in a custom resampler.
  6773. resampling.pBackendUserData
  6774. A pointer that will passed to callbacks in pBackendVTable.
  6775. resampling.linear.lpfOrder
  6776. The linear resampler applies a low-pass filter as part of it's procesing for anti-aliasing. This setting controls the order of the filter. The higher
  6777. the value, the better the quality, in general. Setting this to 0 will disable low-pass filtering altogether. The maximum value is
  6778. `MA_MAX_FILTER_ORDER`. The default value is `min(4, MA_MAX_FILTER_ORDER)`.
  6779. playback.pDeviceID
  6780. 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
  6781. default playback device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  6782. playback.format
  6783. 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
  6784. initialization from the device object directly with `device.playback.format`.
  6785. playback.channels
  6786. 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
  6787. from the device object directly with `device.playback.channels`.
  6788. playback.pChannelMap
  6789. 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
  6790. device object direct with `device.playback.pChannelMap`. When set, the buffer should contain `channels` items.
  6791. playback.shareMode
  6792. 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
  6793. 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
  6794. ma_share_mode_shared and reinitializing.
  6795. capture.pDeviceID
  6796. 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
  6797. default capture device. Retrieve the device ID from the `ma_device_info` structure, which can be retrieved using device enumeration.
  6798. capture.format
  6799. 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
  6800. initialization from the device object directly with `device.capture.format`.
  6801. capture.channels
  6802. 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
  6803. from the device object directly with `device.capture.channels`.
  6804. capture.pChannelMap
  6805. 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
  6806. device object direct with `device.capture.pChannelMap`. When set, the buffer should contain `channels` items.
  6807. capture.shareMode
  6808. 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
  6809. 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
  6810. ma_share_mode_shared and reinitializing.
  6811. wasapi.noAutoConvertSRC
  6812. WASAPI only. When set to true, disables WASAPI's automatic resampling and forces the use of miniaudio's resampler. Defaults to false.
  6813. wasapi.noDefaultQualitySRC
  6814. WASAPI only. Only used when `wasapi.noAutoConvertSRC` is set to false. When set to true, disables the use of `AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY`.
  6815. You should usually leave this set to false, which is the default.
  6816. wasapi.noAutoStreamRouting
  6817. WASAPI only. When set to true, disables automatic stream routing on the WASAPI backend. Defaults to false.
  6818. wasapi.noHardwareOffloading
  6819. WASAPI only. When set to true, disables the use of WASAPI's hardware offloading feature. Defaults to false.
  6820. alsa.noMMap
  6821. ALSA only. When set to true, disables MMap mode. Defaults to false.
  6822. alsa.noAutoFormat
  6823. ALSA only. When set to true, disables ALSA's automatic format conversion by including the SND_PCM_NO_AUTO_FORMAT flag. Defaults to false.
  6824. alsa.noAutoChannels
  6825. ALSA only. When set to true, disables ALSA's automatic channel conversion by including the SND_PCM_NO_AUTO_CHANNELS flag. Defaults to false.
  6826. alsa.noAutoResample
  6827. ALSA only. When set to true, disables ALSA's automatic resampling by including the SND_PCM_NO_AUTO_RESAMPLE flag. Defaults to false.
  6828. pulse.pStreamNamePlayback
  6829. PulseAudio only. Sets the stream name for playback.
  6830. pulse.pStreamNameCapture
  6831. PulseAudio only. Sets the stream name for capture.
  6832. coreaudio.allowNominalSampleRateChange
  6833. Core Audio only. Desktop only. When enabled, allows the sample rate of the device to be changed at the operating system level. This
  6834. 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
  6835. that is known to be natively supported by the hardware thereby avoiding the cost of resampling. When set to true, miniaudio will
  6836. find the closest match between the sample rate requested in the device config and the sample rates natively supported by the
  6837. hardware. When set to false, the sample rate currently set by the operating system will always be used.
  6838. opensl.streamType
  6839. OpenSL only. Explicitly sets the stream type. If left unset (`ma_opensl_stream_type_default`), the
  6840. stream type will be left unset. Think of this as the type of audio you're playing.
  6841. opensl.recordingPreset
  6842. OpenSL only. Explicitly sets the type of recording your program will be doing. When left
  6843. unset, the recording preset will be left unchanged.
  6844. aaudio.usage
  6845. AAudio only. Explicitly sets the nature of the audio the program will be consuming. When
  6846. left unset, the usage will be left unchanged.
  6847. aaudio.contentType
  6848. AAudio only. Sets the content type. When left unset, the content type will be left unchanged.
  6849. aaudio.inputPreset
  6850. AAudio only. Explicitly sets the type of recording your program will be doing. When left
  6851. unset, the input preset will be left unchanged.
  6852. aaudio.noAutoStartAfterReroute
  6853. AAudio only. Controls whether or not the device should be automatically restarted after a
  6854. stream reroute. When set to false (default) the device will be restarted automatically;
  6855. otherwise the device will be stopped.
  6856. Once initialized, the device's config is immutable. If you need to change the config you will need to initialize a new device.
  6857. After initializing the device it will be in a stopped state. To start it, use `ma_device_start()`.
  6858. If both `periodSizeInFrames` and `periodSizeInMilliseconds` are set to zero, it will default to `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY` or
  6859. `MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE`, depending on whether or not `performanceProfile` is set to `ma_performance_profile_low_latency` or
  6860. `ma_performance_profile_conservative`.
  6861. 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
  6862. 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
  6863. 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,
  6864. 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.
  6865. Starting with Windows 10, miniaudio will use low-latency shared mode where possible which may make exclusive mode unnecessary.
  6866. 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
  6867. 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
  6868. on an optimized pass-through fast path. You can retrieve the format, channel count and sample rate by inspecting the `playback/capture.format`,
  6869. `playback/capture.channels` and `sampleRate` members of the device object.
  6870. 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
  6871. asking for permissions. Please refer to the official documentation for ActivateAudioInterfaceAsync() for more information.
  6872. ALSA Specific: When initializing the default device, requesting shared mode will try using the "dmix" device for playback and the "dsnoop" device for capture.
  6873. If these fail it will try falling back to the "hw" device.
  6874. Example 1 - Simple Initialization
  6875. ---------------------------------
  6876. 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
  6877. playback device this is usually all you need.
  6878. ```c
  6879. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  6880. config.playback.format = ma_format_f32;
  6881. config.playback.channels = 2;
  6882. config.sampleRate = 48000;
  6883. config.dataCallback = ma_data_callback;
  6884. config.pMyUserData = pMyUserData;
  6885. ma_device device;
  6886. ma_result result = ma_device_init(NULL, &config, &device);
  6887. if (result != MA_SUCCESS) {
  6888. // Error
  6889. }
  6890. ```
  6891. Example 2 - Advanced Initialization
  6892. -----------------------------------
  6893. 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
  6894. 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
  6895. enumeration.
  6896. ```c
  6897. ma_context context;
  6898. ma_result result = ma_context_init(NULL, 0, NULL, &context);
  6899. if (result != MA_SUCCESS) {
  6900. // Error
  6901. }
  6902. ma_device_info* pPlaybackDeviceInfos;
  6903. ma_uint32 playbackDeviceCount;
  6904. result = ma_context_get_devices(&context, &pPlaybackDeviceInfos, &playbackDeviceCount, NULL, NULL);
  6905. if (result != MA_SUCCESS) {
  6906. // Error
  6907. }
  6908. // ... choose a device from pPlaybackDeviceInfos ...
  6909. ma_device_config config = ma_device_config_init(ma_device_type_playback);
  6910. config.playback.pDeviceID = pMyChosenDeviceID; // <-- Get this from the `id` member of one of the `ma_device_info` objects returned by ma_context_get_devices().
  6911. config.playback.format = ma_format_f32;
  6912. config.playback.channels = 2;
  6913. config.sampleRate = 48000;
  6914. config.dataCallback = ma_data_callback;
  6915. config.pUserData = pMyUserData;
  6916. config.periodSizeInMilliseconds = 10;
  6917. config.periods = 3;
  6918. ma_device device;
  6919. result = ma_device_init(&context, &config, &device);
  6920. if (result != MA_SUCCESS) {
  6921. // Error
  6922. }
  6923. ```
  6924. See Also
  6925. --------
  6926. ma_device_config_init()
  6927. ma_device_uninit()
  6928. ma_device_start()
  6929. ma_context_init()
  6930. ma_context_get_devices()
  6931. ma_context_enumerate_devices()
  6932. */
  6933. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice);
  6934. /*
  6935. Initializes a device without a context, with extra parameters for controlling the configuration of the internal self-managed context.
  6936. 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
  6937. allows you to configure the internally created context.
  6938. Parameters
  6939. ----------
  6940. backends (in, optional)
  6941. A list of backends to try initializing, in priority order. Can be NULL, in which case it uses default priority order.
  6942. backendCount (in, optional)
  6943. The number of items in `backend`. Ignored if `backend` is NULL.
  6944. pContextConfig (in, optional)
  6945. The context configuration.
  6946. pConfig (in)
  6947. A pointer to the device configuration. Cannot be null. See remarks for details.
  6948. pDevice (out)
  6949. A pointer to the device object being initialized.
  6950. Return Value
  6951. ------------
  6952. MA_SUCCESS if successful; any other error code otherwise.
  6953. Thread Safety
  6954. -------------
  6955. 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
  6956. calling this at the same time as `ma_device_uninit()`.
  6957. Callback Safety
  6958. ---------------
  6959. Unsafe. It is not safe to call this inside any callback.
  6960. Remarks
  6961. -------
  6962. 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
  6963. your own context.
  6964. See the documentation for `ma_context_init()` for information on the different context configuration options.
  6965. See Also
  6966. --------
  6967. ma_device_init()
  6968. ma_device_uninit()
  6969. ma_device_config_init()
  6970. ma_context_init()
  6971. */
  6972. 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);
  6973. /*
  6974. Uninitializes a device.
  6975. This will explicitly stop the device. You do not need to call `ma_device_stop()` beforehand, but it's harmless if you do.
  6976. Parameters
  6977. ----------
  6978. pDevice (in)
  6979. A pointer to the device to stop.
  6980. Return Value
  6981. ------------
  6982. Nothing
  6983. Thread Safety
  6984. -------------
  6985. Unsafe. As soon as this API is called the device should be considered undefined.
  6986. Callback Safety
  6987. ---------------
  6988. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  6989. See Also
  6990. --------
  6991. ma_device_init()
  6992. ma_device_stop()
  6993. */
  6994. MA_API void ma_device_uninit(ma_device* pDevice);
  6995. /*
  6996. Retrieves a pointer to the context that owns the given device.
  6997. */
  6998. MA_API ma_context* ma_device_get_context(ma_device* pDevice);
  6999. /*
  7000. Helper function for retrieving the log object associated with the context that owns this device.
  7001. */
  7002. MA_API ma_log* ma_device_get_log(ma_device* pDevice);
  7003. /*
  7004. Retrieves information about the device.
  7005. Parameters
  7006. ----------
  7007. pDevice (in)
  7008. A pointer to the device whose information is being retrieved.
  7009. type (in)
  7010. The device type. This parameter is required for duplex devices. When retrieving device
  7011. information, you are doing so for an individual playback or capture device.
  7012. pDeviceInfo (out)
  7013. A pointer to the `ma_device_info` that will receive the device information.
  7014. Return Value
  7015. ------------
  7016. MA_SUCCESS if successful; any other error code otherwise.
  7017. Thread Safety
  7018. -------------
  7019. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7020. may not be safe.
  7021. Callback Safety
  7022. ---------------
  7023. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7024. which may or may not be safe.
  7025. */
  7026. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo);
  7027. /*
  7028. Retrieves the name of the device.
  7029. Parameters
  7030. ----------
  7031. pDevice (in)
  7032. A pointer to the device whose information is being retrieved.
  7033. type (in)
  7034. The device type. This parameter is required for duplex devices. When retrieving device
  7035. information, you are doing so for an individual playback or capture device.
  7036. pName (out)
  7037. A pointer to the buffer that will receive the name.
  7038. nameCap (in)
  7039. The capacity of the output buffer, including space for the null terminator.
  7040. pLengthNotIncludingNullTerminator (out, optional)
  7041. A pointer to the variable that will receive the length of the name, not including the null
  7042. terminator.
  7043. Return Value
  7044. ------------
  7045. MA_SUCCESS if successful; any other error code otherwise.
  7046. Thread Safety
  7047. -------------
  7048. Unsafe. This should be considered unsafe because it may be calling into the backend which may or
  7049. may not be safe.
  7050. Callback Safety
  7051. ---------------
  7052. Unsafe. You should avoid calling this in the data callback because it may call into the backend
  7053. which may or may not be safe.
  7054. Remarks
  7055. -------
  7056. If the name does not fully fit into the output buffer, it'll be truncated. You can pass in NULL to
  7057. `pName` if you want to first get the length of the name for the purpose of memory allocation of the
  7058. output buffer. Allocating a buffer of size `MA_MAX_DEVICE_NAME_LENGTH + 1` should be enough for
  7059. most cases and will avoid the need for the inefficiency of calling this function twice.
  7060. This is implemented in terms of `ma_device_get_info()`.
  7061. */
  7062. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator);
  7063. /*
  7064. Starts the device. For playback devices this begins playback. For capture devices it begins recording.
  7065. Use `ma_device_stop()` to stop the device.
  7066. Parameters
  7067. ----------
  7068. pDevice (in)
  7069. A pointer to the device to start.
  7070. Return Value
  7071. ------------
  7072. MA_SUCCESS if successful; any other error code otherwise.
  7073. Thread Safety
  7074. -------------
  7075. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7076. Callback Safety
  7077. ---------------
  7078. Unsafe. It is not safe to call this inside any callback.
  7079. Remarks
  7080. -------
  7081. 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
  7082. audio data in the buffer, which needs to be done before the device begins playback.
  7083. 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.
  7084. Do not call this in any callback.
  7085. See Also
  7086. --------
  7087. ma_device_stop()
  7088. */
  7089. MA_API ma_result ma_device_start(ma_device* pDevice);
  7090. /*
  7091. Stops the device. For playback devices this stops playback. For capture devices it stops recording.
  7092. Use `ma_device_start()` to start the device again.
  7093. Parameters
  7094. ----------
  7095. pDevice (in)
  7096. A pointer to the device to stop.
  7097. Return Value
  7098. ------------
  7099. MA_SUCCESS if successful; any other error code otherwise.
  7100. Thread Safety
  7101. -------------
  7102. Safe. It's safe to call this from any thread with the exception of the callback thread.
  7103. Callback Safety
  7104. ---------------
  7105. Unsafe. It is not safe to call this inside any callback. Doing this will result in a deadlock.
  7106. Remarks
  7107. -------
  7108. 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
  7109. 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
  7110. that was specified at initialization time).
  7111. 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
  7112. 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
  7113. speakers or received from the microphone which can in turn result in de-syncs.
  7114. Do not call this in any callback.
  7115. This will be called implicitly by `ma_device_uninit()`.
  7116. See Also
  7117. --------
  7118. ma_device_start()
  7119. */
  7120. MA_API ma_result ma_device_stop(ma_device* pDevice);
  7121. /*
  7122. Determines whether or not the device is started.
  7123. Parameters
  7124. ----------
  7125. pDevice (in)
  7126. A pointer to the device whose start state is being retrieved.
  7127. Return Value
  7128. ------------
  7129. True if the device is started, false otherwise.
  7130. Thread Safety
  7131. -------------
  7132. 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
  7133. value will be out of sync.
  7134. Callback Safety
  7135. ---------------
  7136. Safe. This is implemented as a simple accessor.
  7137. See Also
  7138. --------
  7139. ma_device_start()
  7140. ma_device_stop()
  7141. */
  7142. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice);
  7143. /*
  7144. Retrieves the state of the device.
  7145. Parameters
  7146. ----------
  7147. pDevice (in)
  7148. A pointer to the device whose state is being retrieved.
  7149. Return Value
  7150. ------------
  7151. The current state of the device. The return value will be one of the following:
  7152. +-------------------------------+------------------------------------------------------------------------------+
  7153. | ma_device_state_uninitialized | Will only be returned if the device is in the middle of initialization. |
  7154. +-------------------------------+------------------------------------------------------------------------------+
  7155. | ma_device_state_stopped | The device is stopped. The initial state of the device after initialization. |
  7156. +-------------------------------+------------------------------------------------------------------------------+
  7157. | ma_device_state_started | The device started and requesting and/or delivering audio data. |
  7158. +-------------------------------+------------------------------------------------------------------------------+
  7159. | ma_device_state_starting | The device is in the process of starting. |
  7160. +-------------------------------+------------------------------------------------------------------------------+
  7161. | ma_device_state_stopping | The device is in the process of stopping. |
  7162. +-------------------------------+------------------------------------------------------------------------------+
  7163. Thread Safety
  7164. -------------
  7165. 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,
  7166. there's a possibility the return value could be out of sync. See remarks.
  7167. Callback Safety
  7168. ---------------
  7169. Safe. This is implemented as a simple accessor.
  7170. Remarks
  7171. -------
  7172. The general flow of a devices state goes like this:
  7173. ```
  7174. ma_device_init() -> ma_device_state_uninitialized -> ma_device_state_stopped
  7175. ma_device_start() -> ma_device_state_starting -> ma_device_state_started
  7176. ma_device_stop() -> ma_device_state_stopping -> ma_device_state_stopped
  7177. ```
  7178. 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
  7179. value returned by this function could potentially be out of sync. If this is significant to your program you need to implement your own
  7180. synchronization.
  7181. */
  7182. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice);
  7183. /*
  7184. Performs post backend initialization routines for setting up internal data conversion.
  7185. This should be called whenever the backend is initialized. The only time this should be called from
  7186. outside of miniaudio is if you're implementing a custom backend, and you would only do it if you
  7187. are reinitializing the backend due to rerouting or reinitializing for some reason.
  7188. Parameters
  7189. ----------
  7190. pDevice [in]
  7191. A pointer to the device.
  7192. deviceType [in]
  7193. The type of the device that was just reinitialized.
  7194. pPlaybackDescriptor [in]
  7195. The descriptor of the playback device containing the internal data format and buffer sizes.
  7196. pPlaybackDescriptor [in]
  7197. The descriptor of the capture device containing the internal data format and buffer sizes.
  7198. Return Value
  7199. ------------
  7200. MA_SUCCESS if successful; any other error otherwise.
  7201. Thread Safety
  7202. -------------
  7203. Unsafe. This will be reinitializing internal data converters which may be in use by another thread.
  7204. Callback Safety
  7205. ---------------
  7206. Unsafe. This will be reinitializing internal data converters which may be in use by the callback.
  7207. Remarks
  7208. -------
  7209. For a duplex device, you can call this for only one side of the system. This is why the deviceType
  7210. is specified as a parameter rather than deriving it from the device.
  7211. You do not need to call this manually unless you are doing a custom backend, in which case you need
  7212. only do it if you're manually performing rerouting or reinitialization.
  7213. */
  7214. 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);
  7215. /*
  7216. Sets the master volume factor for the device.
  7217. 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
  7218. values less than 0 decreases the volume.
  7219. Parameters
  7220. ----------
  7221. pDevice (in)
  7222. A pointer to the device whose volume is being set.
  7223. volume (in)
  7224. The new volume factor. Must be >= 0.
  7225. Return Value
  7226. ------------
  7227. MA_SUCCESS if the volume was set successfully.
  7228. MA_INVALID_ARGS if pDevice is NULL.
  7229. MA_INVALID_ARGS if volume is negative.
  7230. Thread Safety
  7231. -------------
  7232. Safe. This just sets a local member of the device object.
  7233. Callback Safety
  7234. ---------------
  7235. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7236. Remarks
  7237. -------
  7238. This applies the volume factor across all channels.
  7239. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7240. See Also
  7241. --------
  7242. ma_device_get_master_volume()
  7243. ma_device_set_master_volume_db()
  7244. ma_device_get_master_volume_db()
  7245. */
  7246. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume);
  7247. /*
  7248. Retrieves the master volume factor for the device.
  7249. Parameters
  7250. ----------
  7251. pDevice (in)
  7252. A pointer to the device whose volume factor is being retrieved.
  7253. pVolume (in)
  7254. A pointer to the variable that will receive the volume factor. The returned value will be in the range of [0, 1].
  7255. Return Value
  7256. ------------
  7257. MA_SUCCESS if successful.
  7258. MA_INVALID_ARGS if pDevice is NULL.
  7259. MA_INVALID_ARGS if pVolume is NULL.
  7260. Thread Safety
  7261. -------------
  7262. Safe. This just a simple member retrieval.
  7263. Callback Safety
  7264. ---------------
  7265. Safe.
  7266. Remarks
  7267. -------
  7268. If an error occurs, `*pVolume` will be set to 0.
  7269. See Also
  7270. --------
  7271. ma_device_set_master_volume()
  7272. ma_device_set_master_volume_gain_db()
  7273. ma_device_get_master_volume_gain_db()
  7274. */
  7275. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume);
  7276. /*
  7277. Sets the master volume for the device as gain in decibels.
  7278. A gain of 0 is full volume, whereas a gain of < 0 will decrease the volume.
  7279. Parameters
  7280. ----------
  7281. pDevice (in)
  7282. A pointer to the device whose gain is being set.
  7283. gainDB (in)
  7284. 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.
  7285. Return Value
  7286. ------------
  7287. MA_SUCCESS if the volume was set successfully.
  7288. MA_INVALID_ARGS if pDevice is NULL.
  7289. MA_INVALID_ARGS if the gain is > 0.
  7290. Thread Safety
  7291. -------------
  7292. Safe. This just sets a local member of the device object.
  7293. Callback Safety
  7294. ---------------
  7295. Safe. If you set the volume in the data callback, that data written to the output buffer will have the new volume applied.
  7296. Remarks
  7297. -------
  7298. This applies the gain across all channels.
  7299. This does not change the operating system's volume. It only affects the volume for the given `ma_device` object's audio stream.
  7300. See Also
  7301. --------
  7302. ma_device_get_master_volume_gain_db()
  7303. ma_device_set_master_volume()
  7304. ma_device_get_master_volume()
  7305. */
  7306. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB);
  7307. /*
  7308. Retrieves the master gain in decibels.
  7309. Parameters
  7310. ----------
  7311. pDevice (in)
  7312. A pointer to the device whose gain is being retrieved.
  7313. pGainDB (in)
  7314. A pointer to the variable that will receive the gain in decibels. The returned value will be <= 0.
  7315. Return Value
  7316. ------------
  7317. MA_SUCCESS if successful.
  7318. MA_INVALID_ARGS if pDevice is NULL.
  7319. MA_INVALID_ARGS if pGainDB is NULL.
  7320. Thread Safety
  7321. -------------
  7322. Safe. This just a simple member retrieval.
  7323. Callback Safety
  7324. ---------------
  7325. Safe.
  7326. Remarks
  7327. -------
  7328. If an error occurs, `*pGainDB` will be set to 0.
  7329. See Also
  7330. --------
  7331. ma_device_set_master_volume_db()
  7332. ma_device_set_master_volume()
  7333. ma_device_get_master_volume()
  7334. */
  7335. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB);
  7336. /*
  7337. Called from the data callback of asynchronous backends to allow miniaudio to process the data and fire the miniaudio data callback.
  7338. Parameters
  7339. ----------
  7340. pDevice (in)
  7341. A pointer to device whose processing the data callback.
  7342. pOutput (out)
  7343. 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
  7344. this can be NULL, in which case pInput must not be NULL.
  7345. pInput (in)
  7346. 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
  7347. NULL, in which case `pOutput` must not be NULL.
  7348. frameCount (in)
  7349. The number of frames being processed.
  7350. Return Value
  7351. ------------
  7352. MA_SUCCESS if successful; any other result code otherwise.
  7353. Thread Safety
  7354. -------------
  7355. This function should only ever be called from the internal data callback of the backend. It is safe to call this simultaneously between a
  7356. playback and capture device in duplex setups.
  7357. Callback Safety
  7358. ---------------
  7359. Do not call this from the miniaudio data callback. It should only ever be called from the internal data callback of the backend.
  7360. Remarks
  7361. -------
  7362. If both `pOutput` and `pInput` are NULL, and error will be returned. In duplex scenarios, both `pOutput` and `pInput` can be non-NULL, in
  7363. which case `pInput` will be processed first, followed by `pOutput`.
  7364. 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
  7365. callback.
  7366. */
  7367. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount);
  7368. /*
  7369. Calculates an appropriate buffer size from a descriptor, native sample rate and performance profile.
  7370. This function is used by backends for helping determine an appropriately sized buffer to use with
  7371. the device depending on the values of `periodSizeInFrames` and `periodSizeInMilliseconds` in the
  7372. `pDescriptor` object. Since buffer size calculations based on time depends on the sample rate, a
  7373. best guess at the device's native sample rate is also required which is where `nativeSampleRate`
  7374. comes in. In addition, the performance profile is also needed for cases where both the period size
  7375. in frames and milliseconds are both zero.
  7376. Parameters
  7377. ----------
  7378. pDescriptor (in)
  7379. A pointer to device descriptor whose `periodSizeInFrames` and `periodSizeInMilliseconds` members
  7380. will be used for the calculation of the buffer size.
  7381. nativeSampleRate (in)
  7382. The device's native sample rate. This is only ever used when the `periodSizeInFrames` member of
  7383. `pDescriptor` is zero. In this case, `periodSizeInMilliseconds` will be used instead, in which
  7384. case a sample rate is required to convert to a size in frames.
  7385. performanceProfile (in)
  7386. When both the `periodSizeInFrames` and `periodSizeInMilliseconds` members of `pDescriptor` are
  7387. zero, miniaudio will fall back to a buffer size based on the performance profile. The profile
  7388. to use for this calculation is determine by this parameter.
  7389. Return Value
  7390. ------------
  7391. The calculated buffer size in frames.
  7392. Thread Safety
  7393. -------------
  7394. This is safe so long as nothing modifies `pDescriptor` at the same time. However, this function
  7395. should only ever be called from within the backend's device initialization routine and therefore
  7396. shouldn't have any multithreading concerns.
  7397. Callback Safety
  7398. ---------------
  7399. This is safe to call within the data callback, but there is no reason to ever do this.
  7400. Remarks
  7401. -------
  7402. If `nativeSampleRate` is zero, this function will fall back to `pDescriptor->sampleRate`. If that
  7403. is also zero, `MA_DEFAULT_SAMPLE_RATE` will be used instead.
  7404. */
  7405. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile);
  7406. /*
  7407. Retrieves a friendly name for a backend.
  7408. */
  7409. MA_API const char* ma_get_backend_name(ma_backend backend);
  7410. /*
  7411. Determines whether or not the given backend is available by the compilation environment.
  7412. */
  7413. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend);
  7414. /*
  7415. Retrieves compile-time enabled backends.
  7416. Parameters
  7417. ----------
  7418. pBackends (out, optional)
  7419. A pointer to the buffer that will receive the enabled backends. Set to NULL to retrieve the backend count. Setting
  7420. the capacity of the buffer to `MA_BUFFER_COUNT` will guarantee it's large enough for all backends.
  7421. backendCap (in)
  7422. The capacity of the `pBackends` buffer.
  7423. pBackendCount (out)
  7424. A pointer to the variable that will receive the enabled backend count.
  7425. Return Value
  7426. ------------
  7427. MA_SUCCESS if successful.
  7428. MA_INVALID_ARGS if `pBackendCount` is NULL.
  7429. MA_NO_SPACE if the capacity of `pBackends` is not large enough.
  7430. If `MA_NO_SPACE` is returned, the `pBackends` buffer will be filled with `*pBackendCount` values.
  7431. Thread Safety
  7432. -------------
  7433. Safe.
  7434. Callback Safety
  7435. ---------------
  7436. Safe.
  7437. Remarks
  7438. -------
  7439. If you want to retrieve the number of backends so you can determine the capacity of `pBackends` buffer, you can call
  7440. this function with `pBackends` set to NULL.
  7441. This will also enumerate the null backend. If you don't want to include this you need to check for `ma_backend_null`
  7442. when you enumerate over the returned backends and handle it appropriately. Alternatively, you can disable it at
  7443. compile time with `MA_NO_NULL`.
  7444. The returned backends are determined based on compile time settings, not the platform it's currently running on. For
  7445. example, PulseAudio will be returned if it was enabled at compile time, even when the user doesn't actually have
  7446. PulseAudio installed.
  7447. Example 1
  7448. ---------
  7449. The example below retrieves the enabled backend count using a fixed sized buffer allocated on the stack. The buffer is
  7450. given a capacity of `MA_BACKEND_COUNT` which will guarantee it'll be large enough to store all available backends.
  7451. Since `MA_BACKEND_COUNT` is always a relatively small value, this should be suitable for most scenarios.
  7452. ```
  7453. ma_backend enabledBackends[MA_BACKEND_COUNT];
  7454. size_t enabledBackendCount;
  7455. result = ma_get_enabled_backends(enabledBackends, MA_BACKEND_COUNT, &enabledBackendCount);
  7456. if (result != MA_SUCCESS) {
  7457. // Failed to retrieve enabled backends. Should never happen in this example since all inputs are valid.
  7458. }
  7459. ```
  7460. See Also
  7461. --------
  7462. ma_is_backend_enabled()
  7463. */
  7464. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount);
  7465. /*
  7466. Determines whether or not loopback mode is support by a backend.
  7467. */
  7468. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend);
  7469. #endif /* MA_NO_DEVICE_IO */
  7470. /************************************************************************************************************************************************************
  7471. Utiltities
  7472. ************************************************************************************************************************************************************/
  7473. /*
  7474. Calculates a buffer size in milliseconds from the specified number of frames and sample rate.
  7475. */
  7476. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate);
  7477. /*
  7478. Calculates a buffer size in frames from the specified number of milliseconds and sample rate.
  7479. */
  7480. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate);
  7481. /*
  7482. Copies PCM frames from one buffer to another.
  7483. */
  7484. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7485. /*
  7486. Copies silent frames into the given buffer.
  7487. Remarks
  7488. -------
  7489. 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
  7490. makes more sense for the purpose of mixing to initialize it to the center point.
  7491. */
  7492. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7493. /*
  7494. Offsets a pointer by the specified number of PCM frames.
  7495. */
  7496. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7497. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels);
  7498. 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); }
  7499. 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); }
  7500. /*
  7501. Clips samples.
  7502. */
  7503. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count);
  7504. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count);
  7505. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count);
  7506. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count);
  7507. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count);
  7508. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels);
  7509. /*
  7510. Helper for applying a volume factor to samples.
  7511. Note that the source and destination buffers can be the same, in which case it'll perform the operation in-place.
  7512. */
  7513. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor);
  7514. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor);
  7515. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor);
  7516. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor);
  7517. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor);
  7518. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor);
  7519. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor);
  7520. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor);
  7521. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor);
  7522. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor);
  7523. 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);
  7524. 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);
  7525. 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);
  7526. 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);
  7527. 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);
  7528. 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);
  7529. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7530. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7531. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7532. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7533. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor);
  7534. MA_API void ma_apply_volume_factor_pcm_frames(void* pFrames, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor);
  7535. 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);
  7536. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume);
  7537. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume);
  7538. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7539. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume);
  7540. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume);
  7541. 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);
  7542. /*
  7543. Helper for converting a linear factor to gain in decibels.
  7544. */
  7545. MA_API float ma_volume_linear_to_db(float factor);
  7546. /*
  7547. Helper for converting gain in decibels to a linear factor.
  7548. */
  7549. MA_API float ma_volume_db_to_linear(float gain);
  7550. /**************************************************************************************************
  7551. Data Source
  7552. **************************************************************************************************/
  7553. typedef void ma_data_source;
  7554. #define MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT 0x00000001
  7555. typedef struct
  7556. {
  7557. ma_result (* onRead)(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  7558. ma_result (* onSeek)(ma_data_source* pDataSource, ma_uint64 frameIndex);
  7559. ma_result (* onGetDataFormat)(ma_data_source* pDataSource, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate, ma_channel* pChannelMap, size_t channelMapCap);
  7560. ma_result (* onGetCursor)(ma_data_source* pDataSource, ma_uint64* pCursor);
  7561. ma_result (* onGetLength)(ma_data_source* pDataSource, ma_uint64* pLength);
  7562. ma_result (* onSetLooping)(ma_data_source* pDataSource, ma_bool32 isLooping);
  7563. ma_uint32 flags;
  7564. } ma_data_source_vtable;
  7565. typedef ma_data_source* (* ma_data_source_get_next_proc)(ma_data_source* pDataSource);
  7566. typedef struct
  7567. {
  7568. const ma_data_source_vtable* vtable;
  7569. } ma_data_source_config;
  7570. MA_API ma_data_source_config ma_data_source_config_init(void);
  7571. typedef struct
  7572. {
  7573. const ma_data_source_vtable* vtable;
  7574. ma_uint64 rangeBegInFrames;
  7575. ma_uint64 rangeEndInFrames; /* Set to -1 for unranged (default). */
  7576. ma_uint64 loopBegInFrames; /* Relative to rangeBegInFrames. */
  7577. ma_uint64 loopEndInFrames; /* Relative to rangeBegInFrames. Set to -1 for the end of the range. */
  7578. 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. */
  7579. ma_data_source* pNext; /* When set to NULL, onGetNext will be used. */
  7580. ma_data_source_get_next_proc onGetNext; /* Will be used when pNext is NULL. If both are NULL, no next will be used. */
  7581. MA_ATOMIC(4, ma_bool32) isLooping;
  7582. } ma_data_source_base;
  7583. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource);
  7584. MA_API void ma_data_source_uninit(ma_data_source* pDataSource);
  7585. 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. */
  7586. 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); */
  7587. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex);
  7588. 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);
  7589. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor);
  7590. 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. */
  7591. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor);
  7592. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength);
  7593. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping);
  7594. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource);
  7595. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames);
  7596. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames);
  7597. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames);
  7598. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames);
  7599. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource);
  7600. MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource);
  7601. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource);
  7602. MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource);
  7603. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext);
  7604. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource);
  7605. typedef struct
  7606. {
  7607. ma_data_source_base ds;
  7608. ma_format format;
  7609. ma_uint32 channels;
  7610. ma_uint32 sampleRate;
  7611. ma_uint64 cursor;
  7612. ma_uint64 sizeInFrames;
  7613. const void* pData;
  7614. } ma_audio_buffer_ref;
  7615. 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);
  7616. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef);
  7617. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames);
  7618. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  7619. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex);
  7620. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount);
  7621. 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. */
  7622. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef);
  7623. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor);
  7624. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength);
  7625. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames);
  7626. typedef struct
  7627. {
  7628. ma_format format;
  7629. ma_uint32 channels;
  7630. ma_uint32 sampleRate;
  7631. ma_uint64 sizeInFrames;
  7632. const void* pData; /* If set to NULL, will allocate a block of memory for you. */
  7633. ma_allocation_callbacks allocationCallbacks;
  7634. } ma_audio_buffer_config;
  7635. 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);
  7636. typedef struct
  7637. {
  7638. ma_audio_buffer_ref ref;
  7639. ma_allocation_callbacks allocationCallbacks;
  7640. 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(). */
  7641. ma_uint8 _pExtraData[1]; /* For allocating a buffer with the memory located directly after the other memory of the structure. */
  7642. } ma_audio_buffer;
  7643. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  7644. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer);
  7645. 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. */
  7646. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer);
  7647. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer);
  7648. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop);
  7649. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex);
  7650. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount);
  7651. 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. */
  7652. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer);
  7653. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor);
  7654. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength);
  7655. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames);
  7656. /*
  7657. Paged Audio Buffer
  7658. ==================
  7659. A paged audio buffer is made up of a linked list of pages. It's expandable, but not shrinkable. It
  7660. can be used for cases where audio data is streamed in asynchronously while allowing data to be read
  7661. at the same time.
  7662. This is lock-free, but not 100% thread safe. You can append a page and read from the buffer across
  7663. simultaneously across different threads, however only one thread at a time can append, and only one
  7664. thread at a time can read and seek.
  7665. */
  7666. typedef struct ma_paged_audio_buffer_page ma_paged_audio_buffer_page;
  7667. struct ma_paged_audio_buffer_page
  7668. {
  7669. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pNext;
  7670. ma_uint64 sizeInFrames;
  7671. ma_uint8 pAudioData[1];
  7672. };
  7673. typedef struct
  7674. {
  7675. ma_format format;
  7676. ma_uint32 channels;
  7677. ma_paged_audio_buffer_page head; /* Dummy head for the lock-free algorithm. Always has a size of 0. */
  7678. MA_ATOMIC(MA_SIZEOF_PTR, ma_paged_audio_buffer_page*) pTail; /* Never null. Initially set to &head. */
  7679. } ma_paged_audio_buffer_data;
  7680. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData);
  7681. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks);
  7682. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData);
  7683. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData);
  7684. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength);
  7685. 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);
  7686. 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);
  7687. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage);
  7688. 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);
  7689. typedef struct
  7690. {
  7691. ma_paged_audio_buffer_data* pData; /* Must not be null. */
  7692. } ma_paged_audio_buffer_config;
  7693. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData);
  7694. typedef struct
  7695. {
  7696. ma_data_source_base ds;
  7697. ma_paged_audio_buffer_data* pData; /* Audio data is read from here. Cannot be null. */
  7698. ma_paged_audio_buffer_page* pCurrent;
  7699. ma_uint64 relativeCursor; /* Relative to the current page. */
  7700. ma_uint64 absoluteCursor;
  7701. } ma_paged_audio_buffer;
  7702. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer);
  7703. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer);
  7704. 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. */
  7705. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex);
  7706. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor);
  7707. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength);
  7708. /************************************************************************************************************************************************************
  7709. VFS
  7710. ===
  7711. 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
  7712. appropriate for a given situation.
  7713. ************************************************************************************************************************************************************/
  7714. typedef void ma_vfs;
  7715. typedef ma_handle ma_vfs_file;
  7716. typedef enum
  7717. {
  7718. MA_OPEN_MODE_READ = 0x00000001,
  7719. MA_OPEN_MODE_WRITE = 0x00000002
  7720. } ma_open_mode_flags;
  7721. typedef enum
  7722. {
  7723. ma_seek_origin_start,
  7724. ma_seek_origin_current,
  7725. ma_seek_origin_end /* Not used by decoders. */
  7726. } ma_seek_origin;
  7727. typedef struct
  7728. {
  7729. ma_uint64 sizeInBytes;
  7730. } ma_file_info;
  7731. typedef struct
  7732. {
  7733. ma_result (* onOpen) (ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7734. ma_result (* onOpenW)(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7735. ma_result (* onClose)(ma_vfs* pVFS, ma_vfs_file file);
  7736. ma_result (* onRead) (ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7737. ma_result (* onWrite)(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7738. ma_result (* onSeek) (ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7739. ma_result (* onTell) (ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7740. ma_result (* onInfo) (ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7741. } ma_vfs_callbacks;
  7742. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7743. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile);
  7744. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file);
  7745. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead);
  7746. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten);
  7747. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin);
  7748. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor);
  7749. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo);
  7750. 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);
  7751. typedef struct
  7752. {
  7753. ma_vfs_callbacks cb;
  7754. ma_allocation_callbacks allocationCallbacks; /* Only used for the wchar_t version of open() on non-Windows platforms. */
  7755. } ma_default_vfs;
  7756. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks);
  7757. typedef ma_result (* ma_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead);
  7758. typedef ma_result (* ma_seek_proc)(void* pUserData, ma_int64 offset, ma_seek_origin origin);
  7759. typedef ma_result (* ma_tell_proc)(void* pUserData, ma_int64* pCursor);
  7760. #if !defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING)
  7761. typedef enum
  7762. {
  7763. ma_encoding_format_unknown = 0,
  7764. ma_encoding_format_wav,
  7765. ma_encoding_format_flac,
  7766. ma_encoding_format_mp3,
  7767. ma_encoding_format_vorbis
  7768. } ma_encoding_format;
  7769. #endif
  7770. /************************************************************************************************************************************************************
  7771. Decoding
  7772. ========
  7773. 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
  7774. you do your own synchronization.
  7775. ************************************************************************************************************************************************************/
  7776. #ifndef MA_NO_DECODING
  7777. typedef struct ma_decoder ma_decoder;
  7778. typedef struct
  7779. {
  7780. ma_format preferredFormat;
  7781. ma_uint32 seekPointCount; /* Set to > 0 to generate a seektable if the decoding backend supports it. */
  7782. } ma_decoding_backend_config;
  7783. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount);
  7784. typedef struct
  7785. {
  7786. 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);
  7787. ma_result (* onInitFile )(void* pUserData, const char* pFilePath, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_source** ppBackend); /* Optional. */
  7788. 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. */
  7789. 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. */
  7790. void (* onUninit )(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks);
  7791. } ma_decoding_backend_vtable;
  7792. typedef ma_result (* ma_decoder_read_proc)(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead); /* Returns the number of bytes read. */
  7793. typedef ma_result (* ma_decoder_seek_proc)(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin);
  7794. typedef ma_result (* ma_decoder_tell_proc)(ma_decoder* pDecoder, ma_int64* pCursor);
  7795. typedef struct
  7796. {
  7797. ma_format format; /* Set to 0 or ma_format_unknown to use the stream's internal format. */
  7798. ma_uint32 channels; /* Set to 0 to use the stream's internal channels. */
  7799. ma_uint32 sampleRate; /* Set to 0 to use the stream's internal sample rate. */
  7800. ma_channel* pChannelMap;
  7801. ma_channel_mix_mode channelMixMode;
  7802. ma_dither_mode ditherMode;
  7803. ma_resampler_config resampling;
  7804. ma_allocation_callbacks allocationCallbacks;
  7805. ma_encoding_format encodingFormat;
  7806. 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. */
  7807. ma_decoding_backend_vtable** ppCustomBackendVTables;
  7808. ma_uint32 customBackendCount;
  7809. void* pCustomBackendUserData;
  7810. } ma_decoder_config;
  7811. struct ma_decoder
  7812. {
  7813. ma_data_source_base ds;
  7814. ma_data_source* pBackend; /* The decoding backend we'll be pulling data from. */
  7815. const ma_decoding_backend_vtable* pBackendVTable; /* The vtable for the decoding backend. This needs to be stored so we can access the onUninit() callback. */
  7816. void* pBackendUserData;
  7817. ma_decoder_read_proc onRead;
  7818. ma_decoder_seek_proc onSeek;
  7819. ma_decoder_tell_proc onTell;
  7820. void* pUserData;
  7821. ma_uint64 readPointerInPCMFrames; /* In output sample rate. Used for keeping track of how many frames are available for decoding. */
  7822. ma_format outputFormat;
  7823. ma_uint32 outputChannels;
  7824. ma_uint32 outputSampleRate;
  7825. ma_data_converter converter; /* Data conversion is achieved by running frames through this. */
  7826. void* pInputCache; /* In input format. Can be null if it's not needed. */
  7827. ma_uint64 inputCacheCap; /* The capacity of the input cache. */
  7828. ma_uint64 inputCacheConsumed; /* The number of frames that have been consumed in the cache. Used for determining the next valid frame. */
  7829. ma_uint64 inputCacheRemaining; /* The number of valid frames remaining in the cahce. */
  7830. ma_allocation_callbacks allocationCallbacks;
  7831. union
  7832. {
  7833. struct
  7834. {
  7835. ma_vfs* pVFS;
  7836. ma_vfs_file file;
  7837. } vfs;
  7838. struct
  7839. {
  7840. const ma_uint8* pData;
  7841. size_t dataSize;
  7842. size_t currentReadPos;
  7843. } memory; /* Only used for decoders that were opened against a block of memory. */
  7844. } data;
  7845. };
  7846. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate);
  7847. MA_API ma_decoder_config ma_decoder_config_init_default(void);
  7848. 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);
  7849. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  7850. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  7851. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  7852. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  7853. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder);
  7854. /*
  7855. Uninitializes a decoder.
  7856. */
  7857. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder);
  7858. /*
  7859. Reads PCM frames from the given decoder.
  7860. This is not thread safe without your own synchronization.
  7861. */
  7862. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  7863. /*
  7864. Seeks to a PCM frame based on it's absolute index.
  7865. This is not thread safe without your own synchronization.
  7866. */
  7867. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex);
  7868. /*
  7869. Retrieves the decoder's output data format.
  7870. */
  7871. 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);
  7872. /*
  7873. Retrieves the current position of the read cursor in PCM frames.
  7874. */
  7875. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor);
  7876. /*
  7877. Retrieves the length of the decoder in PCM frames.
  7878. Do not call this on streams of an undefined length, such as internet radio.
  7879. If the length is unknown or an error occurs, 0 will be returned.
  7880. This will always return 0 for Vorbis decoders. This is due to a limitation with stb_vorbis in push mode which is what miniaudio
  7881. uses internally.
  7882. For MP3's, this will decode the entire file. Do not call this in time critical scenarios.
  7883. This function is not thread safe without your own synchronization.
  7884. */
  7885. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength);
  7886. /*
  7887. Retrieves the number of frames that can be read before reaching the end.
  7888. This calls `ma_decoder_get_length_in_pcm_frames()` so you need to be aware of the rules for that function, in
  7889. particular ensuring you do not call it on streams of an undefined length, such as internet radio.
  7890. If the total length of the decoder cannot be retrieved, such as with Vorbis decoders, `MA_NOT_IMPLEMENTED` will be
  7891. returned.
  7892. */
  7893. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames);
  7894. /*
  7895. Helper for opening and decoding a file into a heap allocated block of memory. Free the returned pointer with ma_free(). On input,
  7896. pConfig should be set to what you want. On output it will be set to what you got.
  7897. */
  7898. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  7899. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  7900. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut);
  7901. #endif /* MA_NO_DECODING */
  7902. /************************************************************************************************************************************************************
  7903. Encoding
  7904. ========
  7905. Encoders do not perform any format conversion for you. If your target format does not support the format, and error will be returned.
  7906. ************************************************************************************************************************************************************/
  7907. #ifndef MA_NO_ENCODING
  7908. typedef struct ma_encoder ma_encoder;
  7909. typedef ma_result (* ma_encoder_write_proc) (ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten);
  7910. typedef ma_result (* ma_encoder_seek_proc) (ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin);
  7911. typedef ma_result (* ma_encoder_init_proc) (ma_encoder* pEncoder);
  7912. typedef void (* ma_encoder_uninit_proc) (ma_encoder* pEncoder);
  7913. typedef ma_result (* ma_encoder_write_pcm_frames_proc)(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  7914. typedef struct
  7915. {
  7916. ma_encoding_format encodingFormat;
  7917. ma_format format;
  7918. ma_uint32 channels;
  7919. ma_uint32 sampleRate;
  7920. ma_allocation_callbacks allocationCallbacks;
  7921. } ma_encoder_config;
  7922. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate);
  7923. struct ma_encoder
  7924. {
  7925. ma_encoder_config config;
  7926. ma_encoder_write_proc onWrite;
  7927. ma_encoder_seek_proc onSeek;
  7928. ma_encoder_init_proc onInit;
  7929. ma_encoder_uninit_proc onUninit;
  7930. ma_encoder_write_pcm_frames_proc onWritePCMFrames;
  7931. void* pUserData;
  7932. void* pInternalEncoder; /* <-- The drwav/drflac/stb_vorbis/etc. objects. */
  7933. union
  7934. {
  7935. struct
  7936. {
  7937. ma_vfs* pVFS;
  7938. ma_vfs_file file;
  7939. } vfs;
  7940. } data;
  7941. };
  7942. 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);
  7943. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  7944. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  7945. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  7946. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder);
  7947. MA_API void ma_encoder_uninit(ma_encoder* pEncoder);
  7948. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten);
  7949. #endif /* MA_NO_ENCODING */
  7950. /************************************************************************************************************************************************************
  7951. Generation
  7952. ************************************************************************************************************************************************************/
  7953. #ifndef MA_NO_GENERATION
  7954. typedef enum
  7955. {
  7956. ma_waveform_type_sine,
  7957. ma_waveform_type_square,
  7958. ma_waveform_type_triangle,
  7959. ma_waveform_type_sawtooth
  7960. } ma_waveform_type;
  7961. typedef struct
  7962. {
  7963. ma_format format;
  7964. ma_uint32 channels;
  7965. ma_uint32 sampleRate;
  7966. ma_waveform_type type;
  7967. double amplitude;
  7968. double frequency;
  7969. } ma_waveform_config;
  7970. 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);
  7971. typedef struct
  7972. {
  7973. ma_data_source_base ds;
  7974. ma_waveform_config config;
  7975. double advance;
  7976. double time;
  7977. } ma_waveform;
  7978. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform);
  7979. MA_API void ma_waveform_uninit(ma_waveform* pWaveform);
  7980. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  7981. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex);
  7982. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude);
  7983. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency);
  7984. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type);
  7985. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate);
  7986. typedef enum
  7987. {
  7988. ma_noise_type_white,
  7989. ma_noise_type_pink,
  7990. ma_noise_type_brownian
  7991. } ma_noise_type;
  7992. typedef struct
  7993. {
  7994. ma_format format;
  7995. ma_uint32 channels;
  7996. ma_noise_type type;
  7997. ma_int32 seed;
  7998. double amplitude;
  7999. ma_bool32 duplicateChannels;
  8000. } ma_noise_config;
  8001. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude);
  8002. typedef struct
  8003. {
  8004. ma_data_source_vtable ds;
  8005. ma_noise_config config;
  8006. ma_lcg lcg;
  8007. union
  8008. {
  8009. struct
  8010. {
  8011. double** bin;
  8012. double* accumulation;
  8013. ma_uint32* counter;
  8014. } pink;
  8015. struct
  8016. {
  8017. double* accumulation;
  8018. } brownian;
  8019. } state;
  8020. /* Memory management. */
  8021. void* _pHeap;
  8022. ma_bool32 _ownsHeap;
  8023. } ma_noise;
  8024. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes);
  8025. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise);
  8026. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise);
  8027. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks);
  8028. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8029. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude);
  8030. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed);
  8031. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type);
  8032. #endif /* MA_NO_GENERATION */
  8033. /************************************************************************************************************************************************************
  8034. Resource Manager
  8035. ************************************************************************************************************************************************************/
  8036. /* The resource manager cannot be enabled if there is no decoder. */
  8037. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_NO_DECODING)
  8038. #define MA_NO_RESOURCE_MANAGER
  8039. #endif
  8040. #ifndef MA_NO_RESOURCE_MANAGER
  8041. typedef struct ma_resource_manager ma_resource_manager;
  8042. typedef struct ma_resource_manager_data_buffer_node ma_resource_manager_data_buffer_node;
  8043. typedef struct ma_resource_manager_data_buffer ma_resource_manager_data_buffer;
  8044. typedef struct ma_resource_manager_data_stream ma_resource_manager_data_stream;
  8045. typedef struct ma_resource_manager_data_source ma_resource_manager_data_source;
  8046. typedef enum
  8047. {
  8048. 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. */
  8049. 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. */
  8050. MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC = 0x00000004, /* When set, the resource manager will load the data source asynchronously. */
  8051. 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(). */
  8052. 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. */
  8053. } ma_resource_manager_data_source_flags;
  8054. /*
  8055. Pipeline notifications used by the resource manager. Made up of both an async notification and a fence, both of which are optional.
  8056. */
  8057. typedef struct
  8058. {
  8059. ma_async_notification* pNotification;
  8060. ma_fence* pFence;
  8061. } ma_resource_manager_pipeline_stage_notification;
  8062. typedef struct
  8063. {
  8064. ma_resource_manager_pipeline_stage_notification init; /* Initialization of the decoder. */
  8065. ma_resource_manager_pipeline_stage_notification done; /* Decoding fully completed. */
  8066. } ma_resource_manager_pipeline_notifications;
  8067. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void);
  8068. /* BEGIN BACKWARDS COMPATIBILITY */
  8069. /* TODO: Remove this block in version 0.12. */
  8070. #if 1
  8071. #define ma_resource_manager_job ma_job
  8072. #define ma_resource_manager_job_init ma_job_init
  8073. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_FLAG_NON_BLOCKING MA_JOB_QUEUE_FLAG_NON_BLOCKING
  8074. #define ma_resource_manager_job_queue_config ma_job_queue_config
  8075. #define ma_resource_manager_job_queue_config_init ma_job_queue_config_init
  8076. #define ma_resource_manager_job_queue ma_job_queue
  8077. #define ma_resource_manager_job_queue_get_heap_size ma_job_queue_get_heap_size
  8078. #define ma_resource_manager_job_queue_init_preallocated ma_job_queue_init_preallocated
  8079. #define ma_resource_manager_job_queue_init ma_job_queue_init
  8080. #define ma_resource_manager_job_queue_uninit ma_job_queue_uninit
  8081. #define ma_resource_manager_job_queue_post ma_job_queue_post
  8082. #define ma_resource_manager_job_queue_next ma_job_queue_next
  8083. #endif
  8084. /* END BACKWARDS COMPATIBILITY */
  8085. /* 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. */
  8086. #ifndef MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT
  8087. #define MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT 64
  8088. #endif
  8089. typedef enum
  8090. {
  8091. /* Indicates ma_resource_manager_next_job() should not block. Only valid when the job thread count is 0. */
  8092. MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING = 0x00000001,
  8093. /* Disables any kind of multithreading. Implicitly enables MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING. */
  8094. MA_RESOURCE_MANAGER_FLAG_NO_THREADING = 0x00000002
  8095. } ma_resource_manager_flags;
  8096. typedef struct
  8097. {
  8098. const char* pFilePath;
  8099. const wchar_t* pFilePathW;
  8100. const ma_resource_manager_pipeline_notifications* pNotifications;
  8101. ma_uint64 initialSeekPointInPCMFrames;
  8102. ma_uint64 rangeBegInPCMFrames;
  8103. ma_uint64 rangeEndInPCMFrames;
  8104. ma_uint64 loopPointBegInPCMFrames;
  8105. ma_uint64 loopPointEndInPCMFrames;
  8106. ma_bool32 isLooping;
  8107. ma_uint32 flags;
  8108. } ma_resource_manager_data_source_config;
  8109. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void);
  8110. typedef enum
  8111. {
  8112. ma_resource_manager_data_supply_type_unknown = 0, /* Used for determining whether or the data supply has been initialized. */
  8113. ma_resource_manager_data_supply_type_encoded, /* Data supply is an encoded buffer. Connector is ma_decoder. */
  8114. ma_resource_manager_data_supply_type_decoded, /* Data supply is a decoded buffer. Connector is ma_audio_buffer. */
  8115. ma_resource_manager_data_supply_type_decoded_paged /* Data supply is a linked list of decoded buffers. Connector is ma_paged_audio_buffer. */
  8116. } ma_resource_manager_data_supply_type;
  8117. typedef struct
  8118. {
  8119. MA_ATOMIC(4, ma_resource_manager_data_supply_type) type; /* Read and written from different threads so needs to be accessed atomically. */
  8120. union
  8121. {
  8122. struct
  8123. {
  8124. const void* pData;
  8125. size_t sizeInBytes;
  8126. } encoded;
  8127. struct
  8128. {
  8129. const void* pData;
  8130. ma_uint64 totalFrameCount;
  8131. ma_uint64 decodedFrameCount;
  8132. ma_format format;
  8133. ma_uint32 channels;
  8134. ma_uint32 sampleRate;
  8135. } decoded;
  8136. struct
  8137. {
  8138. ma_paged_audio_buffer_data data;
  8139. ma_uint64 decodedFrameCount;
  8140. ma_uint32 sampleRate;
  8141. } decodedPaged;
  8142. } backend;
  8143. } ma_resource_manager_data_supply;
  8144. struct ma_resource_manager_data_buffer_node
  8145. {
  8146. ma_uint32 hashedName32; /* The hashed name. This is the key. */
  8147. ma_uint32 refCount;
  8148. 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. */
  8149. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8150. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8151. 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_*()). */
  8152. ma_resource_manager_data_supply data;
  8153. ma_resource_manager_data_buffer_node* pParent;
  8154. ma_resource_manager_data_buffer_node* pChildLo;
  8155. ma_resource_manager_data_buffer_node* pChildHi;
  8156. };
  8157. struct ma_resource_manager_data_buffer
  8158. {
  8159. ma_data_source_base ds; /* Base data source. A data buffer is a data source. */
  8160. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this buffer. */
  8161. ma_resource_manager_data_buffer_node* pNode; /* The data node. This is reference counted and is what supplies the data. */
  8162. ma_uint32 flags; /* The flags that were passed used to initialize the buffer. */
  8163. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8164. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8165. ma_uint64 seekTargetInPCMFrames; /* Only updated by the public API. Never written nor read from the job thread. */
  8166. ma_bool32 seekToCursorOnNextRead; /* On the next read we need to seek to the frame cursor. */
  8167. 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. */
  8168. MA_ATOMIC(4, ma_bool32) isLooping; /* Can be read and written by different threads at the same time. Must be used atomically. */
  8169. ma_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. */
  8170. union
  8171. {
  8172. ma_decoder decoder; /* Supply type is ma_resource_manager_data_supply_type_encoded */
  8173. ma_audio_buffer buffer; /* Supply type is ma_resource_manager_data_supply_type_decoded */
  8174. ma_paged_audio_buffer pagedBuffer; /* Supply type is ma_resource_manager_data_supply_type_decoded_paged */
  8175. } connector; /* Connects this object to the node's data supply. */
  8176. };
  8177. struct ma_resource_manager_data_stream
  8178. {
  8179. ma_data_source_base ds; /* Base data source. A data stream is a data source. */
  8180. ma_resource_manager* pResourceManager; /* A pointer to the resource manager that owns this data stream. */
  8181. ma_uint32 flags; /* The flags that were passed used to initialize the stream. */
  8182. 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. */
  8183. ma_bool32 isDecoderInitialized; /* Required for determining whether or not the decoder should be uninitialized in MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM. */
  8184. ma_uint64 totalLengthInPCMFrames; /* This is calculated when first loaded by the MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM. */
  8185. ma_uint32 relativeCursor; /* The playback cursor, relative to the current page. Only ever accessed by the public API. Never accessed by the job thread. */
  8186. MA_ATOMIC(8, ma_uint64) absoluteCursor; /* The playback cursor, in absolute position starting from the start of the file. */
  8187. 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. */
  8188. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8189. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8190. /* Written by the public API, read by the job thread. */
  8191. 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. */
  8192. /* Written by the job thread, read by the public API. */
  8193. void* pPageData; /* Buffer containing the decoded data of each page. Allocated once at initialization time. */
  8194. MA_ATOMIC(4, ma_uint32) pageFrameCount[2]; /* The number of valid PCM frames in each page. Used to determine the last valid frame. */
  8195. /* Written and read by both the public API and the job thread. These must be atomic. */
  8196. 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. */
  8197. MA_ATOMIC(4, ma_bool32) isDecoderAtEnd; /* Whether or not the decoder has reached the end. */
  8198. 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. */
  8199. 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. */
  8200. };
  8201. struct ma_resource_manager_data_source
  8202. {
  8203. union
  8204. {
  8205. ma_resource_manager_data_buffer buffer;
  8206. ma_resource_manager_data_stream stream;
  8207. } backend; /* Must be the first item because we need the first item to be the data source callbacks for the buffer or stream. */
  8208. ma_uint32 flags; /* The flags that were passed in to ma_resource_manager_data_source_init(). */
  8209. MA_ATOMIC(4, ma_uint32) executionCounter; /* For allocating execution orders for jobs. */
  8210. MA_ATOMIC(4, ma_uint32) executionPointer; /* For managing the order of execution for asynchronous jobs relating to this object. Incremented as jobs complete processing. */
  8211. };
  8212. typedef struct
  8213. {
  8214. ma_allocation_callbacks allocationCallbacks;
  8215. ma_log* pLog;
  8216. ma_format decodedFormat; /* The decoded format to use. Set to ma_format_unknown (default) to use the file's native format. */
  8217. ma_uint32 decodedChannels; /* The decoded channel count to use. Set to 0 (default) to use the file's native channel count. */
  8218. ma_uint32 decodedSampleRate; /* the decoded sample rate to use. Set to 0 (default) to use the file's native sample rate. */
  8219. ma_uint32 jobThreadCount; /* Set to 0 if you want to self-manage your job threads. Defaults to 1. */
  8220. 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. */
  8221. ma_uint32 flags;
  8222. ma_vfs* pVFS; /* Can be NULL in which case defaults will be used. */
  8223. ma_decoding_backend_vtable** ppCustomDecodingBackendVTables;
  8224. ma_uint32 customDecodingBackendCount;
  8225. void* pCustomDecodingBackendUserData;
  8226. } ma_resource_manager_config;
  8227. MA_API ma_resource_manager_config ma_resource_manager_config_init(void);
  8228. struct ma_resource_manager
  8229. {
  8230. ma_resource_manager_config config;
  8231. ma_resource_manager_data_buffer_node* pRootDataBufferNode; /* The root buffer in the binary tree. */
  8232. #ifndef MA_NO_THREADING
  8233. ma_mutex dataBufferBSTLock; /* For synchronizing access to the data buffer binary tree. */
  8234. ma_thread jobThreads[MA_RESOURCE_MANAGER_MAX_JOB_THREAD_COUNT]; /* The threads for executing jobs. */
  8235. #endif
  8236. ma_job_queue jobQueue; /* Multi-consumer, multi-producer job queue for managing jobs for asynchronous decoding and streaming. */
  8237. ma_default_vfs defaultVFS; /* Only used if a custom VFS is not specified. */
  8238. ma_log log; /* Only used if no log was specified in the config. */
  8239. };
  8240. /* Init. */
  8241. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager);
  8242. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager);
  8243. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager);
  8244. /* Registration. */
  8245. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags);
  8246. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags);
  8247. 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. */
  8248. 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);
  8249. 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. */
  8250. 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);
  8251. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath);
  8252. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath);
  8253. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName);
  8254. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName);
  8255. /* Data Buffers. */
  8256. 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);
  8257. 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);
  8258. 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);
  8259. 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);
  8260. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer);
  8261. 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);
  8262. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex);
  8263. 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);
  8264. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor);
  8265. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength);
  8266. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer);
  8267. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping);
  8268. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer);
  8269. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames);
  8270. /* Data Streams. */
  8271. 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);
  8272. 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);
  8273. 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);
  8274. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream);
  8275. 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);
  8276. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex);
  8277. 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);
  8278. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor);
  8279. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength);
  8280. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream);
  8281. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping);
  8282. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream);
  8283. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames);
  8284. /* Data Sources. */
  8285. 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);
  8286. 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);
  8287. 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);
  8288. 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);
  8289. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource);
  8290. 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);
  8291. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex);
  8292. 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);
  8293. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor);
  8294. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength);
  8295. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource);
  8296. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping);
  8297. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource);
  8298. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames);
  8299. /* Job management. */
  8300. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob);
  8301. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager); /* Helper for posting a quit job. */
  8302. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob);
  8303. 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. */
  8304. 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. */
  8305. #endif /* MA_NO_RESOURCE_MANAGER */
  8306. /************************************************************************************************************************************************************
  8307. Node Graph
  8308. ************************************************************************************************************************************************************/
  8309. #ifndef MA_NO_NODE_GRAPH
  8310. /* Must never exceed 254. */
  8311. #ifndef MA_MAX_NODE_BUS_COUNT
  8312. #define MA_MAX_NODE_BUS_COUNT 254
  8313. #endif
  8314. /* Used internally by miniaudio for memory management. Must never exceed MA_MAX_NODE_BUS_COUNT. */
  8315. #ifndef MA_MAX_NODE_LOCAL_BUS_COUNT
  8316. #define MA_MAX_NODE_LOCAL_BUS_COUNT 2
  8317. #endif
  8318. /* Use this when the bus count is determined by the node instance rather than the vtable. */
  8319. #define MA_NODE_BUS_COUNT_UNKNOWN 255
  8320. typedef struct ma_node_graph ma_node_graph;
  8321. typedef void ma_node;
  8322. /* Node flags. */
  8323. typedef enum
  8324. {
  8325. MA_NODE_FLAG_PASSTHROUGH = 0x00000001,
  8326. MA_NODE_FLAG_CONTINUOUS_PROCESSING = 0x00000002,
  8327. MA_NODE_FLAG_ALLOW_NULL_INPUT = 0x00000004,
  8328. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES = 0x00000008,
  8329. MA_NODE_FLAG_SILENT_OUTPUT = 0x00000010
  8330. } ma_node_flags;
  8331. /* The playback state of a node. Either started or stopped. */
  8332. typedef enum
  8333. {
  8334. ma_node_state_started = 0,
  8335. ma_node_state_stopped = 1
  8336. } ma_node_state;
  8337. typedef struct
  8338. {
  8339. /*
  8340. Extended processing callback. This callback is used for effects that process input and output
  8341. at different rates (i.e. they perform resampling). This is similar to the simple version, only
  8342. they take two seperate frame counts: one for input, and one for output.
  8343. On input, `pFrameCountOut` is equal to the capacity of the output buffer for each bus, whereas
  8344. `pFrameCountIn` will be equal to the number of PCM frames in each of the buffers in `ppFramesIn`.
  8345. On output, set `pFrameCountOut` to the number of PCM frames that were actually output and set
  8346. `pFrameCountIn` to the number of input frames that were consumed.
  8347. */
  8348. void (* onProcess)(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut);
  8349. /*
  8350. A callback for retrieving the number of a input frames that are required to output the
  8351. specified number of output frames. You would only want to implement this when the node performs
  8352. resampling. This is optional, even for nodes that perform resampling, but it does offer a
  8353. small reduction in latency as it allows miniaudio to calculate the exact number of input frames
  8354. to read at a time instead of having to estimate.
  8355. */
  8356. ma_result (* onGetRequiredInputFrameCount)(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount);
  8357. /*
  8358. The number of input buses. This is how many sub-buffers will be contained in the `ppFramesIn`
  8359. parameters of the callbacks above.
  8360. */
  8361. ma_uint8 inputBusCount;
  8362. /*
  8363. The number of output buses. This is how many sub-buffers will be contained in the `ppFramesOut`
  8364. parameters of the callbacks above.
  8365. */
  8366. ma_uint8 outputBusCount;
  8367. /*
  8368. Flags describing characteristics of the node. This is currently just a placeholder for some
  8369. ideas for later on.
  8370. */
  8371. ma_uint32 flags;
  8372. } ma_node_vtable;
  8373. typedef struct
  8374. {
  8375. const ma_node_vtable* vtable; /* Should never be null. Initialization of the node will fail if so. */
  8376. ma_node_state initialState; /* Defaults to ma_node_state_started. */
  8377. 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). */
  8378. 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). */
  8379. 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`. */
  8380. 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`. */
  8381. } ma_node_config;
  8382. MA_API ma_node_config ma_node_config_init(void);
  8383. /*
  8384. A node has multiple output buses. An output bus is attached to an input bus as an item in a linked
  8385. list. Think of the input bus as a linked list, with the output bus being an item in that list.
  8386. */
  8387. typedef struct ma_node_output_bus ma_node_output_bus;
  8388. struct ma_node_output_bus
  8389. {
  8390. /* Immutable. */
  8391. ma_node* pNode; /* The node that owns this output bus. The input node. Will be null for dummy head and tail nodes. */
  8392. ma_uint8 outputBusIndex; /* The index of the output bus on pNode that this output bus represents. */
  8393. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8394. /* Mutable via multiple threads. Must be used atomically. The weird ordering here is for packing reasons. */
  8395. MA_ATOMIC(1, ma_uint8) inputNodeInputBusIndex; /* The index of the input bus on the input. Required for detaching. */
  8396. 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_*. */
  8397. MA_ATOMIC(4, ma_uint32) refCount; /* Reference count for some thread-safety when detaching. */
  8398. 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. */
  8399. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8400. MA_ATOMIC(4, float) volume; /* Linear. */
  8401. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pNext; /* If null, it's the tail node or detached. */
  8402. MA_ATOMIC(MA_SIZEOF_PTR, ma_node_output_bus*) pPrev; /* If null, it's the head node or detached. */
  8403. MA_ATOMIC(MA_SIZEOF_PTR, ma_node*) pInputNode; /* The node that this output bus is attached to. Required for detaching. */
  8404. };
  8405. /*
  8406. A node has multiple input buses. The output buses of a node are connecting to the input busses of
  8407. another. An input bus is essentially just a linked list of output buses.
  8408. */
  8409. typedef struct ma_node_input_bus ma_node_input_bus;
  8410. struct ma_node_input_bus
  8411. {
  8412. /* Mutable via multiple threads. */
  8413. ma_node_output_bus head; /* Dummy head node for simplifying some lock-free thread-safety stuff. */
  8414. 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. */
  8415. MA_ATOMIC(4, ma_spinlock) lock; /* Unfortunate lock, but significantly simplifies the implementation. Required for thread-safe attaching and detaching. */
  8416. /* Set once at startup. */
  8417. ma_uint8 channels; /* The number of channels in the audio stream for this bus. */
  8418. };
  8419. typedef struct ma_node_base ma_node_base;
  8420. struct ma_node_base
  8421. {
  8422. /* These variables are set once at startup. */
  8423. ma_node_graph* pNodeGraph; /* The graph this node belongs to. */
  8424. const ma_node_vtable* vtable;
  8425. 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. */
  8426. ma_uint16 cachedDataCapInFramesPerBus; /* The capacity of the input data cache in frames, per bus. */
  8427. /* These variables are read and written only from the audio thread. */
  8428. ma_uint16 cachedFrameCountOut;
  8429. ma_uint16 cachedFrameCountIn;
  8430. ma_uint16 consumedFrameCountIn;
  8431. /* These variables are read and written between different threads. */
  8432. MA_ATOMIC(4, ma_node_state) state; /* When set to stopped, nothing will be read, regardless of the times in stateTimes. */
  8433. 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. */
  8434. 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()`. */
  8435. ma_uint32 inputBusCount;
  8436. ma_uint32 outputBusCount;
  8437. ma_node_input_bus* pInputBuses;
  8438. ma_node_output_bus* pOutputBuses;
  8439. /* Memory management. */
  8440. ma_node_input_bus _inputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8441. ma_node_output_bus _outputBuses[MA_MAX_NODE_LOCAL_BUS_COUNT];
  8442. 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. */
  8443. ma_bool32 _ownsHeap; /* If set to true, the node owns the heap allocation and _pHeap will be freed in ma_node_uninit(). */
  8444. };
  8445. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes);
  8446. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode);
  8447. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode);
  8448. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8449. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode);
  8450. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode);
  8451. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode);
  8452. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex);
  8453. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex);
  8454. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex);
  8455. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex);
  8456. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode);
  8457. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume);
  8458. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex);
  8459. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state);
  8460. MA_API ma_node_state ma_node_get_state(const ma_node* pNode);
  8461. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime);
  8462. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state);
  8463. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime);
  8464. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd);
  8465. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode);
  8466. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime);
  8467. typedef struct
  8468. {
  8469. ma_uint32 channels;
  8470. ma_uint16 nodeCacheCapInFrames;
  8471. } ma_node_graph_config;
  8472. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels);
  8473. struct ma_node_graph
  8474. {
  8475. /* Immutable. */
  8476. 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. */
  8477. 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(). */
  8478. ma_uint16 nodeCacheCapInFrames;
  8479. /* Read and written by multiple threads. */
  8480. MA_ATOMIC(4, ma_bool32) isReading;
  8481. };
  8482. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph);
  8483. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks);
  8484. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph);
  8485. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8486. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph);
  8487. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph);
  8488. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime);
  8489. /* Data source node. 0 input buses, 1 output bus. Used for reading from a data source. */
  8490. typedef struct
  8491. {
  8492. ma_node_config nodeConfig;
  8493. ma_data_source* pDataSource;
  8494. } ma_data_source_node_config;
  8495. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource);
  8496. typedef struct
  8497. {
  8498. ma_node_base base;
  8499. ma_data_source* pDataSource;
  8500. } ma_data_source_node;
  8501. 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);
  8502. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8503. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping);
  8504. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode);
  8505. /* Splitter Node. 1 input, 2 outputs. Used for splitting/copying a stream so it can be as input into two separate output nodes. */
  8506. typedef struct
  8507. {
  8508. ma_node_config nodeConfig;
  8509. ma_uint32 channels;
  8510. ma_uint32 outputBusCount;
  8511. } ma_splitter_node_config;
  8512. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels);
  8513. typedef struct
  8514. {
  8515. ma_node_base base;
  8516. } ma_splitter_node;
  8517. 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);
  8518. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8519. /*
  8520. Biquad Node
  8521. */
  8522. typedef struct
  8523. {
  8524. ma_node_config nodeConfig;
  8525. ma_biquad_config biquad;
  8526. } ma_biquad_node_config;
  8527. 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);
  8528. typedef struct
  8529. {
  8530. ma_node_base baseNode;
  8531. ma_biquad biquad;
  8532. } ma_biquad_node;
  8533. 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);
  8534. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode);
  8535. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8536. /*
  8537. Low Pass Filter Node
  8538. */
  8539. typedef struct
  8540. {
  8541. ma_node_config nodeConfig;
  8542. ma_lpf_config lpf;
  8543. } ma_lpf_node_config;
  8544. MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8545. typedef struct
  8546. {
  8547. ma_node_base baseNode;
  8548. ma_lpf lpf;
  8549. } ma_lpf_node;
  8550. 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);
  8551. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode);
  8552. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8553. /*
  8554. High Pass Filter Node
  8555. */
  8556. typedef struct
  8557. {
  8558. ma_node_config nodeConfig;
  8559. ma_hpf_config hpf;
  8560. } ma_hpf_node_config;
  8561. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8562. typedef struct
  8563. {
  8564. ma_node_base baseNode;
  8565. ma_hpf hpf;
  8566. } ma_hpf_node;
  8567. 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);
  8568. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode);
  8569. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8570. /*
  8571. Band Pass Filter Node
  8572. */
  8573. typedef struct
  8574. {
  8575. ma_node_config nodeConfig;
  8576. ma_bpf_config bpf;
  8577. } ma_bpf_node_config;
  8578. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order);
  8579. typedef struct
  8580. {
  8581. ma_node_base baseNode;
  8582. ma_bpf bpf;
  8583. } ma_bpf_node;
  8584. 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);
  8585. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode);
  8586. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8587. /*
  8588. Notching Filter Node
  8589. */
  8590. typedef struct
  8591. {
  8592. ma_node_config nodeConfig;
  8593. ma_notch_config notch;
  8594. } ma_notch_node_config;
  8595. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency);
  8596. typedef struct
  8597. {
  8598. ma_node_base baseNode;
  8599. ma_notch2 notch;
  8600. } ma_notch_node;
  8601. 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);
  8602. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode);
  8603. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8604. /*
  8605. Peaking Filter Node
  8606. */
  8607. typedef struct
  8608. {
  8609. ma_node_config nodeConfig;
  8610. ma_peak_config peak;
  8611. } ma_peak_node_config;
  8612. MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8613. typedef struct
  8614. {
  8615. ma_node_base baseNode;
  8616. ma_peak2 peak;
  8617. } ma_peak_node;
  8618. 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);
  8619. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode);
  8620. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8621. /*
  8622. Low Shelf Filter Node
  8623. */
  8624. typedef struct
  8625. {
  8626. ma_node_config nodeConfig;
  8627. ma_loshelf_config loshelf;
  8628. } ma_loshelf_node_config;
  8629. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8630. typedef struct
  8631. {
  8632. ma_node_base baseNode;
  8633. ma_loshelf2 loshelf;
  8634. } ma_loshelf_node;
  8635. 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);
  8636. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode);
  8637. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8638. /*
  8639. High Shelf Filter Node
  8640. */
  8641. typedef struct
  8642. {
  8643. ma_node_config nodeConfig;
  8644. ma_hishelf_config hishelf;
  8645. } ma_hishelf_node_config;
  8646. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency);
  8647. typedef struct
  8648. {
  8649. ma_node_base baseNode;
  8650. ma_hishelf2 hishelf;
  8651. } ma_hishelf_node;
  8652. 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);
  8653. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode);
  8654. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8655. typedef struct
  8656. {
  8657. ma_node_config nodeConfig;
  8658. ma_delay_config delay;
  8659. } ma_delay_node_config;
  8660. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay);
  8661. typedef struct
  8662. {
  8663. ma_node_base baseNode;
  8664. ma_delay delay;
  8665. } ma_delay_node;
  8666. 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);
  8667. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8668. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value);
  8669. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode);
  8670. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value);
  8671. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode);
  8672. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value);
  8673. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode);
  8674. #endif /* MA_NO_NODE_GRAPH */
  8675. /* SECTION: miniaudio_engine.h */
  8676. /************************************************************************************************************************************************************
  8677. Engine
  8678. ************************************************************************************************************************************************************/
  8679. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  8680. typedef struct ma_engine ma_engine;
  8681. typedef struct ma_sound ma_sound;
  8682. /* Sound flags. */
  8683. typedef enum
  8684. {
  8685. MA_SOUND_FLAG_STREAM = 0x00000001, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM */
  8686. MA_SOUND_FLAG_DECODE = 0x00000002, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE */
  8687. MA_SOUND_FLAG_ASYNC = 0x00000004, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC */
  8688. MA_SOUND_FLAG_WAIT_INIT = 0x00000008, /* MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT */
  8689. MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT = 0x00000010, /* Do not attach to the endpoint by default. Useful for when setting up nodes in a complex graph system. */
  8690. MA_SOUND_FLAG_NO_PITCH = 0x00000020, /* Disable pitch shifting with ma_sound_set_pitch() and ma_sound_group_set_pitch(). This is an optimization. */
  8691. MA_SOUND_FLAG_NO_SPATIALIZATION = 0x00000040 /* Disable spatialization. */
  8692. } ma_sound_flags;
  8693. #ifndef MA_ENGINE_MAX_LISTENERS
  8694. #define MA_ENGINE_MAX_LISTENERS 4
  8695. #endif
  8696. #define MA_LISTENER_INDEX_CLOSEST ((ma_uint8)-1)
  8697. typedef enum
  8698. {
  8699. ma_engine_node_type_sound,
  8700. ma_engine_node_type_group
  8701. } ma_engine_node_type;
  8702. typedef struct
  8703. {
  8704. ma_engine* pEngine;
  8705. ma_engine_node_type type;
  8706. ma_uint32 channelsIn;
  8707. ma_uint32 channelsOut;
  8708. ma_uint32 sampleRate; /* Only used when the type is set to ma_engine_node_type_sound. */
  8709. ma_mono_expansion_mode monoExpansionMode;
  8710. ma_bool8 isPitchDisabled; /* Pitching can be explicitly disable with MA_SOUND_FLAG_NO_PITCH to optimize processing. */
  8711. ma_bool8 isSpatializationDisabled; /* Spatialization can be explicitly disabled with MA_SOUND_FLAG_NO_SPATIALIZATION. */
  8712. 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. */
  8713. } ma_engine_node_config;
  8714. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags);
  8715. /* Base node object for both ma_sound and ma_sound_group. */
  8716. typedef struct
  8717. {
  8718. ma_node_base baseNode; /* Must be the first member for compatiblity with the ma_node API. */
  8719. ma_engine* pEngine; /* A pointer to the engine. Set based on the value from the config. */
  8720. 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. */
  8721. ma_mono_expansion_mode monoExpansionMode;
  8722. ma_fader fader;
  8723. ma_linear_resampler resampler; /* For pitch shift. */
  8724. ma_spatializer spatializer;
  8725. ma_panner panner;
  8726. MA_ATOMIC(4, float) pitch;
  8727. 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. */
  8728. float oldDopplerPitch; /* For determining whether or not the resampler needs to be updated to take a new doppler pitch into account. */
  8729. 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. */
  8730. MA_ATOMIC(4, ma_bool32) isSpatializationDisabled; /* Set to false by default. When set to false, will not have spatialisation applied. */
  8731. 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. */
  8732. /* Memory management. */
  8733. ma_bool8 _ownsHeap;
  8734. void* _pHeap;
  8735. } ma_engine_node;
  8736. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes);
  8737. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode);
  8738. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode);
  8739. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks);
  8740. #define MA_SOUND_SOURCE_CHANNEL_COUNT 0xFFFFFFFF
  8741. typedef struct
  8742. {
  8743. const char* pFilePath; /* Set this to load from the resource manager. */
  8744. const wchar_t* pFilePathW; /* Set this to load from the resource manager. */
  8745. ma_data_source* pDataSource; /* Set this to load from an existing data source. */
  8746. 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`. */
  8747. ma_uint32 initialAttachmentInputBusIndex; /* The index of the input bus of pInitialAttachment to attach the sound to. */
  8748. 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. */
  8749. 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). */
  8750. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  8751. ma_uint32 flags; /* A combination of MA_SOUND_FLAG_* flags. */
  8752. ma_uint64 initialSeekPointInPCMFrames; /* Initializes the sound such that it's seeked to this location by default. */
  8753. ma_uint64 rangeBegInPCMFrames;
  8754. ma_uint64 rangeEndInPCMFrames;
  8755. ma_uint64 loopPointBegInPCMFrames;
  8756. ma_uint64 loopPointEndInPCMFrames;
  8757. ma_bool32 isLooping;
  8758. ma_fence* pDoneFence; /* Released when the resource manager has finished decoding the entire sound. Not used with streams. */
  8759. } ma_sound_config;
  8760. MA_API ma_sound_config ma_sound_config_init(void); /* Deprecated. Will be removed in version 0.12. Use ma_sound_config_2() instead. */
  8761. 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. */
  8762. struct ma_sound
  8763. {
  8764. ma_engine_node engineNode; /* Must be the first member for compatibility with the ma_node API. */
  8765. ma_data_source* pDataSource;
  8766. 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. */
  8767. MA_ATOMIC(4, ma_bool32) atEnd;
  8768. ma_bool8 ownsDataSource;
  8769. /*
  8770. We're declaring a resource manager data source object here to save us a malloc when loading a
  8771. sound via the resource manager, which I *think* will be the most common scenario.
  8772. */
  8773. #ifndef MA_NO_RESOURCE_MANAGER
  8774. ma_resource_manager_data_source* pResourceManagerDataSource;
  8775. #endif
  8776. };
  8777. /* Structure specifically for sounds played with ma_engine_play_sound(). Making this a separate structure to reduce overhead. */
  8778. typedef struct ma_sound_inlined ma_sound_inlined;
  8779. struct ma_sound_inlined
  8780. {
  8781. ma_sound sound;
  8782. ma_sound_inlined* pNext;
  8783. ma_sound_inlined* pPrev;
  8784. };
  8785. /* A sound group is just a sound. */
  8786. typedef ma_sound_config ma_sound_group_config;
  8787. typedef ma_sound ma_sound_group;
  8788. 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. */
  8789. 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. */
  8790. typedef struct
  8791. {
  8792. #if !defined(MA_NO_RESOURCE_MANAGER)
  8793. ma_resource_manager* pResourceManager; /* Can be null in which case a resource manager will be created for you. */
  8794. #endif
  8795. #if !defined(MA_NO_DEVICE_IO)
  8796. ma_context* pContext;
  8797. ma_device* pDevice; /* If set, the caller is responsible for calling ma_engine_data_callback() in the device's data callback. */
  8798. ma_device_id* pPlaybackDeviceID; /* The ID of the playback device to use with the default listener. */
  8799. ma_device_notification_proc notificationCallback;
  8800. #endif
  8801. ma_log* pLog; /* When set to NULL, will use the context's log. */
  8802. ma_uint32 listenerCount; /* Must be between 1 and MA_ENGINE_MAX_LISTENERS. */
  8803. 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. */
  8804. ma_uint32 sampleRate; /* The sample rate. When set to 0 will use the native channel count of the device. */
  8805. 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.*/
  8806. ma_uint32 periodSizeInMilliseconds; /* Used if periodSizeInFrames is unset. */
  8807. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. If set to 0, will use gainSmoothTimeInMilliseconds. */
  8808. ma_uint32 gainSmoothTimeInMilliseconds; /* When set to 0, gainSmoothTimeInFrames will be used. If both are set to 0, a default value will be used. */
  8809. ma_allocation_callbacks allocationCallbacks;
  8810. 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(). */
  8811. 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. */
  8812. ma_mono_expansion_mode monoExpansionMode; /* Controls how the mono channel should be expanded to other channels when spatialization is disabled on a sound. */
  8813. 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. */
  8814. } ma_engine_config;
  8815. MA_API ma_engine_config ma_engine_config_init(void);
  8816. struct ma_engine
  8817. {
  8818. 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. */
  8819. #if !defined(MA_NO_RESOURCE_MANAGER)
  8820. ma_resource_manager* pResourceManager;
  8821. #endif
  8822. #if !defined(MA_NO_DEVICE_IO)
  8823. ma_device* pDevice; /* Optionally set via the config, otherwise allocated by the engine in ma_engine_init(). */
  8824. #endif
  8825. ma_log* pLog;
  8826. ma_uint32 sampleRate;
  8827. ma_uint32 listenerCount;
  8828. ma_spatializer_listener listeners[MA_ENGINE_MAX_LISTENERS];
  8829. ma_allocation_callbacks allocationCallbacks;
  8830. ma_bool8 ownsResourceManager;
  8831. ma_bool8 ownsDevice;
  8832. ma_spinlock inlinedSoundLock; /* For synchronizing access so the inlined sound list. */
  8833. ma_sound_inlined* pInlinedSoundHead; /* The first inlined sound. Inlined sounds are tracked in a linked list. */
  8834. MA_ATOMIC(4, ma_uint32) inlinedSoundCount; /* The total number of allocated inlined sound objects. Used for debugging. */
  8835. ma_uint32 gainSmoothTimeInFrames; /* The number of frames to interpolate the gain of spatialized sounds across. */
  8836. ma_mono_expansion_mode monoExpansionMode;
  8837. };
  8838. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine);
  8839. MA_API void ma_engine_uninit(ma_engine* pEngine);
  8840. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  8841. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine);
  8842. #if !defined(MA_NO_RESOURCE_MANAGER)
  8843. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine);
  8844. #endif
  8845. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine);
  8846. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine);
  8847. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine);
  8848. MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine);
  8849. MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime);
  8850. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine);
  8851. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine);
  8852. MA_API ma_result ma_engine_start(ma_engine* pEngine);
  8853. MA_API ma_result ma_engine_stop(ma_engine* pEngine);
  8854. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume);
  8855. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB);
  8856. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine);
  8857. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ);
  8858. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  8859. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex);
  8860. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  8861. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex);
  8862. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  8863. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex);
  8864. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  8865. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  8866. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z);
  8867. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex);
  8868. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled);
  8869. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex);
  8870. #ifndef MA_NO_RESOURCE_MANAGER
  8871. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex);
  8872. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup); /* Fire and forget. */
  8873. #endif
  8874. #ifndef MA_NO_RESOURCE_MANAGER
  8875. 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);
  8876. 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);
  8877. 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);
  8878. #endif
  8879. 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);
  8880. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound);
  8881. MA_API void ma_sound_uninit(ma_sound* pSound);
  8882. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound);
  8883. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound);
  8884. MA_API ma_result ma_sound_start(ma_sound* pSound);
  8885. MA_API ma_result ma_sound_stop(ma_sound* pSound);
  8886. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume);
  8887. MA_API float ma_sound_get_volume(const ma_sound* pSound);
  8888. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan);
  8889. MA_API float ma_sound_get_pan(const ma_sound* pSound);
  8890. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode);
  8891. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound);
  8892. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch);
  8893. MA_API float ma_sound_get_pitch(const ma_sound* pSound);
  8894. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled);
  8895. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound);
  8896. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex);
  8897. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound);
  8898. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound);
  8899. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound);
  8900. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z);
  8901. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound);
  8902. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z);
  8903. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound);
  8904. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z);
  8905. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound);
  8906. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel);
  8907. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound);
  8908. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning);
  8909. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound);
  8910. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff);
  8911. MA_API float ma_sound_get_rolloff(const ma_sound* pSound);
  8912. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain);
  8913. MA_API float ma_sound_get_min_gain(const ma_sound* pSound);
  8914. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain);
  8915. MA_API float ma_sound_get_max_gain(const ma_sound* pSound);
  8916. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance);
  8917. MA_API float ma_sound_get_min_distance(const ma_sound* pSound);
  8918. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance);
  8919. MA_API float ma_sound_get_max_distance(const ma_sound* pSound);
  8920. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  8921. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  8922. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor);
  8923. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound);
  8924. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor);
  8925. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound);
  8926. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  8927. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  8928. MA_API float ma_sound_get_current_fade_volume(ma_sound* pSound);
  8929. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  8930. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  8931. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames);
  8932. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds);
  8933. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound);
  8934. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound);
  8935. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping);
  8936. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound);
  8937. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound);
  8938. 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(). */
  8939. 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);
  8940. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor);
  8941. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength);
  8942. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor);
  8943. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength);
  8944. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup);
  8945. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup);
  8946. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup);
  8947. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup);
  8948. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup);
  8949. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup);
  8950. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume);
  8951. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup);
  8952. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan);
  8953. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup);
  8954. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode);
  8955. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup);
  8956. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch);
  8957. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup);
  8958. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled);
  8959. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup);
  8960. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex);
  8961. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup);
  8962. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup);
  8963. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup);
  8964. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z);
  8965. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup);
  8966. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z);
  8967. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup);
  8968. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z);
  8969. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup);
  8970. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel);
  8971. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup);
  8972. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning);
  8973. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup);
  8974. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff);
  8975. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup);
  8976. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain);
  8977. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup);
  8978. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain);
  8979. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup);
  8980. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance);
  8981. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup);
  8982. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance);
  8983. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup);
  8984. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain);
  8985. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain);
  8986. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor);
  8987. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup);
  8988. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor);
  8989. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup);
  8990. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames);
  8991. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds);
  8992. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup);
  8993. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  8994. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  8995. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames);
  8996. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds);
  8997. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup);
  8998. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup);
  8999. #endif /* MA_NO_ENGINE */
  9000. /* END SECTION: miniaudio_engine.h */
  9001. #ifdef __cplusplus
  9002. }
  9003. #endif
  9004. #endif /* miniaudio_h */
  9005. /*
  9006. This is for preventing greying out of the implementation section.
  9007. */
  9008. #if defined(Q_CREATOR_RUN) || defined(__INTELLISENSE__) || defined(__CDT_PARSER__)
  9009. #define MINIAUDIO_IMPLEMENTATION
  9010. #endif
  9011. /************************************************************************************************************************************************************
  9012. *************************************************************************************************************************************************************
  9013. IMPLEMENTATION
  9014. *************************************************************************************************************************************************************
  9015. ************************************************************************************************************************************************************/
  9016. #if defined(MINIAUDIO_IMPLEMENTATION) || defined(MA_IMPLEMENTATION)
  9017. #ifndef miniaudio_c
  9018. #define miniaudio_c
  9019. #include <assert.h>
  9020. #include <limits.h> /* For INT_MAX */
  9021. #include <math.h> /* sin(), etc. */
  9022. #include <stdarg.h>
  9023. #include <stdio.h>
  9024. #if !defined(_MSC_VER) && !defined(__DMC__)
  9025. #include <strings.h> /* For strcasecmp(). */
  9026. #include <wchar.h> /* For wcslen(), wcsrtombs() */
  9027. #endif
  9028. #ifdef _MSC_VER
  9029. #include <float.h> /* For _controlfp_s constants */
  9030. #endif
  9031. #ifdef MA_WIN32
  9032. #include <windows.h>
  9033. #else
  9034. #include <stdlib.h> /* For malloc(), free(), wcstombs(). */
  9035. #include <string.h> /* For memset() */
  9036. #include <sched.h>
  9037. #include <sys/time.h> /* select() (used for ma_sleep()). */
  9038. #include <pthread.h>
  9039. #endif
  9040. #include <sys/stat.h> /* For fstat(), etc. */
  9041. #ifdef MA_EMSCRIPTEN
  9042. #include <emscripten/emscripten.h>
  9043. #endif
  9044. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9045. #ifdef _WIN32
  9046. #ifdef _WIN64
  9047. #define MA_64BIT
  9048. #else
  9049. #define MA_32BIT
  9050. #endif
  9051. #endif
  9052. #endif
  9053. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9054. #ifdef __GNUC__
  9055. #ifdef __LP64__
  9056. #define MA_64BIT
  9057. #else
  9058. #define MA_32BIT
  9059. #endif
  9060. #endif
  9061. #endif
  9062. #if !defined(MA_64BIT) && !defined(MA_32BIT)
  9063. #include <stdint.h>
  9064. #if INTPTR_MAX == INT64_MAX
  9065. #define MA_64BIT
  9066. #else
  9067. #define MA_32BIT
  9068. #endif
  9069. #endif
  9070. /* Architecture Detection */
  9071. #if defined(__x86_64__) || defined(_M_X64)
  9072. #define MA_X64
  9073. #elif defined(__i386) || defined(_M_IX86)
  9074. #define MA_X86
  9075. #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  9076. #define MA_ARM
  9077. #endif
  9078. /* Intrinsics Support */
  9079. #if defined(MA_X64) || defined(MA_X86)
  9080. #if defined(_MSC_VER) && !defined(__clang__)
  9081. /* MSVC. */
  9082. #if _MSC_VER >= 1400 && !defined(MA_NO_SSE2) /* 2005 */
  9083. #define MA_SUPPORT_SSE2
  9084. #endif
  9085. /*#if _MSC_VER >= 1600 && !defined(MA_NO_AVX)*/ /* 2010 */
  9086. /* #define MA_SUPPORT_AVX*/
  9087. /*#endif*/
  9088. #if _MSC_VER >= 1700 && !defined(MA_NO_AVX2) /* 2012 */
  9089. #define MA_SUPPORT_AVX2
  9090. #endif
  9091. #else
  9092. /* Assume GNUC-style. */
  9093. #if defined(__SSE2__) && !defined(MA_NO_SSE2)
  9094. #define MA_SUPPORT_SSE2
  9095. #endif
  9096. /*#if defined(__AVX__) && !defined(MA_NO_AVX)*/
  9097. /* #define MA_SUPPORT_AVX*/
  9098. /*#endif*/
  9099. #if defined(__AVX2__) && !defined(MA_NO_AVX2)
  9100. #define MA_SUPPORT_AVX2
  9101. #endif
  9102. #endif
  9103. /* If at this point we still haven't determined compiler support for the intrinsics just fall back to __has_include. */
  9104. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  9105. #if !defined(MA_SUPPORT_SSE2) && !defined(MA_NO_SSE2) && __has_include(<emmintrin.h>)
  9106. #define MA_SUPPORT_SSE2
  9107. #endif
  9108. /*#if !defined(MA_SUPPORT_AVX) && !defined(MA_NO_AVX) && __has_include(<immintrin.h>)*/
  9109. /* #define MA_SUPPORT_AVX*/
  9110. /*#endif*/
  9111. #if !defined(MA_SUPPORT_AVX2) && !defined(MA_NO_AVX2) && __has_include(<immintrin.h>)
  9112. #define MA_SUPPORT_AVX2
  9113. #endif
  9114. #endif
  9115. #if defined(MA_SUPPORT_AVX2) || defined(MA_SUPPORT_AVX)
  9116. #include <immintrin.h>
  9117. #elif defined(MA_SUPPORT_SSE2)
  9118. #include <emmintrin.h>
  9119. #endif
  9120. #endif
  9121. #if defined(MA_ARM)
  9122. #if !defined(MA_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9123. #define MA_SUPPORT_NEON
  9124. #include <arm_neon.h>
  9125. #endif
  9126. #endif
  9127. /* Begin globally disabled warnings. */
  9128. #if defined(_MSC_VER)
  9129. #pragma warning(push)
  9130. #pragma warning(disable:4752) /* found Intel(R) Advanced Vector Extensions; consider using /arch:AVX */
  9131. #pragma warning(disable:4049) /* compiler limit : terminating line number emission */
  9132. #endif
  9133. #if defined(MA_X64) || defined(MA_X86)
  9134. #if defined(_MSC_VER) && !defined(__clang__)
  9135. #if _MSC_VER >= 1400
  9136. #include <intrin.h>
  9137. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9138. {
  9139. __cpuid(info, fid);
  9140. }
  9141. #else
  9142. #define MA_NO_CPUID
  9143. #endif
  9144. #if _MSC_VER >= 1600 && (defined(_MSC_FULL_VER) && _MSC_FULL_VER >= 160040219)
  9145. static MA_INLINE unsigned __int64 ma_xgetbv(int reg)
  9146. {
  9147. return _xgetbv(reg);
  9148. }
  9149. #else
  9150. #define MA_NO_XGETBV
  9151. #endif
  9152. #elif (defined(__GNUC__) || defined(__clang__)) && !defined(MA_ANDROID)
  9153. static MA_INLINE void ma_cpuid(int info[4], int fid)
  9154. {
  9155. /*
  9156. 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
  9157. 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
  9158. supporting different assembly dialects.
  9159. What's basically happening is that we're saving and restoring the ebx register manually.
  9160. */
  9161. #if defined(DRFLAC_X86) && defined(__PIC__)
  9162. __asm__ __volatile__ (
  9163. "xchg{l} {%%}ebx, %k1;"
  9164. "cpuid;"
  9165. "xchg{l} {%%}ebx, %k1;"
  9166. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9167. );
  9168. #else
  9169. __asm__ __volatile__ (
  9170. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  9171. );
  9172. #endif
  9173. }
  9174. static MA_INLINE ma_uint64 ma_xgetbv(int reg)
  9175. {
  9176. unsigned int hi;
  9177. unsigned int lo;
  9178. __asm__ __volatile__ (
  9179. "xgetbv" : "=a"(lo), "=d"(hi) : "c"(reg)
  9180. );
  9181. return ((ma_uint64)hi << 32) | (ma_uint64)lo;
  9182. }
  9183. #else
  9184. #define MA_NO_CPUID
  9185. #define MA_NO_XGETBV
  9186. #endif
  9187. #else
  9188. #define MA_NO_CPUID
  9189. #define MA_NO_XGETBV
  9190. #endif
  9191. static MA_INLINE ma_bool32 ma_has_sse2(void)
  9192. {
  9193. #if defined(MA_SUPPORT_SSE2)
  9194. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_SSE2)
  9195. #if defined(MA_X64)
  9196. return MA_TRUE; /* 64-bit targets always support SSE2. */
  9197. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  9198. return MA_TRUE; /* If the compiler is allowed to freely generate SSE2 code we can assume support. */
  9199. #else
  9200. #if defined(MA_NO_CPUID)
  9201. return MA_FALSE;
  9202. #else
  9203. int info[4];
  9204. ma_cpuid(info, 1);
  9205. return (info[3] & (1 << 26)) != 0;
  9206. #endif
  9207. #endif
  9208. #else
  9209. return MA_FALSE; /* SSE2 is only supported on x86 and x64 architectures. */
  9210. #endif
  9211. #else
  9212. return MA_FALSE; /* No compiler support. */
  9213. #endif
  9214. }
  9215. #if 0
  9216. static MA_INLINE ma_bool32 ma_has_avx()
  9217. {
  9218. #if defined(MA_SUPPORT_AVX)
  9219. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX)
  9220. #if defined(_AVX_) || defined(__AVX__)
  9221. return MA_TRUE; /* If the compiler is allowed to freely generate AVX code we can assume support. */
  9222. #else
  9223. /* AVX requires both CPU and OS support. */
  9224. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9225. return MA_FALSE;
  9226. #else
  9227. int info[4];
  9228. ma_cpuid(info, 1);
  9229. if (((info[2] & (1 << 27)) != 0) && ((info[2] & (1 << 28)) != 0)) {
  9230. ma_uint64 xrc = ma_xgetbv(0);
  9231. if ((xrc & 0x06) == 0x06) {
  9232. return MA_TRUE;
  9233. } else {
  9234. return MA_FALSE;
  9235. }
  9236. } else {
  9237. return MA_FALSE;
  9238. }
  9239. #endif
  9240. #endif
  9241. #else
  9242. return MA_FALSE; /* AVX is only supported on x86 and x64 architectures. */
  9243. #endif
  9244. #else
  9245. return MA_FALSE; /* No compiler support. */
  9246. #endif
  9247. }
  9248. #endif
  9249. static MA_INLINE ma_bool32 ma_has_avx2(void)
  9250. {
  9251. #if defined(MA_SUPPORT_AVX2)
  9252. #if (defined(MA_X64) || defined(MA_X86)) && !defined(MA_NO_AVX2)
  9253. #if defined(_AVX2_) || defined(__AVX2__)
  9254. return MA_TRUE; /* If the compiler is allowed to freely generate AVX2 code we can assume support. */
  9255. #else
  9256. /* AVX2 requires both CPU and OS support. */
  9257. #if defined(MA_NO_CPUID) || defined(MA_NO_XGETBV)
  9258. return MA_FALSE;
  9259. #else
  9260. int info1[4];
  9261. int info7[4];
  9262. ma_cpuid(info1, 1);
  9263. ma_cpuid(info7, 7);
  9264. if (((info1[2] & (1 << 27)) != 0) && ((info7[1] & (1 << 5)) != 0)) {
  9265. ma_uint64 xrc = ma_xgetbv(0);
  9266. if ((xrc & 0x06) == 0x06) {
  9267. return MA_TRUE;
  9268. } else {
  9269. return MA_FALSE;
  9270. }
  9271. } else {
  9272. return MA_FALSE;
  9273. }
  9274. #endif
  9275. #endif
  9276. #else
  9277. return MA_FALSE; /* AVX2 is only supported on x86 and x64 architectures. */
  9278. #endif
  9279. #else
  9280. return MA_FALSE; /* No compiler support. */
  9281. #endif
  9282. }
  9283. static MA_INLINE ma_bool32 ma_has_neon(void)
  9284. {
  9285. #if defined(MA_SUPPORT_NEON)
  9286. #if defined(MA_ARM) && !defined(MA_NO_NEON)
  9287. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  9288. return MA_TRUE; /* If the compiler is allowed to freely generate NEON code we can assume support. */
  9289. #else
  9290. /* TODO: Runtime check. */
  9291. return MA_FALSE;
  9292. #endif
  9293. #else
  9294. return MA_FALSE; /* NEON is only supported on ARM architectures. */
  9295. #endif
  9296. #else
  9297. return MA_FALSE; /* No compiler support. */
  9298. #endif
  9299. }
  9300. #define MA_SIMD_NONE 0
  9301. #define MA_SIMD_SSE2 1
  9302. #define MA_SIMD_AVX2 2
  9303. #define MA_SIMD_NEON 3
  9304. #ifndef MA_PREFERRED_SIMD
  9305. # if defined(MA_SUPPORT_SSE2) && defined(MA_PREFER_SSE2)
  9306. #define MA_PREFERRED_SIMD MA_SIMD_SSE2
  9307. #elif defined(MA_SUPPORT_AVX2) && defined(MA_PREFER_AVX2)
  9308. #define MA_PREFERRED_SIMD MA_SIMD_AVX2
  9309. #elif defined(MA_SUPPORT_NEON) && defined(MA_PREFER_NEON)
  9310. #define MA_PREFERRED_SIMD MA_SIMD_NEON
  9311. #else
  9312. #define MA_PREFERRED_SIMD MA_SIMD_NONE
  9313. #endif
  9314. #endif
  9315. #if defined(__has_builtin)
  9316. #define MA_COMPILER_HAS_BUILTIN(x) __has_builtin(x)
  9317. #else
  9318. #define MA_COMPILER_HAS_BUILTIN(x) 0
  9319. #endif
  9320. #ifndef MA_ASSUME
  9321. #if MA_COMPILER_HAS_BUILTIN(__builtin_assume)
  9322. #define MA_ASSUME(x) __builtin_assume(x)
  9323. #elif MA_COMPILER_HAS_BUILTIN(__builtin_unreachable)
  9324. #define MA_ASSUME(x) do { if (!(x)) __builtin_unreachable(); } while (0)
  9325. #elif defined(_MSC_VER)
  9326. #define MA_ASSUME(x) __assume(x)
  9327. #else
  9328. #define MA_ASSUME(x) (void)(x)
  9329. #endif
  9330. #endif
  9331. #ifndef MA_RESTRICT
  9332. #if defined(__clang__) || defined(__GNUC__) || defined(_MSC_VER)
  9333. #define MA_RESTRICT __restrict
  9334. #else
  9335. #define MA_RESTRICT
  9336. #endif
  9337. #endif
  9338. #if defined(_MSC_VER) && _MSC_VER >= 1400
  9339. #define MA_HAS_BYTESWAP16_INTRINSIC
  9340. #define MA_HAS_BYTESWAP32_INTRINSIC
  9341. #define MA_HAS_BYTESWAP64_INTRINSIC
  9342. #elif defined(__clang__)
  9343. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap16)
  9344. #define MA_HAS_BYTESWAP16_INTRINSIC
  9345. #endif
  9346. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap32)
  9347. #define MA_HAS_BYTESWAP32_INTRINSIC
  9348. #endif
  9349. #if MA_COMPILER_HAS_BUILTIN(__builtin_bswap64)
  9350. #define MA_HAS_BYTESWAP64_INTRINSIC
  9351. #endif
  9352. #elif defined(__GNUC__)
  9353. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  9354. #define MA_HAS_BYTESWAP32_INTRINSIC
  9355. #define MA_HAS_BYTESWAP64_INTRINSIC
  9356. #endif
  9357. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  9358. #define MA_HAS_BYTESWAP16_INTRINSIC
  9359. #endif
  9360. #endif
  9361. static MA_INLINE ma_bool32 ma_is_little_endian(void)
  9362. {
  9363. #if defined(MA_X86) || defined(MA_X64)
  9364. return MA_TRUE;
  9365. #else
  9366. int n = 1;
  9367. return (*(char*)&n) == 1;
  9368. #endif
  9369. }
  9370. static MA_INLINE ma_bool32 ma_is_big_endian(void)
  9371. {
  9372. return !ma_is_little_endian();
  9373. }
  9374. static MA_INLINE ma_uint32 ma_swap_endian_uint32(ma_uint32 n)
  9375. {
  9376. #ifdef MA_HAS_BYTESWAP32_INTRINSIC
  9377. #if defined(_MSC_VER)
  9378. return _byteswap_ulong(n);
  9379. #elif defined(__GNUC__) || defined(__clang__)
  9380. #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. */
  9381. /* Inline assembly optimized implementation for ARM. In my testing, GCC does not generate optimized code with __builtin_bswap32(). */
  9382. ma_uint32 r;
  9383. __asm__ __volatile__ (
  9384. #if defined(MA_64BIT)
  9385. "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! */
  9386. #else
  9387. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  9388. #endif
  9389. );
  9390. return r;
  9391. #else
  9392. return __builtin_bswap32(n);
  9393. #endif
  9394. #else
  9395. #error "This compiler does not support the byte swap intrinsic."
  9396. #endif
  9397. #else
  9398. return ((n & 0xFF000000) >> 24) |
  9399. ((n & 0x00FF0000) >> 8) |
  9400. ((n & 0x0000FF00) << 8) |
  9401. ((n & 0x000000FF) << 24);
  9402. #endif
  9403. }
  9404. #if !defined(MA_EMSCRIPTEN)
  9405. #ifdef MA_WIN32
  9406. static void ma_sleep__win32(ma_uint32 milliseconds)
  9407. {
  9408. Sleep((DWORD)milliseconds);
  9409. }
  9410. #endif
  9411. #ifdef MA_POSIX
  9412. static void ma_sleep__posix(ma_uint32 milliseconds)
  9413. {
  9414. #ifdef MA_EMSCRIPTEN
  9415. (void)milliseconds;
  9416. MA_ASSERT(MA_FALSE); /* The Emscripten build should never sleep. */
  9417. #else
  9418. #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
  9419. struct timespec ts;
  9420. ts.tv_sec = milliseconds / 1000;
  9421. ts.tv_nsec = milliseconds % 1000 * 1000000;
  9422. nanosleep(&ts, NULL);
  9423. #else
  9424. struct timeval tv;
  9425. tv.tv_sec = milliseconds / 1000;
  9426. tv.tv_usec = milliseconds % 1000 * 1000;
  9427. select(0, NULL, NULL, NULL, &tv);
  9428. #endif
  9429. #endif
  9430. }
  9431. #endif
  9432. static MA_INLINE void ma_sleep(ma_uint32 milliseconds)
  9433. {
  9434. #ifdef MA_WIN32
  9435. ma_sleep__win32(milliseconds);
  9436. #endif
  9437. #ifdef MA_POSIX
  9438. ma_sleep__posix(milliseconds);
  9439. #endif
  9440. }
  9441. #endif
  9442. static MA_INLINE void ma_yield()
  9443. {
  9444. #if defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64)
  9445. /* x86/x64 */
  9446. #if (defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)) && !defined(__clang__)
  9447. #if _MSC_VER >= 1400
  9448. _mm_pause();
  9449. #else
  9450. #if defined(__DMC__)
  9451. /* Digital Mars does not recognize the PAUSE opcode. Fall back to NOP. */
  9452. __asm nop;
  9453. #else
  9454. __asm pause;
  9455. #endif
  9456. #endif
  9457. #else
  9458. __asm__ __volatile__ ("pause");
  9459. #endif
  9460. #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__)
  9461. /* ARM */
  9462. #if defined(_MSC_VER)
  9463. /* 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. */
  9464. __yield();
  9465. #else
  9466. __asm__ __volatile__ ("yield"); /* ARMv6K/ARMv6T2 and above. */
  9467. #endif
  9468. #else
  9469. /* Unknown or unsupported architecture. No-op. */
  9470. #endif
  9471. }
  9472. #define MA_MM_DENORMALS_ZERO_MASK 0x0040
  9473. #define MA_MM_FLUSH_ZERO_MASK 0x8000
  9474. static MA_INLINE unsigned int ma_disable_denormals()
  9475. {
  9476. unsigned int prevState;
  9477. #if defined(_MSC_VER)
  9478. {
  9479. /*
  9480. Older versions of Visual Studio don't support the "safe" versions of _controlfp_s(). I don't
  9481. know which version of Visual Studio first added support for _controlfp_s(), but I do know
  9482. that VC6 lacks support. _MSC_VER = 1200 is VC6, but if you get compilation errors on older
  9483. versions of Visual Studio, let me know and I'll make the necessary adjustment.
  9484. */
  9485. #if _MSC_VER <= 1200
  9486. {
  9487. prevState = _statusfp();
  9488. _controlfp(prevState | _DN_FLUSH, _MCW_DN);
  9489. }
  9490. #else
  9491. {
  9492. unsigned int unused;
  9493. _controlfp_s(&prevState, 0, 0);
  9494. _controlfp_s(&unused, prevState | _DN_FLUSH, _MCW_DN);
  9495. }
  9496. #endif
  9497. }
  9498. #elif defined(MA_X86) || defined(MA_X64)
  9499. {
  9500. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9501. {
  9502. prevState = _mm_getcsr();
  9503. _mm_setcsr(prevState | MA_MM_DENORMALS_ZERO_MASK | MA_MM_FLUSH_ZERO_MASK);
  9504. }
  9505. #else
  9506. {
  9507. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9508. prevState = 0;
  9509. }
  9510. #endif
  9511. }
  9512. #else
  9513. {
  9514. /* Unknown or unsupported architecture. No-op. */
  9515. prevState = 0;
  9516. }
  9517. #endif
  9518. return prevState;
  9519. }
  9520. static MA_INLINE void ma_restore_denormals(unsigned int prevState)
  9521. {
  9522. #if defined(_MSC_VER)
  9523. {
  9524. /* Older versions of Visual Studio do not support _controlfp_s(). See ma_disable_denormals(). */
  9525. #if _MSC_VER <= 1200
  9526. {
  9527. _controlfp(prevState, _MCW_DN);
  9528. }
  9529. #else
  9530. {
  9531. unsigned int unused;
  9532. _controlfp_s(&unused, prevState, _MCW_DN);
  9533. }
  9534. #endif
  9535. }
  9536. #elif defined(MA_X86) || defined(MA_X64)
  9537. {
  9538. #if defined(__SSE2__) && !(defined(__TINYC__) || defined(__WATCOMC__)) /* <-- Add compilers that lack support for _mm_getcsr() and _mm_setcsr() to this list. */
  9539. {
  9540. _mm_setcsr(prevState);
  9541. }
  9542. #else
  9543. {
  9544. /* x88/64, but no support for _mm_getcsr()/_mm_setcsr(). May need to fall back to inlined assembly here. */
  9545. (void)prevState;
  9546. }
  9547. #endif
  9548. }
  9549. #else
  9550. {
  9551. /* Unknown or unsupported architecture. No-op. */
  9552. (void)prevState;
  9553. }
  9554. #endif
  9555. }
  9556. #ifndef MA_COINIT_VALUE
  9557. #define MA_COINIT_VALUE 0 /* 0 = COINIT_MULTITHREADED */
  9558. #endif
  9559. #ifndef MA_FLT_MAX
  9560. #ifdef FLT_MAX
  9561. #define MA_FLT_MAX FLT_MAX
  9562. #else
  9563. #define MA_FLT_MAX 3.402823466e+38F
  9564. #endif
  9565. #endif
  9566. #ifndef MA_PI
  9567. #define MA_PI 3.14159265358979323846264f
  9568. #endif
  9569. #ifndef MA_PI_D
  9570. #define MA_PI_D 3.14159265358979323846264
  9571. #endif
  9572. #ifndef MA_TAU
  9573. #define MA_TAU 6.28318530717958647693f
  9574. #endif
  9575. #ifndef MA_TAU_D
  9576. #define MA_TAU_D 6.28318530717958647693
  9577. #endif
  9578. /* The default format when ma_format_unknown (0) is requested when initializing a device. */
  9579. #ifndef MA_DEFAULT_FORMAT
  9580. #define MA_DEFAULT_FORMAT ma_format_f32
  9581. #endif
  9582. /* The default channel count to use when 0 is used when initializing a device. */
  9583. #ifndef MA_DEFAULT_CHANNELS
  9584. #define MA_DEFAULT_CHANNELS 2
  9585. #endif
  9586. /* The default sample rate to use when 0 is used when initializing a device. */
  9587. #ifndef MA_DEFAULT_SAMPLE_RATE
  9588. #define MA_DEFAULT_SAMPLE_RATE 48000
  9589. #endif
  9590. /* Default periods when none is specified in ma_device_init(). More periods means more work on the CPU. */
  9591. #ifndef MA_DEFAULT_PERIODS
  9592. #define MA_DEFAULT_PERIODS 3
  9593. #endif
  9594. /* The default period size in milliseconds for low latency mode. */
  9595. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY
  9596. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY 10
  9597. #endif
  9598. /* The default buffer size in milliseconds for conservative mode. */
  9599. #ifndef MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE
  9600. #define MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE 100
  9601. #endif
  9602. /* The default LPF filter order for linear resampling. Note that this is clamped to MA_MAX_FILTER_ORDER. */
  9603. #ifndef MA_DEFAULT_RESAMPLER_LPF_ORDER
  9604. #if MA_MAX_FILTER_ORDER >= 4
  9605. #define MA_DEFAULT_RESAMPLER_LPF_ORDER 4
  9606. #else
  9607. #define MA_DEFAULT_RESAMPLER_LPF_ORDER MA_MAX_FILTER_ORDER
  9608. #endif
  9609. #endif
  9610. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9611. #pragma GCC diagnostic push
  9612. #pragma GCC diagnostic ignored "-Wunused-variable"
  9613. #endif
  9614. /* Standard sample rates, in order of priority. */
  9615. static ma_uint32 g_maStandardSampleRatePriorities[] = {
  9616. (ma_uint32)ma_standard_sample_rate_48000,
  9617. (ma_uint32)ma_standard_sample_rate_44100,
  9618. (ma_uint32)ma_standard_sample_rate_32000,
  9619. (ma_uint32)ma_standard_sample_rate_24000,
  9620. (ma_uint32)ma_standard_sample_rate_22050,
  9621. (ma_uint32)ma_standard_sample_rate_88200,
  9622. (ma_uint32)ma_standard_sample_rate_96000,
  9623. (ma_uint32)ma_standard_sample_rate_176400,
  9624. (ma_uint32)ma_standard_sample_rate_192000,
  9625. (ma_uint32)ma_standard_sample_rate_16000,
  9626. (ma_uint32)ma_standard_sample_rate_11025,
  9627. (ma_uint32)ma_standard_sample_rate_8000,
  9628. (ma_uint32)ma_standard_sample_rate_352800,
  9629. (ma_uint32)ma_standard_sample_rate_384000
  9630. };
  9631. static MA_INLINE ma_bool32 ma_is_standard_sample_rate(ma_uint32 sampleRate)
  9632. {
  9633. ma_uint32 iSampleRate;
  9634. for (iSampleRate = 0; iSampleRate < sizeof(g_maStandardSampleRatePriorities) / sizeof(g_maStandardSampleRatePriorities[0]); iSampleRate += 1) {
  9635. if (g_maStandardSampleRatePriorities[iSampleRate] == sampleRate) {
  9636. return MA_TRUE;
  9637. }
  9638. }
  9639. /* Getting here means the sample rate is not supported. */
  9640. return MA_FALSE;
  9641. }
  9642. static ma_format g_maFormatPriorities[] = {
  9643. ma_format_s16, /* Most common */
  9644. ma_format_f32,
  9645. /*ma_format_s24_32,*/ /* Clean alignment */
  9646. ma_format_s32,
  9647. ma_format_s24, /* Unclean alignment */
  9648. ma_format_u8 /* Low quality */
  9649. };
  9650. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  9651. #pragma GCC diagnostic pop
  9652. #endif
  9653. MA_API void ma_version(ma_uint32* pMajor, ma_uint32* pMinor, ma_uint32* pRevision)
  9654. {
  9655. if (pMajor) {
  9656. *pMajor = MA_VERSION_MAJOR;
  9657. }
  9658. if (pMinor) {
  9659. *pMinor = MA_VERSION_MINOR;
  9660. }
  9661. if (pRevision) {
  9662. *pRevision = MA_VERSION_REVISION;
  9663. }
  9664. }
  9665. MA_API const char* ma_version_string(void)
  9666. {
  9667. return MA_VERSION_STRING;
  9668. }
  9669. /******************************************************************************
  9670. Standard Library Stuff
  9671. ******************************************************************************/
  9672. #ifndef MA_MALLOC
  9673. #ifdef MA_WIN32
  9674. #define MA_MALLOC(sz) HeapAlloc(GetProcessHeap(), 0, (sz))
  9675. #else
  9676. #define MA_MALLOC(sz) malloc((sz))
  9677. #endif
  9678. #endif
  9679. #ifndef MA_REALLOC
  9680. #ifdef MA_WIN32
  9681. #define MA_REALLOC(p, sz) (((sz) > 0) ? ((p) ? HeapReAlloc(GetProcessHeap(), 0, (p), (sz)) : HeapAlloc(GetProcessHeap(), 0, (sz))) : ((VOID*)(size_t)(HeapFree(GetProcessHeap(), 0, (p)) & 0)))
  9682. #else
  9683. #define MA_REALLOC(p, sz) realloc((p), (sz))
  9684. #endif
  9685. #endif
  9686. #ifndef MA_FREE
  9687. #ifdef MA_WIN32
  9688. #define MA_FREE(p) HeapFree(GetProcessHeap(), 0, (p))
  9689. #else
  9690. #define MA_FREE(p) free((p))
  9691. #endif
  9692. #endif
  9693. static MA_INLINE void ma_zero_memory_default(void* p, size_t sz)
  9694. {
  9695. #ifdef MA_WIN32
  9696. ZeroMemory(p, sz);
  9697. #else
  9698. if (sz > 0) {
  9699. memset(p, 0, sz);
  9700. }
  9701. #endif
  9702. }
  9703. #ifndef MA_ZERO_MEMORY
  9704. #define MA_ZERO_MEMORY(p, sz) ma_zero_memory_default((p), (sz))
  9705. #endif
  9706. #ifndef MA_COPY_MEMORY
  9707. #ifdef MA_WIN32
  9708. #define MA_COPY_MEMORY(dst, src, sz) CopyMemory((dst), (src), (sz))
  9709. #else
  9710. #define MA_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  9711. #endif
  9712. #endif
  9713. #ifndef MA_MOVE_MEMORY
  9714. #ifdef MA_WIN32
  9715. #define MA_MOVE_MEMORY(dst, src, sz) MoveMemory((dst), (src), (sz))
  9716. #else
  9717. #define MA_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  9718. #endif
  9719. #endif
  9720. #ifndef MA_ASSERT
  9721. #ifdef MA_WIN32
  9722. #define MA_ASSERT(condition) assert(condition)
  9723. #else
  9724. #define MA_ASSERT(condition) assert(condition)
  9725. #endif
  9726. #endif
  9727. #define MA_ZERO_OBJECT(p) MA_ZERO_MEMORY((p), sizeof(*(p)))
  9728. #define ma_countof(x) (sizeof(x) / sizeof(x[0]))
  9729. #define ma_max(x, y) (((x) > (y)) ? (x) : (y))
  9730. #define ma_min(x, y) (((x) < (y)) ? (x) : (y))
  9731. #define ma_abs(x) (((x) > 0) ? (x) : -(x))
  9732. #define ma_clamp(x, lo, hi) (ma_max(lo, ma_min(x, hi)))
  9733. #define ma_offset_ptr(p, offset) (((ma_uint8*)(p)) + (offset))
  9734. #define ma_align(x, a) ((x + (a-1)) & ~(a-1))
  9735. #define ma_align_64(x) ma_align(x, 8)
  9736. #define ma_buffer_frame_capacity(buffer, channels, format) (sizeof(buffer) / ma_get_bytes_per_sample(format) / (channels))
  9737. static MA_INLINE double ma_sind(double x)
  9738. {
  9739. /* TODO: Implement custom sin(x). */
  9740. return sin(x);
  9741. }
  9742. static MA_INLINE double ma_expd(double x)
  9743. {
  9744. /* TODO: Implement custom exp(x). */
  9745. return exp(x);
  9746. }
  9747. static MA_INLINE double ma_logd(double x)
  9748. {
  9749. /* TODO: Implement custom log(x). */
  9750. return log(x);
  9751. }
  9752. static MA_INLINE double ma_powd(double x, double y)
  9753. {
  9754. /* TODO: Implement custom pow(x, y). */
  9755. return pow(x, y);
  9756. }
  9757. static MA_INLINE double ma_sqrtd(double x)
  9758. {
  9759. /* TODO: Implement custom sqrt(x). */
  9760. return sqrt(x);
  9761. }
  9762. static MA_INLINE float ma_sinf(float x)
  9763. {
  9764. return (float)ma_sind((float)x);
  9765. }
  9766. static MA_INLINE double ma_cosd(double x)
  9767. {
  9768. return ma_sind((MA_PI_D*0.5) - x);
  9769. }
  9770. static MA_INLINE float ma_cosf(float x)
  9771. {
  9772. return (float)ma_cosd((float)x);
  9773. }
  9774. static MA_INLINE double ma_log10d(double x)
  9775. {
  9776. return ma_logd(x) * 0.43429448190325182765;
  9777. }
  9778. static MA_INLINE float ma_powf(float x, float y)
  9779. {
  9780. return (float)ma_powd((double)x, (double)y);
  9781. }
  9782. static MA_INLINE float ma_log10f(float x)
  9783. {
  9784. return (float)ma_log10d((double)x);
  9785. }
  9786. static MA_INLINE double ma_degrees_to_radians(double degrees)
  9787. {
  9788. return degrees * 0.01745329252;
  9789. }
  9790. static MA_INLINE double ma_radians_to_degrees(double radians)
  9791. {
  9792. return radians * 57.295779512896;
  9793. }
  9794. static MA_INLINE float ma_degrees_to_radians_f(float degrees)
  9795. {
  9796. return degrees * 0.01745329252f;
  9797. }
  9798. static MA_INLINE float ma_radians_to_degrees_f(float radians)
  9799. {
  9800. return radians * 57.295779512896f;
  9801. }
  9802. /*
  9803. Return Values:
  9804. 0: Success
  9805. 22: EINVAL
  9806. 34: ERANGE
  9807. Not using symbolic constants for errors because I want to avoid #including errno.h
  9808. */
  9809. MA_API int ma_strcpy_s(char* dst, size_t dstSizeInBytes, const char* src)
  9810. {
  9811. size_t i;
  9812. if (dst == 0) {
  9813. return 22;
  9814. }
  9815. if (dstSizeInBytes == 0) {
  9816. return 34;
  9817. }
  9818. if (src == 0) {
  9819. dst[0] = '\0';
  9820. return 22;
  9821. }
  9822. for (i = 0; i < dstSizeInBytes && src[i] != '\0'; ++i) {
  9823. dst[i] = src[i];
  9824. }
  9825. if (i < dstSizeInBytes) {
  9826. dst[i] = '\0';
  9827. return 0;
  9828. }
  9829. dst[0] = '\0';
  9830. return 34;
  9831. }
  9832. MA_API int ma_wcscpy_s(wchar_t* dst, size_t dstCap, const wchar_t* src)
  9833. {
  9834. size_t i;
  9835. if (dst == 0) {
  9836. return 22;
  9837. }
  9838. if (dstCap == 0) {
  9839. return 34;
  9840. }
  9841. if (src == 0) {
  9842. dst[0] = '\0';
  9843. return 22;
  9844. }
  9845. for (i = 0; i < dstCap && src[i] != '\0'; ++i) {
  9846. dst[i] = src[i];
  9847. }
  9848. if (i < dstCap) {
  9849. dst[i] = '\0';
  9850. return 0;
  9851. }
  9852. dst[0] = '\0';
  9853. return 34;
  9854. }
  9855. MA_API int ma_strncpy_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  9856. {
  9857. size_t maxcount;
  9858. size_t i;
  9859. if (dst == 0) {
  9860. return 22;
  9861. }
  9862. if (dstSizeInBytes == 0) {
  9863. return 34;
  9864. }
  9865. if (src == 0) {
  9866. dst[0] = '\0';
  9867. return 22;
  9868. }
  9869. maxcount = count;
  9870. if (count == ((size_t)-1) || count >= dstSizeInBytes) { /* -1 = _TRUNCATE */
  9871. maxcount = dstSizeInBytes - 1;
  9872. }
  9873. for (i = 0; i < maxcount && src[i] != '\0'; ++i) {
  9874. dst[i] = src[i];
  9875. }
  9876. if (src[i] == '\0' || i == count || count == ((size_t)-1)) {
  9877. dst[i] = '\0';
  9878. return 0;
  9879. }
  9880. dst[0] = '\0';
  9881. return 34;
  9882. }
  9883. MA_API int ma_strcat_s(char* dst, size_t dstSizeInBytes, const char* src)
  9884. {
  9885. char* dstorig;
  9886. if (dst == 0) {
  9887. return 22;
  9888. }
  9889. if (dstSizeInBytes == 0) {
  9890. return 34;
  9891. }
  9892. if (src == 0) {
  9893. dst[0] = '\0';
  9894. return 22;
  9895. }
  9896. dstorig = dst;
  9897. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  9898. dst += 1;
  9899. dstSizeInBytes -= 1;
  9900. }
  9901. if (dstSizeInBytes == 0) {
  9902. return 22; /* Unterminated. */
  9903. }
  9904. while (dstSizeInBytes > 0 && src[0] != '\0') {
  9905. *dst++ = *src++;
  9906. dstSizeInBytes -= 1;
  9907. }
  9908. if (dstSizeInBytes > 0) {
  9909. dst[0] = '\0';
  9910. } else {
  9911. dstorig[0] = '\0';
  9912. return 34;
  9913. }
  9914. return 0;
  9915. }
  9916. MA_API int ma_strncat_s(char* dst, size_t dstSizeInBytes, const char* src, size_t count)
  9917. {
  9918. char* dstorig;
  9919. if (dst == 0) {
  9920. return 22;
  9921. }
  9922. if (dstSizeInBytes == 0) {
  9923. return 34;
  9924. }
  9925. if (src == 0) {
  9926. return 22;
  9927. }
  9928. dstorig = dst;
  9929. while (dstSizeInBytes > 0 && dst[0] != '\0') {
  9930. dst += 1;
  9931. dstSizeInBytes -= 1;
  9932. }
  9933. if (dstSizeInBytes == 0) {
  9934. return 22; /* Unterminated. */
  9935. }
  9936. if (count == ((size_t)-1)) { /* _TRUNCATE */
  9937. count = dstSizeInBytes - 1;
  9938. }
  9939. while (dstSizeInBytes > 0 && src[0] != '\0' && count > 0) {
  9940. *dst++ = *src++;
  9941. dstSizeInBytes -= 1;
  9942. count -= 1;
  9943. }
  9944. if (dstSizeInBytes > 0) {
  9945. dst[0] = '\0';
  9946. } else {
  9947. dstorig[0] = '\0';
  9948. return 34;
  9949. }
  9950. return 0;
  9951. }
  9952. MA_API int ma_itoa_s(int value, char* dst, size_t dstSizeInBytes, int radix)
  9953. {
  9954. int sign;
  9955. unsigned int valueU;
  9956. char* dstEnd;
  9957. if (dst == NULL || dstSizeInBytes == 0) {
  9958. return 22;
  9959. }
  9960. if (radix < 2 || radix > 36) {
  9961. dst[0] = '\0';
  9962. return 22;
  9963. }
  9964. sign = (value < 0 && radix == 10) ? -1 : 1; /* The negative sign is only used when the base is 10. */
  9965. if (value < 0) {
  9966. valueU = -value;
  9967. } else {
  9968. valueU = value;
  9969. }
  9970. dstEnd = dst;
  9971. do
  9972. {
  9973. int remainder = valueU % radix;
  9974. if (remainder > 9) {
  9975. *dstEnd = (char)((remainder - 10) + 'a');
  9976. } else {
  9977. *dstEnd = (char)(remainder + '0');
  9978. }
  9979. dstEnd += 1;
  9980. dstSizeInBytes -= 1;
  9981. valueU /= radix;
  9982. } while (dstSizeInBytes > 0 && valueU > 0);
  9983. if (dstSizeInBytes == 0) {
  9984. dst[0] = '\0';
  9985. return 22; /* Ran out of room in the output buffer. */
  9986. }
  9987. if (sign < 0) {
  9988. *dstEnd++ = '-';
  9989. dstSizeInBytes -= 1;
  9990. }
  9991. if (dstSizeInBytes == 0) {
  9992. dst[0] = '\0';
  9993. return 22; /* Ran out of room in the output buffer. */
  9994. }
  9995. *dstEnd = '\0';
  9996. /* At this point the string will be reversed. */
  9997. dstEnd -= 1;
  9998. while (dst < dstEnd) {
  9999. char temp = *dst;
  10000. *dst = *dstEnd;
  10001. *dstEnd = temp;
  10002. dst += 1;
  10003. dstEnd -= 1;
  10004. }
  10005. return 0;
  10006. }
  10007. MA_API int ma_strcmp(const char* str1, const char* str2)
  10008. {
  10009. if (str1 == str2) return 0;
  10010. /* These checks differ from the standard implementation. It's not important, but I prefer it just for sanity. */
  10011. if (str1 == NULL) return -1;
  10012. if (str2 == NULL) return 1;
  10013. for (;;) {
  10014. if (str1[0] == '\0') {
  10015. break;
  10016. }
  10017. if (str1[0] != str2[0]) {
  10018. break;
  10019. }
  10020. str1 += 1;
  10021. str2 += 1;
  10022. }
  10023. return ((unsigned char*)str1)[0] - ((unsigned char*)str2)[0];
  10024. }
  10025. MA_API int ma_strappend(char* dst, size_t dstSize, const char* srcA, const char* srcB)
  10026. {
  10027. int result;
  10028. result = ma_strncpy_s(dst, dstSize, srcA, (size_t)-1);
  10029. if (result != 0) {
  10030. return result;
  10031. }
  10032. result = ma_strncat_s(dst, dstSize, srcB, (size_t)-1);
  10033. if (result != 0) {
  10034. return result;
  10035. }
  10036. return result;
  10037. }
  10038. MA_API char* ma_copy_string(const char* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10039. {
  10040. size_t sz;
  10041. char* dst;
  10042. if (src == NULL) {
  10043. return NULL;
  10044. }
  10045. sz = strlen(src)+1;
  10046. dst = (char*)ma_malloc(sz, pAllocationCallbacks);
  10047. if (dst == NULL) {
  10048. return NULL;
  10049. }
  10050. ma_strcpy_s(dst, sz, src);
  10051. return dst;
  10052. }
  10053. MA_API wchar_t* ma_copy_string_w(const wchar_t* src, const ma_allocation_callbacks* pAllocationCallbacks)
  10054. {
  10055. size_t sz = wcslen(src)+1;
  10056. wchar_t* dst = (wchar_t*)ma_malloc(sz * sizeof(*dst), pAllocationCallbacks);
  10057. if (dst == NULL) {
  10058. return NULL;
  10059. }
  10060. ma_wcscpy_s(dst, sz, src);
  10061. return dst;
  10062. }
  10063. #include <errno.h>
  10064. static ma_result ma_result_from_errno(int e)
  10065. {
  10066. switch (e)
  10067. {
  10068. case 0: return MA_SUCCESS;
  10069. #ifdef EPERM
  10070. case EPERM: return MA_INVALID_OPERATION;
  10071. #endif
  10072. #ifdef ENOENT
  10073. case ENOENT: return MA_DOES_NOT_EXIST;
  10074. #endif
  10075. #ifdef ESRCH
  10076. case ESRCH: return MA_DOES_NOT_EXIST;
  10077. #endif
  10078. #ifdef EINTR
  10079. case EINTR: return MA_INTERRUPT;
  10080. #endif
  10081. #ifdef EIO
  10082. case EIO: return MA_IO_ERROR;
  10083. #endif
  10084. #ifdef ENXIO
  10085. case ENXIO: return MA_DOES_NOT_EXIST;
  10086. #endif
  10087. #ifdef E2BIG
  10088. case E2BIG: return MA_INVALID_ARGS;
  10089. #endif
  10090. #ifdef ENOEXEC
  10091. case ENOEXEC: return MA_INVALID_FILE;
  10092. #endif
  10093. #ifdef EBADF
  10094. case EBADF: return MA_INVALID_FILE;
  10095. #endif
  10096. #ifdef ECHILD
  10097. case ECHILD: return MA_ERROR;
  10098. #endif
  10099. #ifdef EAGAIN
  10100. case EAGAIN: return MA_UNAVAILABLE;
  10101. #endif
  10102. #ifdef ENOMEM
  10103. case ENOMEM: return MA_OUT_OF_MEMORY;
  10104. #endif
  10105. #ifdef EACCES
  10106. case EACCES: return MA_ACCESS_DENIED;
  10107. #endif
  10108. #ifdef EFAULT
  10109. case EFAULT: return MA_BAD_ADDRESS;
  10110. #endif
  10111. #ifdef ENOTBLK
  10112. case ENOTBLK: return MA_ERROR;
  10113. #endif
  10114. #ifdef EBUSY
  10115. case EBUSY: return MA_BUSY;
  10116. #endif
  10117. #ifdef EEXIST
  10118. case EEXIST: return MA_ALREADY_EXISTS;
  10119. #endif
  10120. #ifdef EXDEV
  10121. case EXDEV: return MA_ERROR;
  10122. #endif
  10123. #ifdef ENODEV
  10124. case ENODEV: return MA_DOES_NOT_EXIST;
  10125. #endif
  10126. #ifdef ENOTDIR
  10127. case ENOTDIR: return MA_NOT_DIRECTORY;
  10128. #endif
  10129. #ifdef EISDIR
  10130. case EISDIR: return MA_IS_DIRECTORY;
  10131. #endif
  10132. #ifdef EINVAL
  10133. case EINVAL: return MA_INVALID_ARGS;
  10134. #endif
  10135. #ifdef ENFILE
  10136. case ENFILE: return MA_TOO_MANY_OPEN_FILES;
  10137. #endif
  10138. #ifdef EMFILE
  10139. case EMFILE: return MA_TOO_MANY_OPEN_FILES;
  10140. #endif
  10141. #ifdef ENOTTY
  10142. case ENOTTY: return MA_INVALID_OPERATION;
  10143. #endif
  10144. #ifdef ETXTBSY
  10145. case ETXTBSY: return MA_BUSY;
  10146. #endif
  10147. #ifdef EFBIG
  10148. case EFBIG: return MA_TOO_BIG;
  10149. #endif
  10150. #ifdef ENOSPC
  10151. case ENOSPC: return MA_NO_SPACE;
  10152. #endif
  10153. #ifdef ESPIPE
  10154. case ESPIPE: return MA_BAD_SEEK;
  10155. #endif
  10156. #ifdef EROFS
  10157. case EROFS: return MA_ACCESS_DENIED;
  10158. #endif
  10159. #ifdef EMLINK
  10160. case EMLINK: return MA_TOO_MANY_LINKS;
  10161. #endif
  10162. #ifdef EPIPE
  10163. case EPIPE: return MA_BAD_PIPE;
  10164. #endif
  10165. #ifdef EDOM
  10166. case EDOM: return MA_OUT_OF_RANGE;
  10167. #endif
  10168. #ifdef ERANGE
  10169. case ERANGE: return MA_OUT_OF_RANGE;
  10170. #endif
  10171. #ifdef EDEADLK
  10172. case EDEADLK: return MA_DEADLOCK;
  10173. #endif
  10174. #ifdef ENAMETOOLONG
  10175. case ENAMETOOLONG: return MA_PATH_TOO_LONG;
  10176. #endif
  10177. #ifdef ENOLCK
  10178. case ENOLCK: return MA_ERROR;
  10179. #endif
  10180. #ifdef ENOSYS
  10181. case ENOSYS: return MA_NOT_IMPLEMENTED;
  10182. #endif
  10183. #ifdef ENOTEMPTY
  10184. case ENOTEMPTY: return MA_DIRECTORY_NOT_EMPTY;
  10185. #endif
  10186. #ifdef ELOOP
  10187. case ELOOP: return MA_TOO_MANY_LINKS;
  10188. #endif
  10189. #ifdef ENOMSG
  10190. case ENOMSG: return MA_NO_MESSAGE;
  10191. #endif
  10192. #ifdef EIDRM
  10193. case EIDRM: return MA_ERROR;
  10194. #endif
  10195. #ifdef ECHRNG
  10196. case ECHRNG: return MA_ERROR;
  10197. #endif
  10198. #ifdef EL2NSYNC
  10199. case EL2NSYNC: return MA_ERROR;
  10200. #endif
  10201. #ifdef EL3HLT
  10202. case EL3HLT: return MA_ERROR;
  10203. #endif
  10204. #ifdef EL3RST
  10205. case EL3RST: return MA_ERROR;
  10206. #endif
  10207. #ifdef ELNRNG
  10208. case ELNRNG: return MA_OUT_OF_RANGE;
  10209. #endif
  10210. #ifdef EUNATCH
  10211. case EUNATCH: return MA_ERROR;
  10212. #endif
  10213. #ifdef ENOCSI
  10214. case ENOCSI: return MA_ERROR;
  10215. #endif
  10216. #ifdef EL2HLT
  10217. case EL2HLT: return MA_ERROR;
  10218. #endif
  10219. #ifdef EBADE
  10220. case EBADE: return MA_ERROR;
  10221. #endif
  10222. #ifdef EBADR
  10223. case EBADR: return MA_ERROR;
  10224. #endif
  10225. #ifdef EXFULL
  10226. case EXFULL: return MA_ERROR;
  10227. #endif
  10228. #ifdef ENOANO
  10229. case ENOANO: return MA_ERROR;
  10230. #endif
  10231. #ifdef EBADRQC
  10232. case EBADRQC: return MA_ERROR;
  10233. #endif
  10234. #ifdef EBADSLT
  10235. case EBADSLT: return MA_ERROR;
  10236. #endif
  10237. #ifdef EBFONT
  10238. case EBFONT: return MA_INVALID_FILE;
  10239. #endif
  10240. #ifdef ENOSTR
  10241. case ENOSTR: return MA_ERROR;
  10242. #endif
  10243. #ifdef ENODATA
  10244. case ENODATA: return MA_NO_DATA_AVAILABLE;
  10245. #endif
  10246. #ifdef ETIME
  10247. case ETIME: return MA_TIMEOUT;
  10248. #endif
  10249. #ifdef ENOSR
  10250. case ENOSR: return MA_NO_DATA_AVAILABLE;
  10251. #endif
  10252. #ifdef ENONET
  10253. case ENONET: return MA_NO_NETWORK;
  10254. #endif
  10255. #ifdef ENOPKG
  10256. case ENOPKG: return MA_ERROR;
  10257. #endif
  10258. #ifdef EREMOTE
  10259. case EREMOTE: return MA_ERROR;
  10260. #endif
  10261. #ifdef ENOLINK
  10262. case ENOLINK: return MA_ERROR;
  10263. #endif
  10264. #ifdef EADV
  10265. case EADV: return MA_ERROR;
  10266. #endif
  10267. #ifdef ESRMNT
  10268. case ESRMNT: return MA_ERROR;
  10269. #endif
  10270. #ifdef ECOMM
  10271. case ECOMM: return MA_ERROR;
  10272. #endif
  10273. #ifdef EPROTO
  10274. case EPROTO: return MA_ERROR;
  10275. #endif
  10276. #ifdef EMULTIHOP
  10277. case EMULTIHOP: return MA_ERROR;
  10278. #endif
  10279. #ifdef EDOTDOT
  10280. case EDOTDOT: return MA_ERROR;
  10281. #endif
  10282. #ifdef EBADMSG
  10283. case EBADMSG: return MA_BAD_MESSAGE;
  10284. #endif
  10285. #ifdef EOVERFLOW
  10286. case EOVERFLOW: return MA_TOO_BIG;
  10287. #endif
  10288. #ifdef ENOTUNIQ
  10289. case ENOTUNIQ: return MA_NOT_UNIQUE;
  10290. #endif
  10291. #ifdef EBADFD
  10292. case EBADFD: return MA_ERROR;
  10293. #endif
  10294. #ifdef EREMCHG
  10295. case EREMCHG: return MA_ERROR;
  10296. #endif
  10297. #ifdef ELIBACC
  10298. case ELIBACC: return MA_ACCESS_DENIED;
  10299. #endif
  10300. #ifdef ELIBBAD
  10301. case ELIBBAD: return MA_INVALID_FILE;
  10302. #endif
  10303. #ifdef ELIBSCN
  10304. case ELIBSCN: return MA_INVALID_FILE;
  10305. #endif
  10306. #ifdef ELIBMAX
  10307. case ELIBMAX: return MA_ERROR;
  10308. #endif
  10309. #ifdef ELIBEXEC
  10310. case ELIBEXEC: return MA_ERROR;
  10311. #endif
  10312. #ifdef EILSEQ
  10313. case EILSEQ: return MA_INVALID_DATA;
  10314. #endif
  10315. #ifdef ERESTART
  10316. case ERESTART: return MA_ERROR;
  10317. #endif
  10318. #ifdef ESTRPIPE
  10319. case ESTRPIPE: return MA_ERROR;
  10320. #endif
  10321. #ifdef EUSERS
  10322. case EUSERS: return MA_ERROR;
  10323. #endif
  10324. #ifdef ENOTSOCK
  10325. case ENOTSOCK: return MA_NOT_SOCKET;
  10326. #endif
  10327. #ifdef EDESTADDRREQ
  10328. case EDESTADDRREQ: return MA_NO_ADDRESS;
  10329. #endif
  10330. #ifdef EMSGSIZE
  10331. case EMSGSIZE: return MA_TOO_BIG;
  10332. #endif
  10333. #ifdef EPROTOTYPE
  10334. case EPROTOTYPE: return MA_BAD_PROTOCOL;
  10335. #endif
  10336. #ifdef ENOPROTOOPT
  10337. case ENOPROTOOPT: return MA_PROTOCOL_UNAVAILABLE;
  10338. #endif
  10339. #ifdef EPROTONOSUPPORT
  10340. case EPROTONOSUPPORT: return MA_PROTOCOL_NOT_SUPPORTED;
  10341. #endif
  10342. #ifdef ESOCKTNOSUPPORT
  10343. case ESOCKTNOSUPPORT: return MA_SOCKET_NOT_SUPPORTED;
  10344. #endif
  10345. #ifdef EOPNOTSUPP
  10346. case EOPNOTSUPP: return MA_INVALID_OPERATION;
  10347. #endif
  10348. #ifdef EPFNOSUPPORT
  10349. case EPFNOSUPPORT: return MA_PROTOCOL_FAMILY_NOT_SUPPORTED;
  10350. #endif
  10351. #ifdef EAFNOSUPPORT
  10352. case EAFNOSUPPORT: return MA_ADDRESS_FAMILY_NOT_SUPPORTED;
  10353. #endif
  10354. #ifdef EADDRINUSE
  10355. case EADDRINUSE: return MA_ALREADY_IN_USE;
  10356. #endif
  10357. #ifdef EADDRNOTAVAIL
  10358. case EADDRNOTAVAIL: return MA_ERROR;
  10359. #endif
  10360. #ifdef ENETDOWN
  10361. case ENETDOWN: return MA_NO_NETWORK;
  10362. #endif
  10363. #ifdef ENETUNREACH
  10364. case ENETUNREACH: return MA_NO_NETWORK;
  10365. #endif
  10366. #ifdef ENETRESET
  10367. case ENETRESET: return MA_NO_NETWORK;
  10368. #endif
  10369. #ifdef ECONNABORTED
  10370. case ECONNABORTED: return MA_NO_NETWORK;
  10371. #endif
  10372. #ifdef ECONNRESET
  10373. case ECONNRESET: return MA_CONNECTION_RESET;
  10374. #endif
  10375. #ifdef ENOBUFS
  10376. case ENOBUFS: return MA_NO_SPACE;
  10377. #endif
  10378. #ifdef EISCONN
  10379. case EISCONN: return MA_ALREADY_CONNECTED;
  10380. #endif
  10381. #ifdef ENOTCONN
  10382. case ENOTCONN: return MA_NOT_CONNECTED;
  10383. #endif
  10384. #ifdef ESHUTDOWN
  10385. case ESHUTDOWN: return MA_ERROR;
  10386. #endif
  10387. #ifdef ETOOMANYREFS
  10388. case ETOOMANYREFS: return MA_ERROR;
  10389. #endif
  10390. #ifdef ETIMEDOUT
  10391. case ETIMEDOUT: return MA_TIMEOUT;
  10392. #endif
  10393. #ifdef ECONNREFUSED
  10394. case ECONNREFUSED: return MA_CONNECTION_REFUSED;
  10395. #endif
  10396. #ifdef EHOSTDOWN
  10397. case EHOSTDOWN: return MA_NO_HOST;
  10398. #endif
  10399. #ifdef EHOSTUNREACH
  10400. case EHOSTUNREACH: return MA_NO_HOST;
  10401. #endif
  10402. #ifdef EALREADY
  10403. case EALREADY: return MA_IN_PROGRESS;
  10404. #endif
  10405. #ifdef EINPROGRESS
  10406. case EINPROGRESS: return MA_IN_PROGRESS;
  10407. #endif
  10408. #ifdef ESTALE
  10409. case ESTALE: return MA_INVALID_FILE;
  10410. #endif
  10411. #ifdef EUCLEAN
  10412. case EUCLEAN: return MA_ERROR;
  10413. #endif
  10414. #ifdef ENOTNAM
  10415. case ENOTNAM: return MA_ERROR;
  10416. #endif
  10417. #ifdef ENAVAIL
  10418. case ENAVAIL: return MA_ERROR;
  10419. #endif
  10420. #ifdef EISNAM
  10421. case EISNAM: return MA_ERROR;
  10422. #endif
  10423. #ifdef EREMOTEIO
  10424. case EREMOTEIO: return MA_IO_ERROR;
  10425. #endif
  10426. #ifdef EDQUOT
  10427. case EDQUOT: return MA_NO_SPACE;
  10428. #endif
  10429. #ifdef ENOMEDIUM
  10430. case ENOMEDIUM: return MA_DOES_NOT_EXIST;
  10431. #endif
  10432. #ifdef EMEDIUMTYPE
  10433. case EMEDIUMTYPE: return MA_ERROR;
  10434. #endif
  10435. #ifdef ECANCELED
  10436. case ECANCELED: return MA_CANCELLED;
  10437. #endif
  10438. #ifdef ENOKEY
  10439. case ENOKEY: return MA_ERROR;
  10440. #endif
  10441. #ifdef EKEYEXPIRED
  10442. case EKEYEXPIRED: return MA_ERROR;
  10443. #endif
  10444. #ifdef EKEYREVOKED
  10445. case EKEYREVOKED: return MA_ERROR;
  10446. #endif
  10447. #ifdef EKEYREJECTED
  10448. case EKEYREJECTED: return MA_ERROR;
  10449. #endif
  10450. #ifdef EOWNERDEAD
  10451. case EOWNERDEAD: return MA_ERROR;
  10452. #endif
  10453. #ifdef ENOTRECOVERABLE
  10454. case ENOTRECOVERABLE: return MA_ERROR;
  10455. #endif
  10456. #ifdef ERFKILL
  10457. case ERFKILL: return MA_ERROR;
  10458. #endif
  10459. #ifdef EHWPOISON
  10460. case EHWPOISON: return MA_ERROR;
  10461. #endif
  10462. default: return MA_ERROR;
  10463. }
  10464. }
  10465. MA_API ma_result ma_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  10466. {
  10467. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10468. errno_t err;
  10469. #endif
  10470. if (ppFile != NULL) {
  10471. *ppFile = NULL; /* Safety. */
  10472. }
  10473. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10474. return MA_INVALID_ARGS;
  10475. }
  10476. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10477. err = fopen_s(ppFile, pFilePath, pOpenMode);
  10478. if (err != 0) {
  10479. return ma_result_from_errno(err);
  10480. }
  10481. #else
  10482. #if defined(_WIN32) || defined(__APPLE__)
  10483. *ppFile = fopen(pFilePath, pOpenMode);
  10484. #else
  10485. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  10486. *ppFile = fopen64(pFilePath, pOpenMode);
  10487. #else
  10488. *ppFile = fopen(pFilePath, pOpenMode);
  10489. #endif
  10490. #endif
  10491. if (*ppFile == NULL) {
  10492. ma_result result = ma_result_from_errno(errno);
  10493. if (result == MA_SUCCESS) {
  10494. result = MA_ERROR; /* Just a safety check to make sure we never ever return success when pFile == NULL. */
  10495. }
  10496. return result;
  10497. }
  10498. #endif
  10499. return MA_SUCCESS;
  10500. }
  10501. /*
  10502. _wfopen() isn't always available in all compilation environments.
  10503. * Windows only.
  10504. * MSVC seems to support it universally as far back as VC6 from what I can tell (haven't checked further back).
  10505. * MinGW-64 (both 32- and 64-bit) seems to support it.
  10506. * MinGW wraps it in !defined(__STRICT_ANSI__).
  10507. * OpenWatcom wraps it in !defined(_NO_EXT_KEYS).
  10508. This can be reviewed as compatibility issues arise. The preference is to use _wfopen_s() and _wfopen() as opposed to the wcsrtombs()
  10509. fallback, so if you notice your compiler not detecting this properly I'm happy to look at adding support.
  10510. */
  10511. #if defined(_WIN32)
  10512. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  10513. #define MA_HAS_WFOPEN
  10514. #endif
  10515. #endif
  10516. MA_API ma_result ma_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const ma_allocation_callbacks* pAllocationCallbacks)
  10517. {
  10518. if (ppFile != NULL) {
  10519. *ppFile = NULL; /* Safety. */
  10520. }
  10521. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  10522. return MA_INVALID_ARGS;
  10523. }
  10524. #if defined(MA_HAS_WFOPEN)
  10525. {
  10526. /* Use _wfopen() on Windows. */
  10527. #if defined(_MSC_VER) && _MSC_VER >= 1400
  10528. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  10529. if (err != 0) {
  10530. return ma_result_from_errno(err);
  10531. }
  10532. #else
  10533. *ppFile = _wfopen(pFilePath, pOpenMode);
  10534. if (*ppFile == NULL) {
  10535. return ma_result_from_errno(errno);
  10536. }
  10537. #endif
  10538. (void)pAllocationCallbacks;
  10539. }
  10540. #else
  10541. /*
  10542. Use fopen() on anything other than Windows. Requires a conversion. This is annoying because fopen() is locale specific. The only real way I can
  10543. 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
  10544. 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.
  10545. */
  10546. {
  10547. mbstate_t mbs;
  10548. size_t lenMB;
  10549. const wchar_t* pFilePathTemp = pFilePath;
  10550. char* pFilePathMB = NULL;
  10551. char pOpenModeMB[32] = {0};
  10552. /* Get the length first. */
  10553. MA_ZERO_OBJECT(&mbs);
  10554. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  10555. if (lenMB == (size_t)-1) {
  10556. return ma_result_from_errno(errno);
  10557. }
  10558. pFilePathMB = (char*)ma_malloc(lenMB + 1, pAllocationCallbacks);
  10559. if (pFilePathMB == NULL) {
  10560. return MA_OUT_OF_MEMORY;
  10561. }
  10562. pFilePathTemp = pFilePath;
  10563. MA_ZERO_OBJECT(&mbs);
  10564. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  10565. /* The open mode should always consist of ASCII characters so we should be able to do a trivial conversion. */
  10566. {
  10567. size_t i = 0;
  10568. for (;;) {
  10569. if (pOpenMode[i] == 0) {
  10570. pOpenModeMB[i] = '\0';
  10571. break;
  10572. }
  10573. pOpenModeMB[i] = (char)pOpenMode[i];
  10574. i += 1;
  10575. }
  10576. }
  10577. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  10578. ma_free(pFilePathMB, pAllocationCallbacks);
  10579. }
  10580. if (*ppFile == NULL) {
  10581. return MA_ERROR;
  10582. }
  10583. #endif
  10584. return MA_SUCCESS;
  10585. }
  10586. static MA_INLINE void ma_copy_memory_64(void* dst, const void* src, ma_uint64 sizeInBytes)
  10587. {
  10588. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10589. MA_COPY_MEMORY(dst, src, (size_t)sizeInBytes);
  10590. #else
  10591. while (sizeInBytes > 0) {
  10592. ma_uint64 bytesToCopyNow = sizeInBytes;
  10593. if (bytesToCopyNow > MA_SIZE_MAX) {
  10594. bytesToCopyNow = MA_SIZE_MAX;
  10595. }
  10596. MA_COPY_MEMORY(dst, src, (size_t)bytesToCopyNow); /* Safe cast to size_t. */
  10597. sizeInBytes -= bytesToCopyNow;
  10598. dst = ( void*)(( ma_uint8*)dst + bytesToCopyNow);
  10599. src = (const void*)((const ma_uint8*)src + bytesToCopyNow);
  10600. }
  10601. #endif
  10602. }
  10603. static MA_INLINE void ma_zero_memory_64(void* dst, ma_uint64 sizeInBytes)
  10604. {
  10605. #if 0xFFFFFFFFFFFFFFFF <= MA_SIZE_MAX
  10606. MA_ZERO_MEMORY(dst, (size_t)sizeInBytes);
  10607. #else
  10608. while (sizeInBytes > 0) {
  10609. ma_uint64 bytesToZeroNow = sizeInBytes;
  10610. if (bytesToZeroNow > MA_SIZE_MAX) {
  10611. bytesToZeroNow = MA_SIZE_MAX;
  10612. }
  10613. MA_ZERO_MEMORY(dst, (size_t)bytesToZeroNow); /* Safe cast to size_t. */
  10614. sizeInBytes -= bytesToZeroNow;
  10615. dst = (void*)((ma_uint8*)dst + bytesToZeroNow);
  10616. }
  10617. #endif
  10618. }
  10619. /* Thanks to good old Bit Twiddling Hacks for this one: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2 */
  10620. static MA_INLINE unsigned int ma_next_power_of_2(unsigned int x)
  10621. {
  10622. x--;
  10623. x |= x >> 1;
  10624. x |= x >> 2;
  10625. x |= x >> 4;
  10626. x |= x >> 8;
  10627. x |= x >> 16;
  10628. x++;
  10629. return x;
  10630. }
  10631. static MA_INLINE unsigned int ma_prev_power_of_2(unsigned int x)
  10632. {
  10633. return ma_next_power_of_2(x) >> 1;
  10634. }
  10635. static MA_INLINE unsigned int ma_round_to_power_of_2(unsigned int x)
  10636. {
  10637. unsigned int prev = ma_prev_power_of_2(x);
  10638. unsigned int next = ma_next_power_of_2(x);
  10639. if ((next - x) > (x - prev)) {
  10640. return prev;
  10641. } else {
  10642. return next;
  10643. }
  10644. }
  10645. static MA_INLINE unsigned int ma_count_set_bits(unsigned int x)
  10646. {
  10647. unsigned int count = 0;
  10648. while (x != 0) {
  10649. if (x & 1) {
  10650. count += 1;
  10651. }
  10652. x = x >> 1;
  10653. }
  10654. return count;
  10655. }
  10656. /**************************************************************************************************************************************************************
  10657. Allocation Callbacks
  10658. **************************************************************************************************************************************************************/
  10659. static void* ma__malloc_default(size_t sz, void* pUserData)
  10660. {
  10661. (void)pUserData;
  10662. return MA_MALLOC(sz);
  10663. }
  10664. static void* ma__realloc_default(void* p, size_t sz, void* pUserData)
  10665. {
  10666. (void)pUserData;
  10667. return MA_REALLOC(p, sz);
  10668. }
  10669. static void ma__free_default(void* p, void* pUserData)
  10670. {
  10671. (void)pUserData;
  10672. MA_FREE(p);
  10673. }
  10674. static ma_allocation_callbacks ma_allocation_callbacks_init_default(void)
  10675. {
  10676. ma_allocation_callbacks callbacks;
  10677. callbacks.pUserData = NULL;
  10678. callbacks.onMalloc = ma__malloc_default;
  10679. callbacks.onRealloc = ma__realloc_default;
  10680. callbacks.onFree = ma__free_default;
  10681. return callbacks;
  10682. }
  10683. static ma_result ma_allocation_callbacks_init_copy(ma_allocation_callbacks* pDst, const ma_allocation_callbacks* pSrc)
  10684. {
  10685. if (pDst == NULL) {
  10686. return MA_INVALID_ARGS;
  10687. }
  10688. if (pSrc == NULL) {
  10689. *pDst = ma_allocation_callbacks_init_default();
  10690. } else {
  10691. if (pSrc->pUserData == NULL && pSrc->onFree == NULL && pSrc->onMalloc == NULL && pSrc->onRealloc == NULL) {
  10692. *pDst = ma_allocation_callbacks_init_default();
  10693. } else {
  10694. if (pSrc->onFree == NULL || (pSrc->onMalloc == NULL && pSrc->onRealloc == NULL)) {
  10695. return MA_INVALID_ARGS; /* Invalid allocation callbacks. */
  10696. } else {
  10697. *pDst = *pSrc;
  10698. }
  10699. }
  10700. }
  10701. return MA_SUCCESS;
  10702. }
  10703. /**************************************************************************************************************************************************************
  10704. Logging
  10705. **************************************************************************************************************************************************************/
  10706. MA_API const char* ma_log_level_to_string(ma_uint32 logLevel)
  10707. {
  10708. switch (logLevel)
  10709. {
  10710. case MA_LOG_LEVEL_DEBUG: return "DEBUG";
  10711. case MA_LOG_LEVEL_INFO: return "INFO";
  10712. case MA_LOG_LEVEL_WARNING: return "WARNING";
  10713. case MA_LOG_LEVEL_ERROR: return "ERROR";
  10714. default: return "ERROR";
  10715. }
  10716. }
  10717. #if defined(MA_DEBUG_OUTPUT)
  10718. /* Customize this to use a specific tag in __android_log_print() for debug output messages. */
  10719. #ifndef MA_ANDROID_LOG_TAG
  10720. #define MA_ANDROID_LOG_TAG "miniaudio"
  10721. #endif
  10722. void ma_log_callback_debug(void* pUserData, ma_uint32 level, const char* pMessage)
  10723. {
  10724. (void)pUserData;
  10725. /* Special handling for some platforms. */
  10726. #if defined(MA_ANDROID)
  10727. {
  10728. /* Android. */
  10729. __android_log_print(ANDROID_LOG_DEBUG, MA_ANDROID_LOG_TAG, "%s: %s", ma_log_level_to_string(level), pMessage);
  10730. }
  10731. #else
  10732. {
  10733. /* Everything else. */
  10734. printf("%s: %s", ma_log_level_to_string(level), pMessage);
  10735. }
  10736. #endif
  10737. }
  10738. #endif
  10739. MA_API ma_log_callback ma_log_callback_init(ma_log_callback_proc onLog, void* pUserData)
  10740. {
  10741. ma_log_callback callback;
  10742. MA_ZERO_OBJECT(&callback);
  10743. callback.onLog = onLog;
  10744. callback.pUserData = pUserData;
  10745. return callback;
  10746. }
  10747. MA_API ma_result ma_log_init(const ma_allocation_callbacks* pAllocationCallbacks, ma_log* pLog)
  10748. {
  10749. if (pLog == NULL) {
  10750. return MA_INVALID_ARGS;
  10751. }
  10752. MA_ZERO_OBJECT(pLog);
  10753. ma_allocation_callbacks_init_copy(&pLog->allocationCallbacks, pAllocationCallbacks);
  10754. /* We need a mutex for thread safety. */
  10755. #ifndef MA_NO_THREADING
  10756. {
  10757. ma_result result = ma_mutex_init(&pLog->lock);
  10758. if (result != MA_SUCCESS) {
  10759. return result;
  10760. }
  10761. }
  10762. #endif
  10763. /* If we're using debug output, enable it. */
  10764. #if defined(MA_DEBUG_OUTPUT)
  10765. {
  10766. ma_log_register_callback(pLog, ma_log_callback_init(ma_log_callback_debug, NULL)); /* Doesn't really matter if this fails. */
  10767. }
  10768. #endif
  10769. return MA_SUCCESS;
  10770. }
  10771. MA_API void ma_log_uninit(ma_log* pLog)
  10772. {
  10773. if (pLog == NULL) {
  10774. return;
  10775. }
  10776. #ifndef MA_NO_THREADING
  10777. ma_mutex_uninit(&pLog->lock);
  10778. #endif
  10779. }
  10780. static void ma_log_lock(ma_log* pLog)
  10781. {
  10782. #ifndef MA_NO_THREADING
  10783. ma_mutex_lock(&pLog->lock);
  10784. #else
  10785. (void)pLog;
  10786. #endif
  10787. }
  10788. static void ma_log_unlock(ma_log* pLog)
  10789. {
  10790. #ifndef MA_NO_THREADING
  10791. ma_mutex_unlock(&pLog->lock);
  10792. #else
  10793. (void)pLog;
  10794. #endif
  10795. }
  10796. MA_API ma_result ma_log_register_callback(ma_log* pLog, ma_log_callback callback)
  10797. {
  10798. ma_result result = MA_SUCCESS;
  10799. if (pLog == NULL || callback.onLog == NULL) {
  10800. return MA_INVALID_ARGS;
  10801. }
  10802. ma_log_lock(pLog);
  10803. {
  10804. if (pLog->callbackCount == ma_countof(pLog->callbacks)) {
  10805. result = MA_OUT_OF_MEMORY; /* Reached the maximum allowed log callbacks. */
  10806. } else {
  10807. pLog->callbacks[pLog->callbackCount] = callback;
  10808. pLog->callbackCount += 1;
  10809. }
  10810. }
  10811. ma_log_unlock(pLog);
  10812. return result;
  10813. }
  10814. MA_API ma_result ma_log_unregister_callback(ma_log* pLog, ma_log_callback callback)
  10815. {
  10816. if (pLog == NULL) {
  10817. return MA_INVALID_ARGS;
  10818. }
  10819. ma_log_lock(pLog);
  10820. {
  10821. ma_uint32 iLog;
  10822. for (iLog = 0; iLog < pLog->callbackCount; ) {
  10823. if (pLog->callbacks[iLog].onLog == callback.onLog) {
  10824. /* Found. Move everything down a slot. */
  10825. ma_uint32 jLog;
  10826. for (jLog = iLog; jLog < pLog->callbackCount-1; jLog += 1) {
  10827. pLog->callbacks[jLog] = pLog->callbacks[jLog + 1];
  10828. }
  10829. pLog->callbackCount -= 1;
  10830. } else {
  10831. /* Not found. */
  10832. iLog += 1;
  10833. }
  10834. }
  10835. }
  10836. ma_log_unlock(pLog);
  10837. return MA_SUCCESS;
  10838. }
  10839. MA_API ma_result ma_log_post(ma_log* pLog, ma_uint32 level, const char* pMessage)
  10840. {
  10841. if (pLog == NULL || pMessage == NULL) {
  10842. return MA_INVALID_ARGS;
  10843. }
  10844. ma_log_lock(pLog);
  10845. {
  10846. ma_uint32 iLog;
  10847. for (iLog = 0; iLog < pLog->callbackCount; iLog += 1) {
  10848. if (pLog->callbacks[iLog].onLog) {
  10849. pLog->callbacks[iLog].onLog(pLog->callbacks[iLog].pUserData, level, pMessage);
  10850. }
  10851. }
  10852. }
  10853. ma_log_unlock(pLog);
  10854. return MA_SUCCESS;
  10855. }
  10856. /*
  10857. 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
  10858. logging function, I'm happy to keep this simple. In the VC6 build we can implement this in terms of _vsnprintf().
  10859. */
  10860. #if defined(_MSC_VER) && _MSC_VER < 1900
  10861. static int ma_vscprintf(const ma_allocation_callbacks* pAllocationCallbacks, const char* format, va_list args)
  10862. {
  10863. #if _MSC_VER > 1200
  10864. return _vscprintf(format, args);
  10865. #else
  10866. int result;
  10867. char* pTempBuffer = NULL;
  10868. size_t tempBufferCap = 1024;
  10869. if (format == NULL) {
  10870. errno = EINVAL;
  10871. return -1;
  10872. }
  10873. for (;;) {
  10874. char* pNewTempBuffer = (char*)ma_realloc(pTempBuffer, tempBufferCap, pAllocationCallbacks);
  10875. if (pNewTempBuffer == NULL) {
  10876. ma_free(pTempBuffer, pAllocationCallbacks);
  10877. errno = ENOMEM;
  10878. return -1; /* Out of memory. */
  10879. }
  10880. pTempBuffer = pNewTempBuffer;
  10881. result = _vsnprintf(pTempBuffer, tempBufferCap, format, args);
  10882. ma_free(pTempBuffer, NULL);
  10883. if (result != -1) {
  10884. break; /* Got it. */
  10885. }
  10886. /* 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. */
  10887. tempBufferCap *= 2;
  10888. }
  10889. return result;
  10890. #endif
  10891. }
  10892. #endif
  10893. MA_API ma_result ma_log_postv(ma_log* pLog, ma_uint32 level, const char* pFormat, va_list args)
  10894. {
  10895. if (pLog == NULL || pFormat == NULL) {
  10896. return MA_INVALID_ARGS;
  10897. }
  10898. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || ((!defined(_MSC_VER) || _MSC_VER >= 1900) && !defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS)) || (defined(__cplusplus) && __cplusplus >= 201103L)
  10899. {
  10900. ma_result result;
  10901. int length;
  10902. char pFormattedMessageStack[1024];
  10903. char* pFormattedMessageHeap = NULL;
  10904. /* First try formatting into our fixed sized stack allocated buffer. If this is too small we'll fallback to a heap allocation. */
  10905. length = vsnprintf(pFormattedMessageStack, sizeof(pFormattedMessageStack), pFormat, args);
  10906. if (length < 0) {
  10907. return MA_INVALID_OPERATION; /* An error occured when trying to convert the buffer. */
  10908. }
  10909. if ((size_t)length < sizeof(pFormattedMessageStack)) {
  10910. /* The string was written to the stack. */
  10911. result = ma_log_post(pLog, level, pFormattedMessageStack);
  10912. } else {
  10913. /* The stack buffer was too small, try the heap. */
  10914. pFormattedMessageHeap = (char*)ma_malloc(length + 1, &pLog->allocationCallbacks);
  10915. if (pFormattedMessageHeap == NULL) {
  10916. return MA_OUT_OF_MEMORY;
  10917. }
  10918. length = vsnprintf(pFormattedMessageHeap, length + 1, pFormat, args);
  10919. if (length < 0) {
  10920. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  10921. return MA_INVALID_OPERATION;
  10922. }
  10923. result = ma_log_post(pLog, level, pFormattedMessageHeap);
  10924. ma_free(pFormattedMessageHeap, &pLog->allocationCallbacks);
  10925. }
  10926. return result;
  10927. }
  10928. #else
  10929. {
  10930. /*
  10931. 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
  10932. 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
  10933. a fixed sized stack allocated buffer.
  10934. */
  10935. #if defined(_MSC_VER) && _MSC_VER >= 1200 /* 1200 = VC6 */
  10936. {
  10937. ma_result result;
  10938. int formattedLen;
  10939. char* pFormattedMessage = NULL;
  10940. va_list args2;
  10941. #if _MSC_VER >= 1800
  10942. {
  10943. va_copy(args2, args);
  10944. }
  10945. #else
  10946. {
  10947. args2 = args;
  10948. }
  10949. #endif
  10950. formattedLen = ma_vscprintf(&pLog->allocationCallbacks, pFormat, args2);
  10951. va_end(args2);
  10952. if (formattedLen <= 0) {
  10953. return MA_INVALID_OPERATION;
  10954. }
  10955. pFormattedMessage = (char*)ma_malloc(formattedLen + 1, &pLog->allocationCallbacks);
  10956. if (pFormattedMessage == NULL) {
  10957. return MA_OUT_OF_MEMORY;
  10958. }
  10959. /* We'll get errors on newer versions of Visual Studio if we try to use vsprintf(). */
  10960. #if _MSC_VER >= 1400 /* 1400 = Visual Studio 2005 */
  10961. {
  10962. vsprintf_s(pFormattedMessage, formattedLen + 1, pFormat, args);
  10963. }
  10964. #else
  10965. {
  10966. vsprintf(pFormattedMessage, pFormat, args);
  10967. }
  10968. #endif
  10969. result = ma_log_post(pLog, level, pFormattedMessage);
  10970. ma_free(pFormattedMessage, &pLog->allocationCallbacks);
  10971. return result;
  10972. }
  10973. #else
  10974. {
  10975. /* Can't do anything because we don't have a safe way of to emulate vsnprintf() without a manual solution. */
  10976. (void)level;
  10977. (void)args;
  10978. return MA_INVALID_OPERATION;
  10979. }
  10980. #endif
  10981. }
  10982. #endif
  10983. }
  10984. MA_API ma_result ma_log_postf(ma_log* pLog, ma_uint32 level, const char* pFormat, ...)
  10985. {
  10986. ma_result result;
  10987. va_list args;
  10988. if (pLog == NULL || pFormat == NULL) {
  10989. return MA_INVALID_ARGS;
  10990. }
  10991. va_start(args, pFormat);
  10992. {
  10993. result = ma_log_postv(pLog, level, pFormat, args);
  10994. }
  10995. va_end(args);
  10996. return result;
  10997. }
  10998. static MA_INLINE ma_uint8 ma_clip_u8(ma_int32 x)
  10999. {
  11000. return (ma_uint8)(ma_clamp(x, -128, 127) + 128);
  11001. }
  11002. static MA_INLINE ma_int16 ma_clip_s16(ma_int32 x)
  11003. {
  11004. return (ma_int16)ma_clamp(x, -32768, 32767);
  11005. }
  11006. static MA_INLINE ma_int64 ma_clip_s24(ma_int64 x)
  11007. {
  11008. return (ma_int64)ma_clamp(x, -8388608, 8388607);
  11009. }
  11010. static MA_INLINE ma_int32 ma_clip_s32(ma_int64 x)
  11011. {
  11012. /* This dance is to silence warnings with -std=c89. A good compiler should be able to optimize this away. */
  11013. ma_int64 clipMin;
  11014. ma_int64 clipMax;
  11015. clipMin = -((ma_int64)2147483647 + 1);
  11016. clipMax = (ma_int64)2147483647;
  11017. return (ma_int32)ma_clamp(x, clipMin, clipMax);
  11018. }
  11019. static MA_INLINE float ma_clip_f32(float x)
  11020. {
  11021. if (x < -1) return -1;
  11022. if (x > +1) return +1;
  11023. return x;
  11024. }
  11025. static MA_INLINE float ma_mix_f32(float x, float y, float a)
  11026. {
  11027. return x*(1-a) + y*a;
  11028. }
  11029. static MA_INLINE float ma_mix_f32_fast(float x, float y, float a)
  11030. {
  11031. float r0 = (y - x);
  11032. float r1 = r0*a;
  11033. return x + r1;
  11034. /*return x + (y - x)*a;*/
  11035. }
  11036. #if defined(MA_SUPPORT_SSE2)
  11037. static MA_INLINE __m128 ma_mix_f32_fast__sse2(__m128 x, __m128 y, __m128 a)
  11038. {
  11039. return _mm_add_ps(x, _mm_mul_ps(_mm_sub_ps(y, x), a));
  11040. }
  11041. #endif
  11042. #if defined(MA_SUPPORT_AVX2)
  11043. static MA_INLINE __m256 ma_mix_f32_fast__avx2(__m256 x, __m256 y, __m256 a)
  11044. {
  11045. return _mm256_add_ps(x, _mm256_mul_ps(_mm256_sub_ps(y, x), a));
  11046. }
  11047. #endif
  11048. #if defined(MA_SUPPORT_NEON)
  11049. static MA_INLINE float32x4_t ma_mix_f32_fast__neon(float32x4_t x, float32x4_t y, float32x4_t a)
  11050. {
  11051. return vaddq_f32(x, vmulq_f32(vsubq_f32(y, x), a));
  11052. }
  11053. #endif
  11054. static MA_INLINE double ma_mix_f64(double x, double y, double a)
  11055. {
  11056. return x*(1-a) + y*a;
  11057. }
  11058. static MA_INLINE double ma_mix_f64_fast(double x, double y, double a)
  11059. {
  11060. return x + (y - x)*a;
  11061. }
  11062. static MA_INLINE float ma_scale_to_range_f32(float x, float lo, float hi)
  11063. {
  11064. return lo + x*(hi-lo);
  11065. }
  11066. /*
  11067. Greatest common factor using Euclid's algorithm iteratively.
  11068. */
  11069. static MA_INLINE ma_uint32 ma_gcf_u32(ma_uint32 a, ma_uint32 b)
  11070. {
  11071. for (;;) {
  11072. if (b == 0) {
  11073. break;
  11074. } else {
  11075. ma_uint32 t = a;
  11076. a = b;
  11077. b = t % a;
  11078. }
  11079. }
  11080. return a;
  11081. }
  11082. static ma_uint32 ma_ffs_32(ma_uint32 x)
  11083. {
  11084. ma_uint32 i;
  11085. /* Just a naive implementation just to get things working for now. Will optimize this later. */
  11086. for (i = 0; i < 32; i += 1) {
  11087. if ((x & (1 << i)) != 0) {
  11088. return i;
  11089. }
  11090. }
  11091. return i;
  11092. }
  11093. static MA_INLINE ma_int16 ma_float_to_fixed_16(float x)
  11094. {
  11095. return (ma_int16)(x * (1 << 8));
  11096. }
  11097. /*
  11098. Random Number Generation
  11099. miniaudio uses the LCG random number generation algorithm. This is good enough for audio.
  11100. Note that miniaudio's global LCG implementation uses global state which is _not_ thread-local. When this is called across
  11101. multiple threads, results will be unpredictable. However, it won't crash and results will still be random enough for
  11102. miniaudio's purposes.
  11103. */
  11104. #ifndef MA_DEFAULT_LCG_SEED
  11105. #define MA_DEFAULT_LCG_SEED 4321
  11106. #endif
  11107. #define MA_LCG_M 2147483647
  11108. #define MA_LCG_A 48271
  11109. #define MA_LCG_C 0
  11110. static ma_lcg g_maLCG = {MA_DEFAULT_LCG_SEED}; /* Non-zero initial seed. Use ma_seed() to use an explicit seed. */
  11111. static MA_INLINE void ma_lcg_seed(ma_lcg* pLCG, ma_int32 seed)
  11112. {
  11113. MA_ASSERT(pLCG != NULL);
  11114. pLCG->state = seed;
  11115. }
  11116. static MA_INLINE ma_int32 ma_lcg_rand_s32(ma_lcg* pLCG)
  11117. {
  11118. pLCG->state = (MA_LCG_A * pLCG->state + MA_LCG_C) % MA_LCG_M;
  11119. return pLCG->state;
  11120. }
  11121. static MA_INLINE ma_uint32 ma_lcg_rand_u32(ma_lcg* pLCG)
  11122. {
  11123. return (ma_uint32)ma_lcg_rand_s32(pLCG);
  11124. }
  11125. static MA_INLINE ma_int16 ma_lcg_rand_s16(ma_lcg* pLCG)
  11126. {
  11127. return (ma_int16)(ma_lcg_rand_s32(pLCG) & 0xFFFF);
  11128. }
  11129. static MA_INLINE double ma_lcg_rand_f64(ma_lcg* pLCG)
  11130. {
  11131. return ma_lcg_rand_s32(pLCG) / (double)0x7FFFFFFF;
  11132. }
  11133. static MA_INLINE float ma_lcg_rand_f32(ma_lcg* pLCG)
  11134. {
  11135. return (float)ma_lcg_rand_f64(pLCG);
  11136. }
  11137. static MA_INLINE float ma_lcg_rand_range_f32(ma_lcg* pLCG, float lo, float hi)
  11138. {
  11139. return ma_scale_to_range_f32(ma_lcg_rand_f32(pLCG), lo, hi);
  11140. }
  11141. static MA_INLINE ma_int32 ma_lcg_rand_range_s32(ma_lcg* pLCG, ma_int32 lo, ma_int32 hi)
  11142. {
  11143. if (lo == hi) {
  11144. return lo;
  11145. }
  11146. return lo + ma_lcg_rand_u32(pLCG) / (0xFFFFFFFF / (hi - lo + 1) + 1);
  11147. }
  11148. static MA_INLINE void ma_seed(ma_int32 seed)
  11149. {
  11150. ma_lcg_seed(&g_maLCG, seed);
  11151. }
  11152. static MA_INLINE ma_int32 ma_rand_s32(void)
  11153. {
  11154. return ma_lcg_rand_s32(&g_maLCG);
  11155. }
  11156. static MA_INLINE ma_uint32 ma_rand_u32(void)
  11157. {
  11158. return ma_lcg_rand_u32(&g_maLCG);
  11159. }
  11160. static MA_INLINE double ma_rand_f64(void)
  11161. {
  11162. return ma_lcg_rand_f64(&g_maLCG);
  11163. }
  11164. static MA_INLINE float ma_rand_f32(void)
  11165. {
  11166. return ma_lcg_rand_f32(&g_maLCG);
  11167. }
  11168. static MA_INLINE float ma_rand_range_f32(float lo, float hi)
  11169. {
  11170. return ma_lcg_rand_range_f32(&g_maLCG, lo, hi);
  11171. }
  11172. static MA_INLINE ma_int32 ma_rand_range_s32(ma_int32 lo, ma_int32 hi)
  11173. {
  11174. return ma_lcg_rand_range_s32(&g_maLCG, lo, hi);
  11175. }
  11176. static MA_INLINE float ma_dither_f32_rectangle(float ditherMin, float ditherMax)
  11177. {
  11178. return ma_rand_range_f32(ditherMin, ditherMax);
  11179. }
  11180. static MA_INLINE float ma_dither_f32_triangle(float ditherMin, float ditherMax)
  11181. {
  11182. float a = ma_rand_range_f32(ditherMin, 0);
  11183. float b = ma_rand_range_f32(0, ditherMax);
  11184. return a + b;
  11185. }
  11186. static MA_INLINE float ma_dither_f32(ma_dither_mode ditherMode, float ditherMin, float ditherMax)
  11187. {
  11188. if (ditherMode == ma_dither_mode_rectangle) {
  11189. return ma_dither_f32_rectangle(ditherMin, ditherMax);
  11190. }
  11191. if (ditherMode == ma_dither_mode_triangle) {
  11192. return ma_dither_f32_triangle(ditherMin, ditherMax);
  11193. }
  11194. return 0;
  11195. }
  11196. static MA_INLINE ma_int32 ma_dither_s32(ma_dither_mode ditherMode, ma_int32 ditherMin, ma_int32 ditherMax)
  11197. {
  11198. if (ditherMode == ma_dither_mode_rectangle) {
  11199. ma_int32 a = ma_rand_range_s32(ditherMin, ditherMax);
  11200. return a;
  11201. }
  11202. if (ditherMode == ma_dither_mode_triangle) {
  11203. ma_int32 a = ma_rand_range_s32(ditherMin, 0);
  11204. ma_int32 b = ma_rand_range_s32(0, ditherMax);
  11205. return a + b;
  11206. }
  11207. return 0;
  11208. }
  11209. /**************************************************************************************************************************************************************
  11210. Atomics
  11211. **************************************************************************************************************************************************************/
  11212. /* c89atomic.h begin */
  11213. #ifndef c89atomic_h
  11214. #define c89atomic_h
  11215. #if defined(__cplusplus)
  11216. extern "C" {
  11217. #endif
  11218. typedef signed char c89atomic_int8;
  11219. typedef unsigned char c89atomic_uint8;
  11220. typedef signed short c89atomic_int16;
  11221. typedef unsigned short c89atomic_uint16;
  11222. typedef signed int c89atomic_int32;
  11223. typedef unsigned int c89atomic_uint32;
  11224. #if defined(_MSC_VER) && !defined(__clang__)
  11225. typedef signed __int64 c89atomic_int64;
  11226. typedef unsigned __int64 c89atomic_uint64;
  11227. #else
  11228. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  11229. #pragma GCC diagnostic push
  11230. #pragma GCC diagnostic ignored "-Wlong-long"
  11231. #if defined(__clang__)
  11232. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  11233. #endif
  11234. #endif
  11235. typedef signed long long c89atomic_int64;
  11236. typedef unsigned long long c89atomic_uint64;
  11237. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  11238. #pragma GCC diagnostic pop
  11239. #endif
  11240. #endif
  11241. typedef int c89atomic_memory_order;
  11242. typedef unsigned char c89atomic_bool;
  11243. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11244. #ifdef _WIN32
  11245. #ifdef _WIN64
  11246. #define C89ATOMIC_64BIT
  11247. #else
  11248. #define C89ATOMIC_32BIT
  11249. #endif
  11250. #endif
  11251. #endif
  11252. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11253. #ifdef __GNUC__
  11254. #ifdef __LP64__
  11255. #define C89ATOMIC_64BIT
  11256. #else
  11257. #define C89ATOMIC_32BIT
  11258. #endif
  11259. #endif
  11260. #endif
  11261. #if !defined(C89ATOMIC_64BIT) && !defined(C89ATOMIC_32BIT)
  11262. #include <stdint.h>
  11263. #if INTPTR_MAX == INT64_MAX
  11264. #define C89ATOMIC_64BIT
  11265. #else
  11266. #define C89ATOMIC_32BIT
  11267. #endif
  11268. #endif
  11269. #if defined(__x86_64__) || defined(_M_X64)
  11270. #define C89ATOMIC_X64
  11271. #elif defined(__i386) || defined(_M_IX86)
  11272. #define C89ATOMIC_X86
  11273. #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  11274. #define C89ATOMIC_ARM
  11275. #endif
  11276. #if defined(_MSC_VER)
  11277. #define C89ATOMIC_INLINE __forceinline
  11278. #elif defined(__GNUC__)
  11279. #if defined(__STRICT_ANSI__)
  11280. #define C89ATOMIC_INLINE __inline__ __attribute__((always_inline))
  11281. #else
  11282. #define C89ATOMIC_INLINE inline __attribute__((always_inline))
  11283. #endif
  11284. #elif defined(__WATCOMC__) || defined(__DMC__)
  11285. #define C89ATOMIC_INLINE __inline
  11286. #else
  11287. #define C89ATOMIC_INLINE
  11288. #endif
  11289. #define C89ATOMIC_HAS_8
  11290. #define C89ATOMIC_HAS_16
  11291. #define C89ATOMIC_HAS_32
  11292. #define C89ATOMIC_HAS_64
  11293. #if (defined(_MSC_VER) ) || defined(__WATCOMC__) || defined(__DMC__)
  11294. #define c89atomic_memory_order_relaxed 0
  11295. #define c89atomic_memory_order_consume 1
  11296. #define c89atomic_memory_order_acquire 2
  11297. #define c89atomic_memory_order_release 3
  11298. #define c89atomic_memory_order_acq_rel 4
  11299. #define c89atomic_memory_order_seq_cst 5
  11300. #if _MSC_VER < 1600 && defined(C89ATOMIC_X86)
  11301. #define C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY
  11302. #endif
  11303. #if _MSC_VER < 1600
  11304. #undef C89ATOMIC_HAS_8
  11305. #undef C89ATOMIC_HAS_16
  11306. #endif
  11307. #if !defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11308. #include <intrin.h>
  11309. #endif
  11310. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11311. #if defined(C89ATOMIC_HAS_8)
  11312. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
  11313. {
  11314. c89atomic_uint8 result = 0;
  11315. __asm {
  11316. mov ecx, dst
  11317. mov al, expected
  11318. mov dl, desired
  11319. lock cmpxchg [ecx], dl
  11320. mov result, al
  11321. }
  11322. return result;
  11323. }
  11324. #endif
  11325. #if defined(C89ATOMIC_HAS_16)
  11326. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
  11327. {
  11328. c89atomic_uint16 result = 0;
  11329. __asm {
  11330. mov ecx, dst
  11331. mov ax, expected
  11332. mov dx, desired
  11333. lock cmpxchg [ecx], dx
  11334. mov result, ax
  11335. }
  11336. return result;
  11337. }
  11338. #endif
  11339. #if defined(C89ATOMIC_HAS_32)
  11340. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
  11341. {
  11342. c89atomic_uint32 result = 0;
  11343. __asm {
  11344. mov ecx, dst
  11345. mov eax, expected
  11346. mov edx, desired
  11347. lock cmpxchg [ecx], edx
  11348. mov result, eax
  11349. }
  11350. return result;
  11351. }
  11352. #endif
  11353. #if defined(C89ATOMIC_HAS_64)
  11354. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
  11355. {
  11356. c89atomic_uint32 resultEAX = 0;
  11357. c89atomic_uint32 resultEDX = 0;
  11358. __asm {
  11359. mov esi, dst
  11360. mov eax, dword ptr expected
  11361. mov edx, dword ptr expected + 4
  11362. mov ebx, dword ptr desired
  11363. mov ecx, dword ptr desired + 4
  11364. lock cmpxchg8b qword ptr [esi]
  11365. mov resultEAX, eax
  11366. mov resultEDX, edx
  11367. }
  11368. return ((c89atomic_uint64)resultEDX << 32) | resultEAX;
  11369. }
  11370. #endif
  11371. #else
  11372. #if defined(C89ATOMIC_HAS_8)
  11373. #define c89atomic_compare_and_swap_8( dst, expected, desired) (c89atomic_uint8 )_InterlockedCompareExchange8((volatile char*)dst, (char)desired, (char)expected)
  11374. #endif
  11375. #if defined(C89ATOMIC_HAS_16)
  11376. #define c89atomic_compare_and_swap_16(dst, expected, desired) (c89atomic_uint16)_InterlockedCompareExchange16((volatile short*)dst, (short)desired, (short)expected)
  11377. #endif
  11378. #if defined(C89ATOMIC_HAS_32)
  11379. #define c89atomic_compare_and_swap_32(dst, expected, desired) (c89atomic_uint32)_InterlockedCompareExchange((volatile long*)dst, (long)desired, (long)expected)
  11380. #endif
  11381. #if defined(C89ATOMIC_HAS_64)
  11382. #define c89atomic_compare_and_swap_64(dst, expected, desired) (c89atomic_uint64)_InterlockedCompareExchange64((volatile c89atomic_int64*)dst, (c89atomic_int64)desired, (c89atomic_int64)expected)
  11383. #endif
  11384. #endif
  11385. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11386. #if defined(C89ATOMIC_HAS_8)
  11387. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11388. {
  11389. c89atomic_uint8 result = 0;
  11390. (void)order;
  11391. __asm {
  11392. mov ecx, dst
  11393. mov al, src
  11394. lock xchg [ecx], al
  11395. mov result, al
  11396. }
  11397. return result;
  11398. }
  11399. #endif
  11400. #if defined(C89ATOMIC_HAS_16)
  11401. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11402. {
  11403. c89atomic_uint16 result = 0;
  11404. (void)order;
  11405. __asm {
  11406. mov ecx, dst
  11407. mov ax, src
  11408. lock xchg [ecx], ax
  11409. mov result, ax
  11410. }
  11411. return result;
  11412. }
  11413. #endif
  11414. #if defined(C89ATOMIC_HAS_32)
  11415. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11416. {
  11417. c89atomic_uint32 result = 0;
  11418. (void)order;
  11419. __asm {
  11420. mov ecx, dst
  11421. mov eax, src
  11422. lock xchg [ecx], eax
  11423. mov result, eax
  11424. }
  11425. return result;
  11426. }
  11427. #endif
  11428. #else
  11429. #if defined(C89ATOMIC_HAS_8)
  11430. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11431. {
  11432. (void)order;
  11433. return (c89atomic_uint8)_InterlockedExchange8((volatile char*)dst, (char)src);
  11434. }
  11435. #endif
  11436. #if defined(C89ATOMIC_HAS_16)
  11437. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11438. {
  11439. (void)order;
  11440. return (c89atomic_uint16)_InterlockedExchange16((volatile short*)dst, (short)src);
  11441. }
  11442. #endif
  11443. #if defined(C89ATOMIC_HAS_32)
  11444. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11445. {
  11446. (void)order;
  11447. return (c89atomic_uint32)_InterlockedExchange((volatile long*)dst, (long)src);
  11448. }
  11449. #endif
  11450. #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT)
  11451. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11452. {
  11453. (void)order;
  11454. return (c89atomic_uint64)_InterlockedExchange64((volatile long long*)dst, (long long)src);
  11455. }
  11456. #else
  11457. #endif
  11458. #endif
  11459. #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT)
  11460. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11461. {
  11462. c89atomic_uint64 oldValue;
  11463. do {
  11464. oldValue = *dst;
  11465. } while (c89atomic_compare_and_swap_64(dst, oldValue, src) != oldValue);
  11466. (void)order;
  11467. return oldValue;
  11468. }
  11469. #endif
  11470. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11471. #if defined(C89ATOMIC_HAS_8)
  11472. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11473. {
  11474. c89atomic_uint8 result = 0;
  11475. (void)order;
  11476. __asm {
  11477. mov ecx, dst
  11478. mov al, src
  11479. lock xadd [ecx], al
  11480. mov result, al
  11481. }
  11482. return result;
  11483. }
  11484. #endif
  11485. #if defined(C89ATOMIC_HAS_16)
  11486. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11487. {
  11488. c89atomic_uint16 result = 0;
  11489. (void)order;
  11490. __asm {
  11491. mov ecx, dst
  11492. mov ax, src
  11493. lock xadd [ecx], ax
  11494. mov result, ax
  11495. }
  11496. return result;
  11497. }
  11498. #endif
  11499. #if defined(C89ATOMIC_HAS_32)
  11500. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11501. {
  11502. c89atomic_uint32 result = 0;
  11503. (void)order;
  11504. __asm {
  11505. mov ecx, dst
  11506. mov eax, src
  11507. lock xadd [ecx], eax
  11508. mov result, eax
  11509. }
  11510. return result;
  11511. }
  11512. #endif
  11513. #else
  11514. #if defined(C89ATOMIC_HAS_8)
  11515. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11516. {
  11517. (void)order;
  11518. return (c89atomic_uint8)_InterlockedExchangeAdd8((volatile char*)dst, (char)src);
  11519. }
  11520. #endif
  11521. #if defined(C89ATOMIC_HAS_16)
  11522. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11523. {
  11524. (void)order;
  11525. return (c89atomic_uint16)_InterlockedExchangeAdd16((volatile short*)dst, (short)src);
  11526. }
  11527. #endif
  11528. #if defined(C89ATOMIC_HAS_32)
  11529. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11530. {
  11531. (void)order;
  11532. return (c89atomic_uint32)_InterlockedExchangeAdd((volatile long*)dst, (long)src);
  11533. }
  11534. #endif
  11535. #if defined(C89ATOMIC_HAS_64) && defined(C89ATOMIC_64BIT)
  11536. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11537. {
  11538. (void)order;
  11539. return (c89atomic_uint64)_InterlockedExchangeAdd64((volatile long long*)dst, (long long)src);
  11540. }
  11541. #else
  11542. #endif
  11543. #endif
  11544. #if defined(C89ATOMIC_HAS_64) && !defined(C89ATOMIC_64BIT)
  11545. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11546. {
  11547. c89atomic_uint64 oldValue;
  11548. c89atomic_uint64 newValue;
  11549. do {
  11550. oldValue = *dst;
  11551. newValue = oldValue + src;
  11552. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11553. (void)order;
  11554. return oldValue;
  11555. }
  11556. #endif
  11557. #if defined(C89ATOMIC_MSVC_USE_INLINED_ASSEMBLY)
  11558. static C89ATOMIC_INLINE void __stdcall c89atomic_thread_fence(c89atomic_memory_order order)
  11559. {
  11560. (void)order;
  11561. __asm {
  11562. lock add [esp], 0
  11563. }
  11564. }
  11565. #else
  11566. #if defined(C89ATOMIC_X64)
  11567. #define c89atomic_thread_fence(order) __faststorefence(), (void)order
  11568. #else
  11569. static C89ATOMIC_INLINE void c89atomic_thread_fence(c89atomic_memory_order order)
  11570. {
  11571. volatile c89atomic_uint32 barrier = 0;
  11572. c89atomic_fetch_add_explicit_32(&barrier, 0, order);
  11573. }
  11574. #endif
  11575. #endif
  11576. #define c89atomic_compiler_fence() c89atomic_thread_fence(c89atomic_memory_order_seq_cst)
  11577. #define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
  11578. #if defined(C89ATOMIC_HAS_8)
  11579. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order)
  11580. {
  11581. (void)order;
  11582. return c89atomic_compare_and_swap_8((volatile c89atomic_uint8*)ptr, 0, 0);
  11583. }
  11584. #endif
  11585. #if defined(C89ATOMIC_HAS_16)
  11586. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order)
  11587. {
  11588. (void)order;
  11589. return c89atomic_compare_and_swap_16((volatile c89atomic_uint16*)ptr, 0, 0);
  11590. }
  11591. #endif
  11592. #if defined(C89ATOMIC_HAS_32)
  11593. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order)
  11594. {
  11595. (void)order;
  11596. return c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)ptr, 0, 0);
  11597. }
  11598. #endif
  11599. #if defined(C89ATOMIC_HAS_64)
  11600. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order)
  11601. {
  11602. (void)order;
  11603. return c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)ptr, 0, 0);
  11604. }
  11605. #endif
  11606. #if defined(C89ATOMIC_HAS_8)
  11607. #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
  11608. #endif
  11609. #if defined(C89ATOMIC_HAS_16)
  11610. #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
  11611. #endif
  11612. #if defined(C89ATOMIC_HAS_32)
  11613. #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
  11614. #endif
  11615. #if defined(C89ATOMIC_HAS_64)
  11616. #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
  11617. #endif
  11618. #if defined(C89ATOMIC_HAS_8)
  11619. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11620. {
  11621. c89atomic_uint8 oldValue;
  11622. c89atomic_uint8 newValue;
  11623. do {
  11624. oldValue = *dst;
  11625. newValue = (c89atomic_uint8)(oldValue - src);
  11626. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11627. (void)order;
  11628. return oldValue;
  11629. }
  11630. #endif
  11631. #if defined(C89ATOMIC_HAS_16)
  11632. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11633. {
  11634. c89atomic_uint16 oldValue;
  11635. c89atomic_uint16 newValue;
  11636. do {
  11637. oldValue = *dst;
  11638. newValue = (c89atomic_uint16)(oldValue - src);
  11639. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11640. (void)order;
  11641. return oldValue;
  11642. }
  11643. #endif
  11644. #if defined(C89ATOMIC_HAS_32)
  11645. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11646. {
  11647. c89atomic_uint32 oldValue;
  11648. c89atomic_uint32 newValue;
  11649. do {
  11650. oldValue = *dst;
  11651. newValue = oldValue - src;
  11652. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11653. (void)order;
  11654. return oldValue;
  11655. }
  11656. #endif
  11657. #if defined(C89ATOMIC_HAS_64)
  11658. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11659. {
  11660. c89atomic_uint64 oldValue;
  11661. c89atomic_uint64 newValue;
  11662. do {
  11663. oldValue = *dst;
  11664. newValue = oldValue - src;
  11665. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11666. (void)order;
  11667. return oldValue;
  11668. }
  11669. #endif
  11670. #if defined(C89ATOMIC_HAS_8)
  11671. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11672. {
  11673. c89atomic_uint8 oldValue;
  11674. c89atomic_uint8 newValue;
  11675. do {
  11676. oldValue = *dst;
  11677. newValue = (c89atomic_uint8)(oldValue & src);
  11678. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11679. (void)order;
  11680. return oldValue;
  11681. }
  11682. #endif
  11683. #if defined(C89ATOMIC_HAS_16)
  11684. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11685. {
  11686. c89atomic_uint16 oldValue;
  11687. c89atomic_uint16 newValue;
  11688. do {
  11689. oldValue = *dst;
  11690. newValue = (c89atomic_uint16)(oldValue & src);
  11691. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11692. (void)order;
  11693. return oldValue;
  11694. }
  11695. #endif
  11696. #if defined(C89ATOMIC_HAS_32)
  11697. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11698. {
  11699. c89atomic_uint32 oldValue;
  11700. c89atomic_uint32 newValue;
  11701. do {
  11702. oldValue = *dst;
  11703. newValue = oldValue & src;
  11704. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11705. (void)order;
  11706. return oldValue;
  11707. }
  11708. #endif
  11709. #if defined(C89ATOMIC_HAS_64)
  11710. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11711. {
  11712. c89atomic_uint64 oldValue;
  11713. c89atomic_uint64 newValue;
  11714. do {
  11715. oldValue = *dst;
  11716. newValue = oldValue & src;
  11717. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11718. (void)order;
  11719. return oldValue;
  11720. }
  11721. #endif
  11722. #if defined(C89ATOMIC_HAS_8)
  11723. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11724. {
  11725. c89atomic_uint8 oldValue;
  11726. c89atomic_uint8 newValue;
  11727. do {
  11728. oldValue = *dst;
  11729. newValue = (c89atomic_uint8)(oldValue ^ src);
  11730. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11731. (void)order;
  11732. return oldValue;
  11733. }
  11734. #endif
  11735. #if defined(C89ATOMIC_HAS_16)
  11736. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11737. {
  11738. c89atomic_uint16 oldValue;
  11739. c89atomic_uint16 newValue;
  11740. do {
  11741. oldValue = *dst;
  11742. newValue = (c89atomic_uint16)(oldValue ^ src);
  11743. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11744. (void)order;
  11745. return oldValue;
  11746. }
  11747. #endif
  11748. #if defined(C89ATOMIC_HAS_32)
  11749. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11750. {
  11751. c89atomic_uint32 oldValue;
  11752. c89atomic_uint32 newValue;
  11753. do {
  11754. oldValue = *dst;
  11755. newValue = oldValue ^ src;
  11756. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11757. (void)order;
  11758. return oldValue;
  11759. }
  11760. #endif
  11761. #if defined(C89ATOMIC_HAS_64)
  11762. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11763. {
  11764. c89atomic_uint64 oldValue;
  11765. c89atomic_uint64 newValue;
  11766. do {
  11767. oldValue = *dst;
  11768. newValue = oldValue ^ src;
  11769. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11770. (void)order;
  11771. return oldValue;
  11772. }
  11773. #endif
  11774. #if defined(C89ATOMIC_HAS_8)
  11775. static C89ATOMIC_INLINE c89atomic_uint8 __stdcall c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11776. {
  11777. c89atomic_uint8 oldValue;
  11778. c89atomic_uint8 newValue;
  11779. do {
  11780. oldValue = *dst;
  11781. newValue = (c89atomic_uint8)(oldValue | src);
  11782. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  11783. (void)order;
  11784. return oldValue;
  11785. }
  11786. #endif
  11787. #if defined(C89ATOMIC_HAS_16)
  11788. static C89ATOMIC_INLINE c89atomic_uint16 __stdcall c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11789. {
  11790. c89atomic_uint16 oldValue;
  11791. c89atomic_uint16 newValue;
  11792. do {
  11793. oldValue = *dst;
  11794. newValue = (c89atomic_uint16)(oldValue | src);
  11795. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  11796. (void)order;
  11797. return oldValue;
  11798. }
  11799. #endif
  11800. #if defined(C89ATOMIC_HAS_32)
  11801. static C89ATOMIC_INLINE c89atomic_uint32 __stdcall c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11802. {
  11803. c89atomic_uint32 oldValue;
  11804. c89atomic_uint32 newValue;
  11805. do {
  11806. oldValue = *dst;
  11807. newValue = oldValue | src;
  11808. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  11809. (void)order;
  11810. return oldValue;
  11811. }
  11812. #endif
  11813. #if defined(C89ATOMIC_HAS_64)
  11814. static C89ATOMIC_INLINE c89atomic_uint64 __stdcall c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11815. {
  11816. c89atomic_uint64 oldValue;
  11817. c89atomic_uint64 newValue;
  11818. do {
  11819. oldValue = *dst;
  11820. newValue = oldValue | src;
  11821. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  11822. (void)order;
  11823. return oldValue;
  11824. }
  11825. #endif
  11826. #if defined(C89ATOMIC_HAS_8)
  11827. #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
  11828. #endif
  11829. #if defined(C89ATOMIC_HAS_16)
  11830. #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
  11831. #endif
  11832. #if defined(C89ATOMIC_HAS_32)
  11833. #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
  11834. #endif
  11835. #if defined(C89ATOMIC_HAS_64)
  11836. #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
  11837. #endif
  11838. #if defined(C89ATOMIC_HAS_8)
  11839. #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
  11840. #endif
  11841. #if defined(C89ATOMIC_HAS_16)
  11842. #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
  11843. #endif
  11844. #if defined(C89ATOMIC_HAS_32)
  11845. #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
  11846. #endif
  11847. #if defined(C89ATOMIC_HAS_64)
  11848. #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
  11849. #endif
  11850. #if defined(C89ATOMIC_HAS_8)
  11851. typedef c89atomic_uint8 c89atomic_flag;
  11852. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order)
  11853. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
  11854. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  11855. #else
  11856. typedef c89atomic_uint32 c89atomic_flag;
  11857. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_32(ptr, order)
  11858. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_32(ptr, order)
  11859. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_32(ptr, order)
  11860. #endif
  11861. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  11862. #define C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE
  11863. #define C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE
  11864. #define c89atomic_memory_order_relaxed __ATOMIC_RELAXED
  11865. #define c89atomic_memory_order_consume __ATOMIC_CONSUME
  11866. #define c89atomic_memory_order_acquire __ATOMIC_ACQUIRE
  11867. #define c89atomic_memory_order_release __ATOMIC_RELEASE
  11868. #define c89atomic_memory_order_acq_rel __ATOMIC_ACQ_REL
  11869. #define c89atomic_memory_order_seq_cst __ATOMIC_SEQ_CST
  11870. #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  11871. #define c89atomic_thread_fence(order) __atomic_thread_fence(order)
  11872. #define c89atomic_signal_fence(order) __atomic_signal_fence(order)
  11873. #define c89atomic_is_lock_free_8(ptr) __atomic_is_lock_free(1, ptr)
  11874. #define c89atomic_is_lock_free_16(ptr) __atomic_is_lock_free(2, ptr)
  11875. #define c89atomic_is_lock_free_32(ptr) __atomic_is_lock_free(4, ptr)
  11876. #define c89atomic_is_lock_free_64(ptr) __atomic_is_lock_free(8, ptr)
  11877. #define c89atomic_test_and_set_explicit_8( dst, order) __atomic_exchange_n(dst, 1, order)
  11878. #define c89atomic_test_and_set_explicit_16(dst, order) __atomic_exchange_n(dst, 1, order)
  11879. #define c89atomic_test_and_set_explicit_32(dst, order) __atomic_exchange_n(dst, 1, order)
  11880. #define c89atomic_test_and_set_explicit_64(dst, order) __atomic_exchange_n(dst, 1, order)
  11881. #define c89atomic_clear_explicit_8( dst, order) __atomic_store_n(dst, 0, order)
  11882. #define c89atomic_clear_explicit_16(dst, order) __atomic_store_n(dst, 0, order)
  11883. #define c89atomic_clear_explicit_32(dst, order) __atomic_store_n(dst, 0, order)
  11884. #define c89atomic_clear_explicit_64(dst, order) __atomic_store_n(dst, 0, order)
  11885. #define c89atomic_store_explicit_8( dst, src, order) __atomic_store_n(dst, src, order)
  11886. #define c89atomic_store_explicit_16(dst, src, order) __atomic_store_n(dst, src, order)
  11887. #define c89atomic_store_explicit_32(dst, src, order) __atomic_store_n(dst, src, order)
  11888. #define c89atomic_store_explicit_64(dst, src, order) __atomic_store_n(dst, src, order)
  11889. #define c89atomic_load_explicit_8( dst, order) __atomic_load_n(dst, order)
  11890. #define c89atomic_load_explicit_16(dst, order) __atomic_load_n(dst, order)
  11891. #define c89atomic_load_explicit_32(dst, order) __atomic_load_n(dst, order)
  11892. #define c89atomic_load_explicit_64(dst, order) __atomic_load_n(dst, order)
  11893. #define c89atomic_exchange_explicit_8( dst, src, order) __atomic_exchange_n(dst, src, order)
  11894. #define c89atomic_exchange_explicit_16(dst, src, order) __atomic_exchange_n(dst, src, order)
  11895. #define c89atomic_exchange_explicit_32(dst, src, order) __atomic_exchange_n(dst, src, order)
  11896. #define c89atomic_exchange_explicit_64(dst, src, order) __atomic_exchange_n(dst, src, order)
  11897. #define c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  11898. #define c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  11899. #define c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  11900. #define c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 0, successOrder, failureOrder)
  11901. #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  11902. #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  11903. #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  11904. #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) __atomic_compare_exchange_n(dst, expected, desired, 1, successOrder, failureOrder)
  11905. #define c89atomic_fetch_add_explicit_8( dst, src, order) __atomic_fetch_add(dst, src, order)
  11906. #define c89atomic_fetch_add_explicit_16(dst, src, order) __atomic_fetch_add(dst, src, order)
  11907. #define c89atomic_fetch_add_explicit_32(dst, src, order) __atomic_fetch_add(dst, src, order)
  11908. #define c89atomic_fetch_add_explicit_64(dst, src, order) __atomic_fetch_add(dst, src, order)
  11909. #define c89atomic_fetch_sub_explicit_8( dst, src, order) __atomic_fetch_sub(dst, src, order)
  11910. #define c89atomic_fetch_sub_explicit_16(dst, src, order) __atomic_fetch_sub(dst, src, order)
  11911. #define c89atomic_fetch_sub_explicit_32(dst, src, order) __atomic_fetch_sub(dst, src, order)
  11912. #define c89atomic_fetch_sub_explicit_64(dst, src, order) __atomic_fetch_sub(dst, src, order)
  11913. #define c89atomic_fetch_or_explicit_8( dst, src, order) __atomic_fetch_or(dst, src, order)
  11914. #define c89atomic_fetch_or_explicit_16(dst, src, order) __atomic_fetch_or(dst, src, order)
  11915. #define c89atomic_fetch_or_explicit_32(dst, src, order) __atomic_fetch_or(dst, src, order)
  11916. #define c89atomic_fetch_or_explicit_64(dst, src, order) __atomic_fetch_or(dst, src, order)
  11917. #define c89atomic_fetch_xor_explicit_8( dst, src, order) __atomic_fetch_xor(dst, src, order)
  11918. #define c89atomic_fetch_xor_explicit_16(dst, src, order) __atomic_fetch_xor(dst, src, order)
  11919. #define c89atomic_fetch_xor_explicit_32(dst, src, order) __atomic_fetch_xor(dst, src, order)
  11920. #define c89atomic_fetch_xor_explicit_64(dst, src, order) __atomic_fetch_xor(dst, src, order)
  11921. #define c89atomic_fetch_and_explicit_8( dst, src, order) __atomic_fetch_and(dst, src, order)
  11922. #define c89atomic_fetch_and_explicit_16(dst, src, order) __atomic_fetch_and(dst, src, order)
  11923. #define c89atomic_fetch_and_explicit_32(dst, src, order) __atomic_fetch_and(dst, src, order)
  11924. #define c89atomic_fetch_and_explicit_64(dst, src, order) __atomic_fetch_and(dst, src, order)
  11925. #define c89atomic_compare_and_swap_8 (dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  11926. #define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  11927. #define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  11928. #define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  11929. typedef c89atomic_uint8 c89atomic_flag;
  11930. #define c89atomic_flag_test_and_set_explicit(dst, order) (c89atomic_bool)__atomic_test_and_set(dst, order)
  11931. #define c89atomic_flag_clear_explicit(dst, order) __atomic_clear(dst, order)
  11932. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  11933. #else
  11934. #define c89atomic_memory_order_relaxed 1
  11935. #define c89atomic_memory_order_consume 2
  11936. #define c89atomic_memory_order_acquire 3
  11937. #define c89atomic_memory_order_release 4
  11938. #define c89atomic_memory_order_acq_rel 5
  11939. #define c89atomic_memory_order_seq_cst 6
  11940. #define c89atomic_compiler_fence() __asm__ __volatile__("":::"memory")
  11941. #if defined(__GNUC__)
  11942. #define c89atomic_thread_fence(order) __sync_synchronize(), (void)order
  11943. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11944. {
  11945. if (order > c89atomic_memory_order_acquire) {
  11946. __sync_synchronize();
  11947. }
  11948. return __sync_lock_test_and_set(dst, src);
  11949. }
  11950. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11951. {
  11952. c89atomic_uint16 oldValue;
  11953. do {
  11954. oldValue = *dst;
  11955. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  11956. (void)order;
  11957. return oldValue;
  11958. }
  11959. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11960. {
  11961. c89atomic_uint32 oldValue;
  11962. do {
  11963. oldValue = *dst;
  11964. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  11965. (void)order;
  11966. return oldValue;
  11967. }
  11968. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11969. {
  11970. c89atomic_uint64 oldValue;
  11971. do {
  11972. oldValue = *dst;
  11973. } while (__sync_val_compare_and_swap(dst, oldValue, src) != oldValue);
  11974. (void)order;
  11975. return oldValue;
  11976. }
  11977. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11978. {
  11979. (void)order;
  11980. return __sync_fetch_and_add(dst, src);
  11981. }
  11982. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  11983. {
  11984. (void)order;
  11985. return __sync_fetch_and_add(dst, src);
  11986. }
  11987. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  11988. {
  11989. (void)order;
  11990. return __sync_fetch_and_add(dst, src);
  11991. }
  11992. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  11993. {
  11994. (void)order;
  11995. return __sync_fetch_and_add(dst, src);
  11996. }
  11997. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  11998. {
  11999. (void)order;
  12000. return __sync_fetch_and_sub(dst, src);
  12001. }
  12002. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12003. {
  12004. (void)order;
  12005. return __sync_fetch_and_sub(dst, src);
  12006. }
  12007. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12008. {
  12009. (void)order;
  12010. return __sync_fetch_and_sub(dst, src);
  12011. }
  12012. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12013. {
  12014. (void)order;
  12015. return __sync_fetch_and_sub(dst, src);
  12016. }
  12017. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12018. {
  12019. (void)order;
  12020. return __sync_fetch_and_or(dst, src);
  12021. }
  12022. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12023. {
  12024. (void)order;
  12025. return __sync_fetch_and_or(dst, src);
  12026. }
  12027. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12028. {
  12029. (void)order;
  12030. return __sync_fetch_and_or(dst, src);
  12031. }
  12032. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12033. {
  12034. (void)order;
  12035. return __sync_fetch_and_or(dst, src);
  12036. }
  12037. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12038. {
  12039. (void)order;
  12040. return __sync_fetch_and_xor(dst, src);
  12041. }
  12042. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12043. {
  12044. (void)order;
  12045. return __sync_fetch_and_xor(dst, src);
  12046. }
  12047. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12048. {
  12049. (void)order;
  12050. return __sync_fetch_and_xor(dst, src);
  12051. }
  12052. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12053. {
  12054. (void)order;
  12055. return __sync_fetch_and_xor(dst, src);
  12056. }
  12057. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12058. {
  12059. (void)order;
  12060. return __sync_fetch_and_and(dst, src);
  12061. }
  12062. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12063. {
  12064. (void)order;
  12065. return __sync_fetch_and_and(dst, src);
  12066. }
  12067. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12068. {
  12069. (void)order;
  12070. return __sync_fetch_and_and(dst, src);
  12071. }
  12072. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12073. {
  12074. (void)order;
  12075. return __sync_fetch_and_and(dst, src);
  12076. }
  12077. #define c89atomic_compare_and_swap_8( dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12078. #define c89atomic_compare_and_swap_16(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12079. #define c89atomic_compare_and_swap_32(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12080. #define c89atomic_compare_and_swap_64(dst, expected, desired) __sync_val_compare_and_swap(dst, expected, desired)
  12081. #else
  12082. #if defined(C89ATOMIC_X86)
  12083. #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addl $0, (%%esp)" ::: "memory", "cc")
  12084. #elif defined(C89ATOMIC_X64)
  12085. #define c89atomic_thread_fence(order) __asm__ __volatile__("lock; addq $0, (%%rsp)" ::: "memory", "cc")
  12086. #else
  12087. #error Unsupported architecture. Please submit a feature request.
  12088. #endif
  12089. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_compare_and_swap_8(volatile c89atomic_uint8* dst, c89atomic_uint8 expected, c89atomic_uint8 desired)
  12090. {
  12091. c89atomic_uint8 result;
  12092. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12093. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12094. #else
  12095. #error Unsupported architecture. Please submit a feature request.
  12096. #endif
  12097. return result;
  12098. }
  12099. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_compare_and_swap_16(volatile c89atomic_uint16* dst, c89atomic_uint16 expected, c89atomic_uint16 desired)
  12100. {
  12101. c89atomic_uint16 result;
  12102. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12103. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12104. #else
  12105. #error Unsupported architecture. Please submit a feature request.
  12106. #endif
  12107. return result;
  12108. }
  12109. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_compare_and_swap_32(volatile c89atomic_uint32* dst, c89atomic_uint32 expected, c89atomic_uint32 desired)
  12110. {
  12111. c89atomic_uint32 result;
  12112. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12113. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12114. #else
  12115. #error Unsupported architecture. Please submit a feature request.
  12116. #endif
  12117. return result;
  12118. }
  12119. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_compare_and_swap_64(volatile c89atomic_uint64* dst, c89atomic_uint64 expected, c89atomic_uint64 desired)
  12120. {
  12121. volatile c89atomic_uint64 result;
  12122. #if defined(C89ATOMIC_X86)
  12123. c89atomic_uint32 resultEAX;
  12124. c89atomic_uint32 resultEDX;
  12125. __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");
  12126. result = ((c89atomic_uint64)resultEDX << 32) | resultEAX;
  12127. #elif defined(C89ATOMIC_X64)
  12128. __asm__ __volatile__("lock; cmpxchg %3, %0" : "+m"(*dst), "=a"(result) : "a"(expected), "d"(desired) : "cc");
  12129. #else
  12130. #error Unsupported architecture. Please submit a feature request.
  12131. #endif
  12132. return result;
  12133. }
  12134. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_exchange_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12135. {
  12136. c89atomic_uint8 result = 0;
  12137. (void)order;
  12138. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12139. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12140. #else
  12141. #error Unsupported architecture. Please submit a feature request.
  12142. #endif
  12143. return result;
  12144. }
  12145. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_exchange_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12146. {
  12147. c89atomic_uint16 result = 0;
  12148. (void)order;
  12149. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12150. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12151. #else
  12152. #error Unsupported architecture. Please submit a feature request.
  12153. #endif
  12154. return result;
  12155. }
  12156. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_exchange_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12157. {
  12158. c89atomic_uint32 result;
  12159. (void)order;
  12160. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12161. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12162. #else
  12163. #error Unsupported architecture. Please submit a feature request.
  12164. #endif
  12165. return result;
  12166. }
  12167. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_exchange_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12168. {
  12169. c89atomic_uint64 result;
  12170. (void)order;
  12171. #if defined(C89ATOMIC_X86)
  12172. do {
  12173. result = *dst;
  12174. } while (c89atomic_compare_and_swap_64(dst, result, src) != result);
  12175. #elif defined(C89ATOMIC_X64)
  12176. __asm__ __volatile__("lock; xchg %1, %0" : "+m"(*dst), "=a"(result) : "a"(src));
  12177. #else
  12178. #error Unsupported architecture. Please submit a feature request.
  12179. #endif
  12180. return result;
  12181. }
  12182. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_add_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12183. {
  12184. c89atomic_uint8 result;
  12185. (void)order;
  12186. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12187. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12188. #else
  12189. #error Unsupported architecture. Please submit a feature request.
  12190. #endif
  12191. return result;
  12192. }
  12193. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_add_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12194. {
  12195. c89atomic_uint16 result;
  12196. (void)order;
  12197. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12198. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12199. #else
  12200. #error Unsupported architecture. Please submit a feature request.
  12201. #endif
  12202. return result;
  12203. }
  12204. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_add_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12205. {
  12206. c89atomic_uint32 result;
  12207. (void)order;
  12208. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12209. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12210. #else
  12211. #error Unsupported architecture. Please submit a feature request.
  12212. #endif
  12213. return result;
  12214. }
  12215. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_add_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12216. {
  12217. #if defined(C89ATOMIC_X86)
  12218. c89atomic_uint64 oldValue;
  12219. c89atomic_uint64 newValue;
  12220. (void)order;
  12221. do {
  12222. oldValue = *dst;
  12223. newValue = oldValue + src;
  12224. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12225. return oldValue;
  12226. #elif defined(C89ATOMIC_X64)
  12227. c89atomic_uint64 result;
  12228. (void)order;
  12229. __asm__ __volatile__("lock; xadd %1, %0" : "+m"(*dst), "=a"(result) : "a"(src) : "cc");
  12230. return result;
  12231. #endif
  12232. }
  12233. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_sub_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12234. {
  12235. c89atomic_uint8 oldValue;
  12236. c89atomic_uint8 newValue;
  12237. do {
  12238. oldValue = *dst;
  12239. newValue = (c89atomic_uint8)(oldValue - src);
  12240. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12241. (void)order;
  12242. return oldValue;
  12243. }
  12244. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_sub_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12245. {
  12246. c89atomic_uint16 oldValue;
  12247. c89atomic_uint16 newValue;
  12248. do {
  12249. oldValue = *dst;
  12250. newValue = (c89atomic_uint16)(oldValue - src);
  12251. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12252. (void)order;
  12253. return oldValue;
  12254. }
  12255. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_sub_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12256. {
  12257. c89atomic_uint32 oldValue;
  12258. c89atomic_uint32 newValue;
  12259. do {
  12260. oldValue = *dst;
  12261. newValue = oldValue - src;
  12262. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12263. (void)order;
  12264. return oldValue;
  12265. }
  12266. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_sub_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12267. {
  12268. c89atomic_uint64 oldValue;
  12269. c89atomic_uint64 newValue;
  12270. do {
  12271. oldValue = *dst;
  12272. newValue = oldValue - src;
  12273. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12274. (void)order;
  12275. return oldValue;
  12276. }
  12277. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_and_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12278. {
  12279. c89atomic_uint8 oldValue;
  12280. c89atomic_uint8 newValue;
  12281. do {
  12282. oldValue = *dst;
  12283. newValue = (c89atomic_uint8)(oldValue & src);
  12284. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12285. (void)order;
  12286. return oldValue;
  12287. }
  12288. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_and_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12289. {
  12290. c89atomic_uint16 oldValue;
  12291. c89atomic_uint16 newValue;
  12292. do {
  12293. oldValue = *dst;
  12294. newValue = (c89atomic_uint16)(oldValue & src);
  12295. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12296. (void)order;
  12297. return oldValue;
  12298. }
  12299. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_and_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12300. {
  12301. c89atomic_uint32 oldValue;
  12302. c89atomic_uint32 newValue;
  12303. do {
  12304. oldValue = *dst;
  12305. newValue = oldValue & src;
  12306. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12307. (void)order;
  12308. return oldValue;
  12309. }
  12310. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_and_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12311. {
  12312. c89atomic_uint64 oldValue;
  12313. c89atomic_uint64 newValue;
  12314. do {
  12315. oldValue = *dst;
  12316. newValue = oldValue & src;
  12317. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12318. (void)order;
  12319. return oldValue;
  12320. }
  12321. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_xor_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12322. {
  12323. c89atomic_uint8 oldValue;
  12324. c89atomic_uint8 newValue;
  12325. do {
  12326. oldValue = *dst;
  12327. newValue = (c89atomic_uint8)(oldValue ^ src);
  12328. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12329. (void)order;
  12330. return oldValue;
  12331. }
  12332. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_xor_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12333. {
  12334. c89atomic_uint16 oldValue;
  12335. c89atomic_uint16 newValue;
  12336. do {
  12337. oldValue = *dst;
  12338. newValue = (c89atomic_uint16)(oldValue ^ src);
  12339. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12340. (void)order;
  12341. return oldValue;
  12342. }
  12343. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_xor_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12344. {
  12345. c89atomic_uint32 oldValue;
  12346. c89atomic_uint32 newValue;
  12347. do {
  12348. oldValue = *dst;
  12349. newValue = oldValue ^ src;
  12350. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12351. (void)order;
  12352. return oldValue;
  12353. }
  12354. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_xor_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12355. {
  12356. c89atomic_uint64 oldValue;
  12357. c89atomic_uint64 newValue;
  12358. do {
  12359. oldValue = *dst;
  12360. newValue = oldValue ^ src;
  12361. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12362. (void)order;
  12363. return oldValue;
  12364. }
  12365. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_fetch_or_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8 src, c89atomic_memory_order order)
  12366. {
  12367. c89atomic_uint8 oldValue;
  12368. c89atomic_uint8 newValue;
  12369. do {
  12370. oldValue = *dst;
  12371. newValue = (c89atomic_uint8)(oldValue | src);
  12372. } while (c89atomic_compare_and_swap_8(dst, oldValue, newValue) != oldValue);
  12373. (void)order;
  12374. return oldValue;
  12375. }
  12376. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_fetch_or_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16 src, c89atomic_memory_order order)
  12377. {
  12378. c89atomic_uint16 oldValue;
  12379. c89atomic_uint16 newValue;
  12380. do {
  12381. oldValue = *dst;
  12382. newValue = (c89atomic_uint16)(oldValue | src);
  12383. } while (c89atomic_compare_and_swap_16(dst, oldValue, newValue) != oldValue);
  12384. (void)order;
  12385. return oldValue;
  12386. }
  12387. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_fetch_or_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32 src, c89atomic_memory_order order)
  12388. {
  12389. c89atomic_uint32 oldValue;
  12390. c89atomic_uint32 newValue;
  12391. do {
  12392. oldValue = *dst;
  12393. newValue = oldValue | src;
  12394. } while (c89atomic_compare_and_swap_32(dst, oldValue, newValue) != oldValue);
  12395. (void)order;
  12396. return oldValue;
  12397. }
  12398. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_fetch_or_explicit_64(volatile c89atomic_uint64* dst, c89atomic_uint64 src, c89atomic_memory_order order)
  12399. {
  12400. c89atomic_uint64 oldValue;
  12401. c89atomic_uint64 newValue;
  12402. do {
  12403. oldValue = *dst;
  12404. newValue = oldValue | src;
  12405. } while (c89atomic_compare_and_swap_64(dst, oldValue, newValue) != oldValue);
  12406. (void)order;
  12407. return oldValue;
  12408. }
  12409. #endif
  12410. #define c89atomic_signal_fence(order) c89atomic_thread_fence(order)
  12411. static C89ATOMIC_INLINE c89atomic_uint8 c89atomic_load_explicit_8(volatile const c89atomic_uint8* ptr, c89atomic_memory_order order)
  12412. {
  12413. (void)order;
  12414. return c89atomic_compare_and_swap_8((c89atomic_uint8*)ptr, 0, 0);
  12415. }
  12416. static C89ATOMIC_INLINE c89atomic_uint16 c89atomic_load_explicit_16(volatile const c89atomic_uint16* ptr, c89atomic_memory_order order)
  12417. {
  12418. (void)order;
  12419. return c89atomic_compare_and_swap_16((c89atomic_uint16*)ptr, 0, 0);
  12420. }
  12421. static C89ATOMIC_INLINE c89atomic_uint32 c89atomic_load_explicit_32(volatile const c89atomic_uint32* ptr, c89atomic_memory_order order)
  12422. {
  12423. (void)order;
  12424. return c89atomic_compare_and_swap_32((c89atomic_uint32*)ptr, 0, 0);
  12425. }
  12426. static C89ATOMIC_INLINE c89atomic_uint64 c89atomic_load_explicit_64(volatile const c89atomic_uint64* ptr, c89atomic_memory_order order)
  12427. {
  12428. (void)order;
  12429. return c89atomic_compare_and_swap_64((c89atomic_uint64*)ptr, 0, 0);
  12430. }
  12431. #define c89atomic_store_explicit_8( dst, src, order) (void)c89atomic_exchange_explicit_8 (dst, src, order)
  12432. #define c89atomic_store_explicit_16(dst, src, order) (void)c89atomic_exchange_explicit_16(dst, src, order)
  12433. #define c89atomic_store_explicit_32(dst, src, order) (void)c89atomic_exchange_explicit_32(dst, src, order)
  12434. #define c89atomic_store_explicit_64(dst, src, order) (void)c89atomic_exchange_explicit_64(dst, src, order)
  12435. #define c89atomic_test_and_set_explicit_8( dst, order) c89atomic_exchange_explicit_8 (dst, 1, order)
  12436. #define c89atomic_test_and_set_explicit_16(dst, order) c89atomic_exchange_explicit_16(dst, 1, order)
  12437. #define c89atomic_test_and_set_explicit_32(dst, order) c89atomic_exchange_explicit_32(dst, 1, order)
  12438. #define c89atomic_test_and_set_explicit_64(dst, order) c89atomic_exchange_explicit_64(dst, 1, order)
  12439. #define c89atomic_clear_explicit_8( dst, order) c89atomic_store_explicit_8 (dst, 0, order)
  12440. #define c89atomic_clear_explicit_16(dst, order) c89atomic_store_explicit_16(dst, 0, order)
  12441. #define c89atomic_clear_explicit_32(dst, order) c89atomic_store_explicit_32(dst, 0, order)
  12442. #define c89atomic_clear_explicit_64(dst, order) c89atomic_store_explicit_64(dst, 0, order)
  12443. typedef c89atomic_uint8 c89atomic_flag;
  12444. #define c89atomic_flag_test_and_set_explicit(ptr, order) (c89atomic_bool)c89atomic_test_and_set_explicit_8(ptr, order)
  12445. #define c89atomic_flag_clear_explicit(ptr, order) c89atomic_clear_explicit_8(ptr, order)
  12446. #define c89atoimc_flag_load_explicit(ptr, order) c89atomic_load_explicit_8(ptr, order)
  12447. #endif
  12448. #if !defined(C89ATOMIC_HAS_NATIVE_COMPARE_EXCHANGE)
  12449. #if defined(C89ATOMIC_HAS_8)
  12450. c89atomic_bool c89atomic_compare_exchange_strong_explicit_8(volatile c89atomic_uint8* dst, c89atomic_uint8* expected, c89atomic_uint8 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12451. {
  12452. c89atomic_uint8 expectedValue;
  12453. c89atomic_uint8 result;
  12454. (void)successOrder;
  12455. (void)failureOrder;
  12456. expectedValue = c89atomic_load_explicit_8(expected, c89atomic_memory_order_seq_cst);
  12457. result = c89atomic_compare_and_swap_8(dst, expectedValue, desired);
  12458. if (result == expectedValue) {
  12459. return 1;
  12460. } else {
  12461. c89atomic_store_explicit_8(expected, result, failureOrder);
  12462. return 0;
  12463. }
  12464. }
  12465. #endif
  12466. #if defined(C89ATOMIC_HAS_16)
  12467. c89atomic_bool c89atomic_compare_exchange_strong_explicit_16(volatile c89atomic_uint16* dst, c89atomic_uint16* expected, c89atomic_uint16 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12468. {
  12469. c89atomic_uint16 expectedValue;
  12470. c89atomic_uint16 result;
  12471. (void)successOrder;
  12472. (void)failureOrder;
  12473. expectedValue = c89atomic_load_explicit_16(expected, c89atomic_memory_order_seq_cst);
  12474. result = c89atomic_compare_and_swap_16(dst, expectedValue, desired);
  12475. if (result == expectedValue) {
  12476. return 1;
  12477. } else {
  12478. c89atomic_store_explicit_16(expected, result, failureOrder);
  12479. return 0;
  12480. }
  12481. }
  12482. #endif
  12483. #if defined(C89ATOMIC_HAS_32)
  12484. c89atomic_bool c89atomic_compare_exchange_strong_explicit_32(volatile c89atomic_uint32* dst, c89atomic_uint32* expected, c89atomic_uint32 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12485. {
  12486. c89atomic_uint32 expectedValue;
  12487. c89atomic_uint32 result;
  12488. (void)successOrder;
  12489. (void)failureOrder;
  12490. expectedValue = c89atomic_load_explicit_32(expected, c89atomic_memory_order_seq_cst);
  12491. result = c89atomic_compare_and_swap_32(dst, expectedValue, desired);
  12492. if (result == expectedValue) {
  12493. return 1;
  12494. } else {
  12495. c89atomic_store_explicit_32(expected, result, failureOrder);
  12496. return 0;
  12497. }
  12498. }
  12499. #endif
  12500. #if defined(C89ATOMIC_HAS_64)
  12501. c89atomic_bool c89atomic_compare_exchange_strong_explicit_64(volatile c89atomic_uint64* dst, volatile c89atomic_uint64* expected, c89atomic_uint64 desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12502. {
  12503. c89atomic_uint64 expectedValue;
  12504. c89atomic_uint64 result;
  12505. (void)successOrder;
  12506. (void)failureOrder;
  12507. expectedValue = c89atomic_load_explicit_64(expected, c89atomic_memory_order_seq_cst);
  12508. result = c89atomic_compare_and_swap_64(dst, expectedValue, desired);
  12509. if (result == expectedValue) {
  12510. return 1;
  12511. } else {
  12512. c89atomic_store_explicit_64(expected, result, failureOrder);
  12513. return 0;
  12514. }
  12515. }
  12516. #endif
  12517. #define c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8 (dst, expected, desired, successOrder, failureOrder)
  12518. #define c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, successOrder, failureOrder)
  12519. #define c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, successOrder, failureOrder)
  12520. #define c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, successOrder, failureOrder)
  12521. #endif
  12522. #if !defined(C89ATOMIC_HAS_NATIVE_IS_LOCK_FREE)
  12523. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_8(volatile void* ptr)
  12524. {
  12525. (void)ptr;
  12526. return 1;
  12527. }
  12528. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_16(volatile void* ptr)
  12529. {
  12530. (void)ptr;
  12531. return 1;
  12532. }
  12533. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_32(volatile void* ptr)
  12534. {
  12535. (void)ptr;
  12536. return 1;
  12537. }
  12538. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_64(volatile void* ptr)
  12539. {
  12540. (void)ptr;
  12541. #if defined(C89ATOMIC_64BIT)
  12542. return 1;
  12543. #else
  12544. #if defined(C89ATOMIC_X86) || defined(C89ATOMIC_X64)
  12545. return 1;
  12546. #else
  12547. return 0;
  12548. #endif
  12549. #endif
  12550. }
  12551. #endif
  12552. #if defined(C89ATOMIC_64BIT)
  12553. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
  12554. {
  12555. return c89atomic_is_lock_free_64((volatile c89atomic_uint64*)ptr);
  12556. }
  12557. static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
  12558. {
  12559. return (void*)c89atomic_load_explicit_64((volatile c89atomic_uint64*)ptr, order);
  12560. }
  12561. static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12562. {
  12563. c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
  12564. }
  12565. static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12566. {
  12567. return (void*)c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)src, order);
  12568. }
  12569. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12570. {
  12571. return c89atomic_compare_exchange_strong_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
  12572. }
  12573. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12574. {
  12575. return c89atomic_compare_exchange_weak_explicit_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder);
  12576. }
  12577. static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12578. {
  12579. return (void*)c89atomic_compare_and_swap_64((volatile c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)desired);
  12580. }
  12581. #elif defined(C89ATOMIC_32BIT)
  12582. static C89ATOMIC_INLINE c89atomic_bool c89atomic_is_lock_free_ptr(volatile void** ptr)
  12583. {
  12584. return c89atomic_is_lock_free_32((volatile c89atomic_uint32*)ptr);
  12585. }
  12586. static C89ATOMIC_INLINE void* c89atomic_load_explicit_ptr(volatile void** ptr, c89atomic_memory_order order)
  12587. {
  12588. return (void*)c89atomic_load_explicit_32((volatile c89atomic_uint32*)ptr, order);
  12589. }
  12590. static C89ATOMIC_INLINE void c89atomic_store_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12591. {
  12592. c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
  12593. }
  12594. static C89ATOMIC_INLINE void* c89atomic_exchange_explicit_ptr(volatile void** dst, void* src, c89atomic_memory_order order)
  12595. {
  12596. return (void*)c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)src, order);
  12597. }
  12598. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_strong_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12599. {
  12600. return c89atomic_compare_exchange_strong_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
  12601. }
  12602. static C89ATOMIC_INLINE c89atomic_bool c89atomic_compare_exchange_weak_explicit_ptr(volatile void** dst, void** expected, void* desired, c89atomic_memory_order successOrder, c89atomic_memory_order failureOrder)
  12603. {
  12604. return c89atomic_compare_exchange_weak_explicit_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder);
  12605. }
  12606. static C89ATOMIC_INLINE void* c89atomic_compare_and_swap_ptr(volatile void** dst, void* expected, void* desired)
  12607. {
  12608. return (void*)c89atomic_compare_and_swap_32((volatile c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)desired);
  12609. }
  12610. #else
  12611. #error Unsupported architecture.
  12612. #endif
  12613. #define c89atomic_flag_test_and_set(ptr) c89atomic_flag_test_and_set_explicit(ptr, c89atomic_memory_order_seq_cst)
  12614. #define c89atomic_flag_clear(ptr) c89atomic_flag_clear_explicit(ptr, c89atomic_memory_order_seq_cst)
  12615. #define c89atomic_store_ptr(dst, src) c89atomic_store_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
  12616. #define c89atomic_load_ptr(ptr) c89atomic_load_explicit_ptr((volatile void**)ptr, c89atomic_memory_order_seq_cst)
  12617. #define c89atomic_exchange_ptr(dst, src) c89atomic_exchange_explicit_ptr((volatile void**)dst, (void*)src, c89atomic_memory_order_seq_cst)
  12618. #define c89atomic_compare_exchange_strong_ptr(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12619. #define c89atomic_compare_exchange_weak_ptr(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_ptr((volatile void**)dst, (void**)expected, (void*)desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12620. #define c89atomic_test_and_set_8( ptr) c89atomic_test_and_set_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  12621. #define c89atomic_test_and_set_16(ptr) c89atomic_test_and_set_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  12622. #define c89atomic_test_and_set_32(ptr) c89atomic_test_and_set_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  12623. #define c89atomic_test_and_set_64(ptr) c89atomic_test_and_set_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  12624. #define c89atomic_clear_8( ptr) c89atomic_clear_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  12625. #define c89atomic_clear_16(ptr) c89atomic_clear_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  12626. #define c89atomic_clear_32(ptr) c89atomic_clear_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  12627. #define c89atomic_clear_64(ptr) c89atomic_clear_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  12628. #define c89atomic_store_8( dst, src) c89atomic_store_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12629. #define c89atomic_store_16(dst, src) c89atomic_store_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12630. #define c89atomic_store_32(dst, src) c89atomic_store_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12631. #define c89atomic_store_64(dst, src) c89atomic_store_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12632. #define c89atomic_load_8( ptr) c89atomic_load_explicit_8( ptr, c89atomic_memory_order_seq_cst)
  12633. #define c89atomic_load_16(ptr) c89atomic_load_explicit_16(ptr, c89atomic_memory_order_seq_cst)
  12634. #define c89atomic_load_32(ptr) c89atomic_load_explicit_32(ptr, c89atomic_memory_order_seq_cst)
  12635. #define c89atomic_load_64(ptr) c89atomic_load_explicit_64(ptr, c89atomic_memory_order_seq_cst)
  12636. #define c89atomic_exchange_8( dst, src) c89atomic_exchange_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12637. #define c89atomic_exchange_16(dst, src) c89atomic_exchange_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12638. #define c89atomic_exchange_32(dst, src) c89atomic_exchange_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12639. #define c89atomic_exchange_64(dst, src) c89atomic_exchange_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12640. #define c89atomic_compare_exchange_strong_8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12641. #define c89atomic_compare_exchange_strong_16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12642. #define c89atomic_compare_exchange_strong_32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12643. #define c89atomic_compare_exchange_strong_64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12644. #define c89atomic_compare_exchange_weak_8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12645. #define c89atomic_compare_exchange_weak_16( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12646. #define c89atomic_compare_exchange_weak_32( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12647. #define c89atomic_compare_exchange_weak_64( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12648. #define c89atomic_fetch_add_8( dst, src) c89atomic_fetch_add_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12649. #define c89atomic_fetch_add_16(dst, src) c89atomic_fetch_add_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12650. #define c89atomic_fetch_add_32(dst, src) c89atomic_fetch_add_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12651. #define c89atomic_fetch_add_64(dst, src) c89atomic_fetch_add_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12652. #define c89atomic_fetch_sub_8( dst, src) c89atomic_fetch_sub_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12653. #define c89atomic_fetch_sub_16(dst, src) c89atomic_fetch_sub_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12654. #define c89atomic_fetch_sub_32(dst, src) c89atomic_fetch_sub_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12655. #define c89atomic_fetch_sub_64(dst, src) c89atomic_fetch_sub_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12656. #define c89atomic_fetch_or_8( dst, src) c89atomic_fetch_or_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12657. #define c89atomic_fetch_or_16(dst, src) c89atomic_fetch_or_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12658. #define c89atomic_fetch_or_32(dst, src) c89atomic_fetch_or_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12659. #define c89atomic_fetch_or_64(dst, src) c89atomic_fetch_or_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12660. #define c89atomic_fetch_xor_8( dst, src) c89atomic_fetch_xor_explicit_8( dst, src, c89atomic_memory_order_seq_cst)
  12661. #define c89atomic_fetch_xor_16(dst, src) c89atomic_fetch_xor_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12662. #define c89atomic_fetch_xor_32(dst, src) c89atomic_fetch_xor_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12663. #define c89atomic_fetch_xor_64(dst, src) c89atomic_fetch_xor_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12664. #define c89atomic_fetch_and_8( dst, src) c89atomic_fetch_and_explicit_8 (dst, src, c89atomic_memory_order_seq_cst)
  12665. #define c89atomic_fetch_and_16(dst, src) c89atomic_fetch_and_explicit_16(dst, src, c89atomic_memory_order_seq_cst)
  12666. #define c89atomic_fetch_and_32(dst, src) c89atomic_fetch_and_explicit_32(dst, src, c89atomic_memory_order_seq_cst)
  12667. #define c89atomic_fetch_and_64(dst, src) c89atomic_fetch_and_explicit_64(dst, src, c89atomic_memory_order_seq_cst)
  12668. #define c89atomic_test_and_set_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_test_and_set_explicit_8( (c89atomic_uint8* )ptr, order)
  12669. #define c89atomic_test_and_set_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_test_and_set_explicit_16((c89atomic_uint16*)ptr, order)
  12670. #define c89atomic_test_and_set_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_test_and_set_explicit_32((c89atomic_uint32*)ptr, order)
  12671. #define c89atomic_test_and_set_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_test_and_set_explicit_64((c89atomic_uint64*)ptr, order)
  12672. #define c89atomic_clear_explicit_i8( ptr, order) c89atomic_clear_explicit_8( (c89atomic_uint8* )ptr, order)
  12673. #define c89atomic_clear_explicit_i16(ptr, order) c89atomic_clear_explicit_16((c89atomic_uint16*)ptr, order)
  12674. #define c89atomic_clear_explicit_i32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
  12675. #define c89atomic_clear_explicit_i64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
  12676. #define c89atomic_store_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_store_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12677. #define c89atomic_store_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_store_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12678. #define c89atomic_store_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_store_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12679. #define c89atomic_store_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_store_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12680. #define c89atomic_load_explicit_i8( ptr, order) (c89atomic_int8 )c89atomic_load_explicit_8( (c89atomic_uint8* )ptr, order)
  12681. #define c89atomic_load_explicit_i16(ptr, order) (c89atomic_int16)c89atomic_load_explicit_16((c89atomic_uint16*)ptr, order)
  12682. #define c89atomic_load_explicit_i32(ptr, order) (c89atomic_int32)c89atomic_load_explicit_32((c89atomic_uint32*)ptr, order)
  12683. #define c89atomic_load_explicit_i64(ptr, order) (c89atomic_int64)c89atomic_load_explicit_64((c89atomic_uint64*)ptr, order)
  12684. #define c89atomic_exchange_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_exchange_explicit_8 ((c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12685. #define c89atomic_exchange_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_exchange_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12686. #define c89atomic_exchange_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_exchange_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12687. #define c89atomic_exchange_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_exchange_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12688. #define c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
  12689. #define c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
  12690. #define c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
  12691. #define c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_strong_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
  12692. #define c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8* )expected, (c89atomic_uint8 )desired, successOrder, failureOrder)
  12693. #define c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16*)expected, (c89atomic_uint16)desired, successOrder, failureOrder)
  12694. #define c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32*)expected, (c89atomic_uint32)desired, successOrder, failureOrder)
  12695. #define c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, successOrder, failureOrder) c89atomic_compare_exchange_weak_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64*)expected, (c89atomic_uint64)desired, successOrder, failureOrder)
  12696. #define c89atomic_fetch_add_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_add_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12697. #define c89atomic_fetch_add_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_add_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12698. #define c89atomic_fetch_add_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_add_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12699. #define c89atomic_fetch_add_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_add_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12700. #define c89atomic_fetch_sub_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_sub_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12701. #define c89atomic_fetch_sub_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_sub_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12702. #define c89atomic_fetch_sub_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_sub_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12703. #define c89atomic_fetch_sub_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_sub_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12704. #define c89atomic_fetch_or_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_or_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12705. #define c89atomic_fetch_or_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_or_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12706. #define c89atomic_fetch_or_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_or_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12707. #define c89atomic_fetch_or_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_or_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12708. #define c89atomic_fetch_xor_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_xor_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12709. #define c89atomic_fetch_xor_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_xor_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12710. #define c89atomic_fetch_xor_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_xor_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12711. #define c89atomic_fetch_xor_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_xor_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12712. #define c89atomic_fetch_and_explicit_i8( dst, src, order) (c89atomic_int8 )c89atomic_fetch_and_explicit_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )src, order)
  12713. #define c89atomic_fetch_and_explicit_i16(dst, src, order) (c89atomic_int16)c89atomic_fetch_and_explicit_16((c89atomic_uint16*)dst, (c89atomic_uint16)src, order)
  12714. #define c89atomic_fetch_and_explicit_i32(dst, src, order) (c89atomic_int32)c89atomic_fetch_and_explicit_32((c89atomic_uint32*)dst, (c89atomic_uint32)src, order)
  12715. #define c89atomic_fetch_and_explicit_i64(dst, src, order) (c89atomic_int64)c89atomic_fetch_and_explicit_64((c89atomic_uint64*)dst, (c89atomic_uint64)src, order)
  12716. #define c89atomic_test_and_set_i8( ptr) c89atomic_test_and_set_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  12717. #define c89atomic_test_and_set_i16(ptr) c89atomic_test_and_set_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  12718. #define c89atomic_test_and_set_i32(ptr) c89atomic_test_and_set_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  12719. #define c89atomic_test_and_set_i64(ptr) c89atomic_test_and_set_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  12720. #define c89atomic_clear_i8( ptr) c89atomic_clear_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  12721. #define c89atomic_clear_i16(ptr) c89atomic_clear_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  12722. #define c89atomic_clear_i32(ptr) c89atomic_clear_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  12723. #define c89atomic_clear_i64(ptr) c89atomic_clear_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  12724. #define c89atomic_store_i8( dst, src) c89atomic_store_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12725. #define c89atomic_store_i16(dst, src) c89atomic_store_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12726. #define c89atomic_store_i32(dst, src) c89atomic_store_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12727. #define c89atomic_store_i64(dst, src) c89atomic_store_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12728. #define c89atomic_load_i8( ptr) c89atomic_load_explicit_i8( ptr, c89atomic_memory_order_seq_cst)
  12729. #define c89atomic_load_i16(ptr) c89atomic_load_explicit_i16(ptr, c89atomic_memory_order_seq_cst)
  12730. #define c89atomic_load_i32(ptr) c89atomic_load_explicit_i32(ptr, c89atomic_memory_order_seq_cst)
  12731. #define c89atomic_load_i64(ptr) c89atomic_load_explicit_i64(ptr, c89atomic_memory_order_seq_cst)
  12732. #define c89atomic_exchange_i8( dst, src) c89atomic_exchange_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12733. #define c89atomic_exchange_i16(dst, src) c89atomic_exchange_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12734. #define c89atomic_exchange_i32(dst, src) c89atomic_exchange_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12735. #define c89atomic_exchange_i64(dst, src) c89atomic_exchange_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12736. #define c89atomic_compare_exchange_strong_i8( dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12737. #define c89atomic_compare_exchange_strong_i16(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12738. #define c89atomic_compare_exchange_strong_i32(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12739. #define c89atomic_compare_exchange_strong_i64(dst, expected, desired) c89atomic_compare_exchange_strong_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12740. #define c89atomic_compare_exchange_weak_i8( dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i8( dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12741. #define c89atomic_compare_exchange_weak_i16(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i16(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12742. #define c89atomic_compare_exchange_weak_i32(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i32(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12743. #define c89atomic_compare_exchange_weak_i64(dst, expected, desired) c89atomic_compare_exchange_weak_explicit_i64(dst, expected, desired, c89atomic_memory_order_seq_cst, c89atomic_memory_order_seq_cst)
  12744. #define c89atomic_fetch_add_i8( dst, src) c89atomic_fetch_add_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12745. #define c89atomic_fetch_add_i16(dst, src) c89atomic_fetch_add_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12746. #define c89atomic_fetch_add_i32(dst, src) c89atomic_fetch_add_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12747. #define c89atomic_fetch_add_i64(dst, src) c89atomic_fetch_add_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12748. #define c89atomic_fetch_sub_i8( dst, src) c89atomic_fetch_sub_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12749. #define c89atomic_fetch_sub_i16(dst, src) c89atomic_fetch_sub_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12750. #define c89atomic_fetch_sub_i32(dst, src) c89atomic_fetch_sub_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12751. #define c89atomic_fetch_sub_i64(dst, src) c89atomic_fetch_sub_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12752. #define c89atomic_fetch_or_i8( dst, src) c89atomic_fetch_or_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12753. #define c89atomic_fetch_or_i16(dst, src) c89atomic_fetch_or_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12754. #define c89atomic_fetch_or_i32(dst, src) c89atomic_fetch_or_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12755. #define c89atomic_fetch_or_i64(dst, src) c89atomic_fetch_or_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12756. #define c89atomic_fetch_xor_i8( dst, src) c89atomic_fetch_xor_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12757. #define c89atomic_fetch_xor_i16(dst, src) c89atomic_fetch_xor_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12758. #define c89atomic_fetch_xor_i32(dst, src) c89atomic_fetch_xor_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12759. #define c89atomic_fetch_xor_i64(dst, src) c89atomic_fetch_xor_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12760. #define c89atomic_fetch_and_i8( dst, src) c89atomic_fetch_and_explicit_i8( dst, src, c89atomic_memory_order_seq_cst)
  12761. #define c89atomic_fetch_and_i16(dst, src) c89atomic_fetch_and_explicit_i16(dst, src, c89atomic_memory_order_seq_cst)
  12762. #define c89atomic_fetch_and_i32(dst, src) c89atomic_fetch_and_explicit_i32(dst, src, c89atomic_memory_order_seq_cst)
  12763. #define c89atomic_fetch_and_i64(dst, src) c89atomic_fetch_and_explicit_i64(dst, src, c89atomic_memory_order_seq_cst)
  12764. #define c89atomic_compare_and_swap_i8( dst, expected, dedsired) (c89atomic_int8 )c89atomic_compare_and_swap_8( (c89atomic_uint8* )dst, (c89atomic_uint8 )expected, (c89atomic_uint8 )dedsired)
  12765. #define c89atomic_compare_and_swap_i16(dst, expected, dedsired) (c89atomic_int16)c89atomic_compare_and_swap_16((c89atomic_uint16*)dst, (c89atomic_uint16)expected, (c89atomic_uint16)dedsired)
  12766. #define c89atomic_compare_and_swap_i32(dst, expected, dedsired) (c89atomic_int32)c89atomic_compare_and_swap_32((c89atomic_uint32*)dst, (c89atomic_uint32)expected, (c89atomic_uint32)dedsired)
  12767. #define c89atomic_compare_and_swap_i64(dst, expected, dedsired) (c89atomic_int64)c89atomic_compare_and_swap_64((c89atomic_uint64*)dst, (c89atomic_uint64)expected, (c89atomic_uint64)dedsired)
  12768. typedef union
  12769. {
  12770. c89atomic_uint32 i;
  12771. float f;
  12772. } c89atomic_if32;
  12773. typedef union
  12774. {
  12775. c89atomic_uint64 i;
  12776. double f;
  12777. } c89atomic_if64;
  12778. #define c89atomic_clear_explicit_f32(ptr, order) c89atomic_clear_explicit_32((c89atomic_uint32*)ptr, order)
  12779. #define c89atomic_clear_explicit_f64(ptr, order) c89atomic_clear_explicit_64((c89atomic_uint64*)ptr, order)
  12780. static C89ATOMIC_INLINE void c89atomic_store_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  12781. {
  12782. c89atomic_if32 x;
  12783. x.f = src;
  12784. c89atomic_store_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  12785. }
  12786. static C89ATOMIC_INLINE void c89atomic_store_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  12787. {
  12788. c89atomic_if64 x;
  12789. x.f = src;
  12790. c89atomic_store_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  12791. }
  12792. static C89ATOMIC_INLINE float c89atomic_load_explicit_f32(volatile const float* ptr, c89atomic_memory_order order)
  12793. {
  12794. c89atomic_if32 r;
  12795. r.i = c89atomic_load_explicit_32((volatile const c89atomic_uint32*)ptr, order);
  12796. return r.f;
  12797. }
  12798. static C89ATOMIC_INLINE double c89atomic_load_explicit_f64(volatile const double* ptr, c89atomic_memory_order order)
  12799. {
  12800. c89atomic_if64 r;
  12801. r.i = c89atomic_load_explicit_64((volatile const c89atomic_uint64*)ptr, order);
  12802. return r.f;
  12803. }
  12804. static C89ATOMIC_INLINE float c89atomic_exchange_explicit_f32(volatile float* dst, float src, c89atomic_memory_order order)
  12805. {
  12806. c89atomic_if32 r;
  12807. c89atomic_if32 x;
  12808. x.f = src;
  12809. r.i = c89atomic_exchange_explicit_32((volatile c89atomic_uint32*)dst, x.i, order);
  12810. return r.f;
  12811. }
  12812. static C89ATOMIC_INLINE double c89atomic_exchange_explicit_f64(volatile double* dst, double src, c89atomic_memory_order order)
  12813. {
  12814. c89atomic_if64 r;
  12815. c89atomic_if64 x;
  12816. x.f = src;
  12817. r.i = c89atomic_exchange_explicit_64((volatile c89atomic_uint64*)dst, x.i, order);
  12818. return r.f;
  12819. }
  12820. #define c89atomic_clear_f32(ptr) (float )c89atomic_clear_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
  12821. #define c89atomic_clear_f64(ptr) (double)c89atomic_clear_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
  12822. #define c89atomic_store_f32(dst, src) c89atomic_store_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  12823. #define c89atomic_store_f64(dst, src) c89atomic_store_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  12824. #define c89atomic_load_f32(ptr) (float )c89atomic_load_explicit_f32(ptr, c89atomic_memory_order_seq_cst)
  12825. #define c89atomic_load_f64(ptr) (double)c89atomic_load_explicit_f64(ptr, c89atomic_memory_order_seq_cst)
  12826. #define c89atomic_exchange_f32(dst, src) (float )c89atomic_exchange_explicit_f32(dst, src, c89atomic_memory_order_seq_cst)
  12827. #define c89atomic_exchange_f64(dst, src) (double)c89atomic_exchange_explicit_f64(dst, src, c89atomic_memory_order_seq_cst)
  12828. typedef c89atomic_flag c89atomic_spinlock;
  12829. static C89ATOMIC_INLINE void c89atomic_spinlock_lock(volatile c89atomic_spinlock* pSpinlock)
  12830. {
  12831. for (;;) {
  12832. if (c89atomic_flag_test_and_set_explicit(pSpinlock, c89atomic_memory_order_acquire) == 0) {
  12833. break;
  12834. }
  12835. while (c89atoimc_flag_load_explicit(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
  12836. }
  12837. }
  12838. }
  12839. static C89ATOMIC_INLINE void c89atomic_spinlock_unlock(volatile c89atomic_spinlock* pSpinlock)
  12840. {
  12841. c89atomic_flag_clear_explicit(pSpinlock, c89atomic_memory_order_release);
  12842. }
  12843. #if defined(__cplusplus)
  12844. }
  12845. #endif
  12846. #endif
  12847. /* c89atomic.h end */
  12848. MA_API ma_uint64 ma_calculate_frame_count_after_resampling(ma_uint32 sampleRateOut, ma_uint32 sampleRateIn, ma_uint64 frameCountIn)
  12849. {
  12850. /* This is based on the calculation in ma_linear_resampler_get_expected_output_frame_count(). */
  12851. ma_uint64 outputFrameCount;
  12852. ma_uint64 preliminaryInputFrameCountFromFrac;
  12853. ma_uint64 preliminaryInputFrameCount;
  12854. if (sampleRateIn == 0 || sampleRateOut == 0 || frameCountIn == 0) {
  12855. return 0;
  12856. }
  12857. if (sampleRateOut == sampleRateIn) {
  12858. return frameCountIn;
  12859. }
  12860. outputFrameCount = (frameCountIn * sampleRateOut) / sampleRateIn;
  12861. preliminaryInputFrameCountFromFrac = (outputFrameCount * (sampleRateIn / sampleRateOut)) / sampleRateOut;
  12862. preliminaryInputFrameCount = (outputFrameCount * (sampleRateIn % sampleRateOut)) + preliminaryInputFrameCountFromFrac;
  12863. if (preliminaryInputFrameCount <= frameCountIn) {
  12864. outputFrameCount += 1;
  12865. }
  12866. return outputFrameCount;
  12867. }
  12868. #ifndef MA_DATA_CONVERTER_STACK_BUFFER_SIZE
  12869. #define MA_DATA_CONVERTER_STACK_BUFFER_SIZE 4096
  12870. #endif
  12871. #if defined(MA_WIN32)
  12872. static ma_result ma_result_from_GetLastError(DWORD error)
  12873. {
  12874. switch (error)
  12875. {
  12876. case ERROR_SUCCESS: return MA_SUCCESS;
  12877. case ERROR_PATH_NOT_FOUND: return MA_DOES_NOT_EXIST;
  12878. case ERROR_TOO_MANY_OPEN_FILES: return MA_TOO_MANY_OPEN_FILES;
  12879. case ERROR_NOT_ENOUGH_MEMORY: return MA_OUT_OF_MEMORY;
  12880. case ERROR_DISK_FULL: return MA_NO_SPACE;
  12881. case ERROR_HANDLE_EOF: return MA_AT_END;
  12882. case ERROR_NEGATIVE_SEEK: return MA_BAD_SEEK;
  12883. case ERROR_INVALID_PARAMETER: return MA_INVALID_ARGS;
  12884. case ERROR_ACCESS_DENIED: return MA_ACCESS_DENIED;
  12885. case ERROR_SEM_TIMEOUT: return MA_TIMEOUT;
  12886. case ERROR_FILE_NOT_FOUND: return MA_DOES_NOT_EXIST;
  12887. default: break;
  12888. }
  12889. return MA_ERROR;
  12890. }
  12891. #endif /* MA_WIN32 */
  12892. /*******************************************************************************
  12893. Threading
  12894. *******************************************************************************/
  12895. static MA_INLINE ma_result ma_spinlock_lock_ex(volatile ma_spinlock* pSpinlock, ma_bool32 yield)
  12896. {
  12897. if (pSpinlock == NULL) {
  12898. return MA_INVALID_ARGS;
  12899. }
  12900. for (;;) {
  12901. if (c89atomic_exchange_explicit_32(pSpinlock, 1, c89atomic_memory_order_acquire) == 0) {
  12902. break;
  12903. }
  12904. while (c89atomic_load_explicit_32(pSpinlock, c89atomic_memory_order_relaxed) == 1) {
  12905. if (yield) {
  12906. ma_yield();
  12907. }
  12908. }
  12909. }
  12910. return MA_SUCCESS;
  12911. }
  12912. MA_API ma_result ma_spinlock_lock(volatile ma_spinlock* pSpinlock)
  12913. {
  12914. return ma_spinlock_lock_ex(pSpinlock, MA_TRUE);
  12915. }
  12916. MA_API ma_result ma_spinlock_lock_noyield(volatile ma_spinlock* pSpinlock)
  12917. {
  12918. return ma_spinlock_lock_ex(pSpinlock, MA_FALSE);
  12919. }
  12920. MA_API ma_result ma_spinlock_unlock(volatile ma_spinlock* pSpinlock)
  12921. {
  12922. if (pSpinlock == NULL) {
  12923. return MA_INVALID_ARGS;
  12924. }
  12925. c89atomic_store_explicit_32(pSpinlock, 0, c89atomic_memory_order_release);
  12926. return MA_SUCCESS;
  12927. }
  12928. #ifndef MA_NO_THREADING
  12929. #ifdef MA_WIN32
  12930. #define MA_THREADCALL WINAPI
  12931. typedef unsigned long ma_thread_result;
  12932. #else
  12933. #define MA_THREADCALL
  12934. typedef void* ma_thread_result;
  12935. #endif
  12936. typedef ma_thread_result (MA_THREADCALL * ma_thread_entry_proc)(void* pData);
  12937. #ifdef MA_WIN32
  12938. static int ma_thread_priority_to_win32(ma_thread_priority priority)
  12939. {
  12940. switch (priority) {
  12941. case ma_thread_priority_idle: return THREAD_PRIORITY_IDLE;
  12942. case ma_thread_priority_lowest: return THREAD_PRIORITY_LOWEST;
  12943. case ma_thread_priority_low: return THREAD_PRIORITY_BELOW_NORMAL;
  12944. case ma_thread_priority_normal: return THREAD_PRIORITY_NORMAL;
  12945. case ma_thread_priority_high: return THREAD_PRIORITY_ABOVE_NORMAL;
  12946. case ma_thread_priority_highest: return THREAD_PRIORITY_HIGHEST;
  12947. case ma_thread_priority_realtime: return THREAD_PRIORITY_TIME_CRITICAL;
  12948. default: return THREAD_PRIORITY_NORMAL;
  12949. }
  12950. }
  12951. static ma_result ma_thread_create__win32(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  12952. {
  12953. *pThread = CreateThread(NULL, stackSize, entryProc, pData, 0, NULL);
  12954. if (*pThread == NULL) {
  12955. return ma_result_from_GetLastError(GetLastError());
  12956. }
  12957. SetThreadPriority((HANDLE)*pThread, ma_thread_priority_to_win32(priority));
  12958. return MA_SUCCESS;
  12959. }
  12960. static void ma_thread_wait__win32(ma_thread* pThread)
  12961. {
  12962. WaitForSingleObject((HANDLE)*pThread, INFINITE);
  12963. CloseHandle((HANDLE)*pThread);
  12964. }
  12965. static ma_result ma_mutex_init__win32(ma_mutex* pMutex)
  12966. {
  12967. *pMutex = CreateEventW(NULL, FALSE, TRUE, NULL);
  12968. if (*pMutex == NULL) {
  12969. return ma_result_from_GetLastError(GetLastError());
  12970. }
  12971. return MA_SUCCESS;
  12972. }
  12973. static void ma_mutex_uninit__win32(ma_mutex* pMutex)
  12974. {
  12975. CloseHandle((HANDLE)*pMutex);
  12976. }
  12977. static void ma_mutex_lock__win32(ma_mutex* pMutex)
  12978. {
  12979. WaitForSingleObject((HANDLE)*pMutex, INFINITE);
  12980. }
  12981. static void ma_mutex_unlock__win32(ma_mutex* pMutex)
  12982. {
  12983. SetEvent((HANDLE)*pMutex);
  12984. }
  12985. static ma_result ma_event_init__win32(ma_event* pEvent)
  12986. {
  12987. *pEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  12988. if (*pEvent == NULL) {
  12989. return ma_result_from_GetLastError(GetLastError());
  12990. }
  12991. return MA_SUCCESS;
  12992. }
  12993. static void ma_event_uninit__win32(ma_event* pEvent)
  12994. {
  12995. CloseHandle((HANDLE)*pEvent);
  12996. }
  12997. static ma_result ma_event_wait__win32(ma_event* pEvent)
  12998. {
  12999. DWORD result = WaitForSingleObject((HANDLE)*pEvent, INFINITE);
  13000. if (result == WAIT_OBJECT_0) {
  13001. return MA_SUCCESS;
  13002. }
  13003. if (result == WAIT_TIMEOUT) {
  13004. return MA_TIMEOUT;
  13005. }
  13006. return ma_result_from_GetLastError(GetLastError());
  13007. }
  13008. static ma_result ma_event_signal__win32(ma_event* pEvent)
  13009. {
  13010. BOOL result = SetEvent((HANDLE)*pEvent);
  13011. if (result == 0) {
  13012. return ma_result_from_GetLastError(GetLastError());
  13013. }
  13014. return MA_SUCCESS;
  13015. }
  13016. static ma_result ma_semaphore_init__win32(int initialValue, ma_semaphore* pSemaphore)
  13017. {
  13018. *pSemaphore = CreateSemaphoreW(NULL, (LONG)initialValue, LONG_MAX, NULL);
  13019. if (*pSemaphore == NULL) {
  13020. return ma_result_from_GetLastError(GetLastError());
  13021. }
  13022. return MA_SUCCESS;
  13023. }
  13024. static void ma_semaphore_uninit__win32(ma_semaphore* pSemaphore)
  13025. {
  13026. CloseHandle((HANDLE)*pSemaphore);
  13027. }
  13028. static ma_result ma_semaphore_wait__win32(ma_semaphore* pSemaphore)
  13029. {
  13030. DWORD result = WaitForSingleObject((HANDLE)*pSemaphore, INFINITE);
  13031. if (result == WAIT_OBJECT_0) {
  13032. return MA_SUCCESS;
  13033. }
  13034. if (result == WAIT_TIMEOUT) {
  13035. return MA_TIMEOUT;
  13036. }
  13037. return ma_result_from_GetLastError(GetLastError());
  13038. }
  13039. static ma_result ma_semaphore_release__win32(ma_semaphore* pSemaphore)
  13040. {
  13041. BOOL result = ReleaseSemaphore((HANDLE)*pSemaphore, 1, NULL);
  13042. if (result == 0) {
  13043. return ma_result_from_GetLastError(GetLastError());
  13044. }
  13045. return MA_SUCCESS;
  13046. }
  13047. #endif
  13048. #ifdef MA_POSIX
  13049. static ma_result ma_thread_create__posix(ma_thread* pThread, ma_thread_priority priority, size_t stackSize, ma_thread_entry_proc entryProc, void* pData)
  13050. {
  13051. int result;
  13052. pthread_attr_t* pAttr = NULL;
  13053. #if !defined(__EMSCRIPTEN__)
  13054. /* Try setting the thread priority. It's not critical if anything fails here. */
  13055. pthread_attr_t attr;
  13056. if (pthread_attr_init(&attr) == 0) {
  13057. int scheduler = -1;
  13058. if (priority == ma_thread_priority_idle) {
  13059. #ifdef SCHED_IDLE
  13060. if (pthread_attr_setschedpolicy(&attr, SCHED_IDLE) == 0) {
  13061. scheduler = SCHED_IDLE;
  13062. }
  13063. #endif
  13064. } else if (priority == ma_thread_priority_realtime) {
  13065. #ifdef SCHED_FIFO
  13066. if (pthread_attr_setschedpolicy(&attr, SCHED_FIFO) == 0) {
  13067. scheduler = SCHED_FIFO;
  13068. }
  13069. #endif
  13070. #ifdef MA_LINUX
  13071. } else {
  13072. scheduler = sched_getscheduler(0);
  13073. #endif
  13074. }
  13075. if (stackSize > 0) {
  13076. pthread_attr_setstacksize(&attr, stackSize);
  13077. }
  13078. if (scheduler != -1) {
  13079. int priorityMin = sched_get_priority_min(scheduler);
  13080. int priorityMax = sched_get_priority_max(scheduler);
  13081. int priorityStep = (priorityMax - priorityMin) / 7; /* 7 = number of priorities supported by miniaudio. */
  13082. struct sched_param sched;
  13083. if (pthread_attr_getschedparam(&attr, &sched) == 0) {
  13084. if (priority == ma_thread_priority_idle) {
  13085. sched.sched_priority = priorityMin;
  13086. } else if (priority == ma_thread_priority_realtime) {
  13087. sched.sched_priority = priorityMax;
  13088. } else {
  13089. sched.sched_priority += ((int)priority + 5) * priorityStep; /* +5 because the lowest priority is -5. */
  13090. if (sched.sched_priority < priorityMin) {
  13091. sched.sched_priority = priorityMin;
  13092. }
  13093. if (sched.sched_priority > priorityMax) {
  13094. sched.sched_priority = priorityMax;
  13095. }
  13096. }
  13097. if (pthread_attr_setschedparam(&attr, &sched) == 0) {
  13098. pAttr = &attr;
  13099. }
  13100. }
  13101. }
  13102. }
  13103. #else
  13104. /* It's the emscripten build. We'll have a few unused parameters. */
  13105. (void)priority;
  13106. (void)stackSize;
  13107. #endif
  13108. result = pthread_create((pthread_t*)pThread, pAttr, entryProc, pData);
  13109. /* The thread attributes object is no longer required. */
  13110. if (pAttr != NULL) {
  13111. pthread_attr_destroy(pAttr);
  13112. }
  13113. if (result != 0) {
  13114. return ma_result_from_errno(result);
  13115. }
  13116. return MA_SUCCESS;
  13117. }
  13118. static void ma_thread_wait__posix(ma_thread* pThread)
  13119. {
  13120. pthread_join((pthread_t)*pThread, NULL);
  13121. }
  13122. static ma_result ma_mutex_init__posix(ma_mutex* pMutex)
  13123. {
  13124. int result = pthread_mutex_init((pthread_mutex_t*)pMutex, NULL);
  13125. if (result != 0) {
  13126. return ma_result_from_errno(result);
  13127. }
  13128. return MA_SUCCESS;
  13129. }
  13130. static void ma_mutex_uninit__posix(ma_mutex* pMutex)
  13131. {
  13132. pthread_mutex_destroy((pthread_mutex_t*)pMutex);
  13133. }
  13134. static void ma_mutex_lock__posix(ma_mutex* pMutex)
  13135. {
  13136. pthread_mutex_lock((pthread_mutex_t*)pMutex);
  13137. }
  13138. static void ma_mutex_unlock__posix(ma_mutex* pMutex)
  13139. {
  13140. pthread_mutex_unlock((pthread_mutex_t*)pMutex);
  13141. }
  13142. static ma_result ma_event_init__posix(ma_event* pEvent)
  13143. {
  13144. int result;
  13145. result = pthread_mutex_init((pthread_mutex_t*)&pEvent->lock, NULL);
  13146. if (result != 0) {
  13147. return ma_result_from_errno(result);
  13148. }
  13149. result = pthread_cond_init((pthread_cond_t*)&pEvent->cond, NULL);
  13150. if (result != 0) {
  13151. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13152. return ma_result_from_errno(result);
  13153. }
  13154. pEvent->value = 0;
  13155. return MA_SUCCESS;
  13156. }
  13157. static void ma_event_uninit__posix(ma_event* pEvent)
  13158. {
  13159. pthread_cond_destroy((pthread_cond_t*)&pEvent->cond);
  13160. pthread_mutex_destroy((pthread_mutex_t*)&pEvent->lock);
  13161. }
  13162. static ma_result ma_event_wait__posix(ma_event* pEvent)
  13163. {
  13164. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13165. {
  13166. while (pEvent->value == 0) {
  13167. pthread_cond_wait((pthread_cond_t*)&pEvent->cond, (pthread_mutex_t*)&pEvent->lock);
  13168. }
  13169. pEvent->value = 0; /* Auto-reset. */
  13170. }
  13171. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13172. return MA_SUCCESS;
  13173. }
  13174. static ma_result ma_event_signal__posix(ma_event* pEvent)
  13175. {
  13176. pthread_mutex_lock((pthread_mutex_t*)&pEvent->lock);
  13177. {
  13178. pEvent->value = 1;
  13179. pthread_cond_signal((pthread_cond_t*)&pEvent->cond);
  13180. }
  13181. pthread_mutex_unlock((pthread_mutex_t*)&pEvent->lock);
  13182. return MA_SUCCESS;
  13183. }
  13184. static ma_result ma_semaphore_init__posix(int initialValue, ma_semaphore* pSemaphore)
  13185. {
  13186. int result;
  13187. if (pSemaphore == NULL) {
  13188. return MA_INVALID_ARGS;
  13189. }
  13190. pSemaphore->value = initialValue;
  13191. result = pthread_mutex_init((pthread_mutex_t*)&pSemaphore->lock, NULL);
  13192. if (result != 0) {
  13193. return ma_result_from_errno(result); /* Failed to create mutex. */
  13194. }
  13195. result = pthread_cond_init((pthread_cond_t*)&pSemaphore->cond, NULL);
  13196. if (result != 0) {
  13197. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13198. return ma_result_from_errno(result); /* Failed to create condition variable. */
  13199. }
  13200. return MA_SUCCESS;
  13201. }
  13202. static void ma_semaphore_uninit__posix(ma_semaphore* pSemaphore)
  13203. {
  13204. if (pSemaphore == NULL) {
  13205. return;
  13206. }
  13207. pthread_cond_destroy((pthread_cond_t*)&pSemaphore->cond);
  13208. pthread_mutex_destroy((pthread_mutex_t*)&pSemaphore->lock);
  13209. }
  13210. static ma_result ma_semaphore_wait__posix(ma_semaphore* pSemaphore)
  13211. {
  13212. if (pSemaphore == NULL) {
  13213. return MA_INVALID_ARGS;
  13214. }
  13215. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13216. {
  13217. /* We need to wait on a condition variable before escaping. We can't return from this function until the semaphore has been signaled. */
  13218. while (pSemaphore->value == 0) {
  13219. pthread_cond_wait((pthread_cond_t*)&pSemaphore->cond, (pthread_mutex_t*)&pSemaphore->lock);
  13220. }
  13221. pSemaphore->value -= 1;
  13222. }
  13223. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13224. return MA_SUCCESS;
  13225. }
  13226. static ma_result ma_semaphore_release__posix(ma_semaphore* pSemaphore)
  13227. {
  13228. if (pSemaphore == NULL) {
  13229. return MA_INVALID_ARGS;
  13230. }
  13231. pthread_mutex_lock((pthread_mutex_t*)&pSemaphore->lock);
  13232. {
  13233. pSemaphore->value += 1;
  13234. pthread_cond_signal((pthread_cond_t*)&pSemaphore->cond);
  13235. }
  13236. pthread_mutex_unlock((pthread_mutex_t*)&pSemaphore->lock);
  13237. return MA_SUCCESS;
  13238. }
  13239. #endif
  13240. typedef struct
  13241. {
  13242. ma_thread_entry_proc entryProc;
  13243. void* pData;
  13244. ma_allocation_callbacks allocationCallbacks;
  13245. } ma_thread_proxy_data;
  13246. static ma_thread_result MA_THREADCALL ma_thread_entry_proxy(void* pData)
  13247. {
  13248. ma_thread_proxy_data* pProxyData = (ma_thread_proxy_data*)pData;
  13249. ma_thread_entry_proc entryProc;
  13250. void* pEntryProcData;
  13251. ma_thread_result result;
  13252. #if defined(MA_ON_THREAD_ENTRY)
  13253. MA_ON_THREAD_ENTRY
  13254. #endif
  13255. entryProc = pProxyData->entryProc;
  13256. pEntryProcData = pProxyData->pData;
  13257. /* Free the proxy data before getting into the real thread entry proc. */
  13258. ma_free(pProxyData, &pProxyData->allocationCallbacks);
  13259. result = entryProc(pEntryProcData);
  13260. #if defined(MA_ON_THREAD_EXIT)
  13261. MA_ON_THREAD_EXIT
  13262. #endif
  13263. return result;
  13264. }
  13265. 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)
  13266. {
  13267. ma_result result;
  13268. ma_thread_proxy_data* pProxyData;
  13269. if (pThread == NULL || entryProc == NULL) {
  13270. return MA_INVALID_ARGS;
  13271. }
  13272. pProxyData = (ma_thread_proxy_data*)ma_malloc(sizeof(*pProxyData), pAllocationCallbacks); /* Will be freed by the proxy entry proc. */
  13273. if (pProxyData == NULL) {
  13274. return MA_OUT_OF_MEMORY;
  13275. }
  13276. pProxyData->entryProc = entryProc;
  13277. pProxyData->pData = pData;
  13278. ma_allocation_callbacks_init_copy(&pProxyData->allocationCallbacks, pAllocationCallbacks);
  13279. #ifdef MA_WIN32
  13280. result = ma_thread_create__win32(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13281. #endif
  13282. #ifdef MA_POSIX
  13283. result = ma_thread_create__posix(pThread, priority, stackSize, ma_thread_entry_proxy, pProxyData);
  13284. #endif
  13285. if (result != MA_SUCCESS) {
  13286. ma_free(pProxyData, pAllocationCallbacks);
  13287. return result;
  13288. }
  13289. return MA_SUCCESS;
  13290. }
  13291. static void ma_thread_wait(ma_thread* pThread)
  13292. {
  13293. if (pThread == NULL) {
  13294. return;
  13295. }
  13296. #ifdef MA_WIN32
  13297. ma_thread_wait__win32(pThread);
  13298. #endif
  13299. #ifdef MA_POSIX
  13300. ma_thread_wait__posix(pThread);
  13301. #endif
  13302. }
  13303. MA_API ma_result ma_mutex_init(ma_mutex* pMutex)
  13304. {
  13305. if (pMutex == NULL) {
  13306. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13307. return MA_INVALID_ARGS;
  13308. }
  13309. #ifdef MA_WIN32
  13310. return ma_mutex_init__win32(pMutex);
  13311. #endif
  13312. #ifdef MA_POSIX
  13313. return ma_mutex_init__posix(pMutex);
  13314. #endif
  13315. }
  13316. MA_API void ma_mutex_uninit(ma_mutex* pMutex)
  13317. {
  13318. if (pMutex == NULL) {
  13319. return;
  13320. }
  13321. #ifdef MA_WIN32
  13322. ma_mutex_uninit__win32(pMutex);
  13323. #endif
  13324. #ifdef MA_POSIX
  13325. ma_mutex_uninit__posix(pMutex);
  13326. #endif
  13327. }
  13328. MA_API void ma_mutex_lock(ma_mutex* pMutex)
  13329. {
  13330. if (pMutex == NULL) {
  13331. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13332. return;
  13333. }
  13334. #ifdef MA_WIN32
  13335. ma_mutex_lock__win32(pMutex);
  13336. #endif
  13337. #ifdef MA_POSIX
  13338. ma_mutex_lock__posix(pMutex);
  13339. #endif
  13340. }
  13341. MA_API void ma_mutex_unlock(ma_mutex* pMutex)
  13342. {
  13343. if (pMutex == NULL) {
  13344. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13345. return;
  13346. }
  13347. #ifdef MA_WIN32
  13348. ma_mutex_unlock__win32(pMutex);
  13349. #endif
  13350. #ifdef MA_POSIX
  13351. ma_mutex_unlock__posix(pMutex);
  13352. #endif
  13353. }
  13354. MA_API ma_result ma_event_init(ma_event* pEvent)
  13355. {
  13356. if (pEvent == NULL) {
  13357. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13358. return MA_INVALID_ARGS;
  13359. }
  13360. #ifdef MA_WIN32
  13361. return ma_event_init__win32(pEvent);
  13362. #endif
  13363. #ifdef MA_POSIX
  13364. return ma_event_init__posix(pEvent);
  13365. #endif
  13366. }
  13367. #if 0
  13368. static ma_result ma_event_alloc_and_init(ma_event** ppEvent, ma_allocation_callbacks* pAllocationCallbacks)
  13369. {
  13370. ma_result result;
  13371. ma_event* pEvent;
  13372. if (ppEvent == NULL) {
  13373. return MA_INVALID_ARGS;
  13374. }
  13375. *ppEvent = NULL;
  13376. pEvent = ma_malloc(sizeof(*pEvent), pAllocationCallbacks);
  13377. if (pEvent == NULL) {
  13378. return MA_OUT_OF_MEMORY;
  13379. }
  13380. result = ma_event_init(pEvent);
  13381. if (result != MA_SUCCESS) {
  13382. ma_free(pEvent, pAllocationCallbacks);
  13383. return result;
  13384. }
  13385. *ppEvent = pEvent;
  13386. return result;
  13387. }
  13388. #endif
  13389. MA_API void ma_event_uninit(ma_event* pEvent)
  13390. {
  13391. if (pEvent == NULL) {
  13392. return;
  13393. }
  13394. #ifdef MA_WIN32
  13395. ma_event_uninit__win32(pEvent);
  13396. #endif
  13397. #ifdef MA_POSIX
  13398. ma_event_uninit__posix(pEvent);
  13399. #endif
  13400. }
  13401. #if 0
  13402. static void ma_event_uninit_and_free(ma_event* pEvent, ma_allocation_callbacks* pAllocationCallbacks)
  13403. {
  13404. if (pEvent == NULL) {
  13405. return;
  13406. }
  13407. ma_event_uninit(pEvent);
  13408. ma_free(pEvent, pAllocationCallbacks);
  13409. }
  13410. #endif
  13411. MA_API ma_result ma_event_wait(ma_event* pEvent)
  13412. {
  13413. if (pEvent == NULL) {
  13414. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  13415. return MA_INVALID_ARGS;
  13416. }
  13417. #ifdef MA_WIN32
  13418. return ma_event_wait__win32(pEvent);
  13419. #endif
  13420. #ifdef MA_POSIX
  13421. return ma_event_wait__posix(pEvent);
  13422. #endif
  13423. }
  13424. MA_API ma_result ma_event_signal(ma_event* pEvent)
  13425. {
  13426. if (pEvent == NULL) {
  13427. MA_ASSERT(MA_FALSE); /* Fire an assert to the caller is aware of this bug. */
  13428. return MA_INVALID_ARGS;
  13429. }
  13430. #ifdef MA_WIN32
  13431. return ma_event_signal__win32(pEvent);
  13432. #endif
  13433. #ifdef MA_POSIX
  13434. return ma_event_signal__posix(pEvent);
  13435. #endif
  13436. }
  13437. MA_API ma_result ma_semaphore_init(int initialValue, ma_semaphore* pSemaphore)
  13438. {
  13439. if (pSemaphore == NULL) {
  13440. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13441. return MA_INVALID_ARGS;
  13442. }
  13443. #ifdef MA_WIN32
  13444. return ma_semaphore_init__win32(initialValue, pSemaphore);
  13445. #endif
  13446. #ifdef MA_POSIX
  13447. return ma_semaphore_init__posix(initialValue, pSemaphore);
  13448. #endif
  13449. }
  13450. MA_API void ma_semaphore_uninit(ma_semaphore* pSemaphore)
  13451. {
  13452. if (pSemaphore == NULL) {
  13453. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13454. return;
  13455. }
  13456. #ifdef MA_WIN32
  13457. ma_semaphore_uninit__win32(pSemaphore);
  13458. #endif
  13459. #ifdef MA_POSIX
  13460. ma_semaphore_uninit__posix(pSemaphore);
  13461. #endif
  13462. }
  13463. MA_API ma_result ma_semaphore_wait(ma_semaphore* pSemaphore)
  13464. {
  13465. if (pSemaphore == NULL) {
  13466. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13467. return MA_INVALID_ARGS;
  13468. }
  13469. #ifdef MA_WIN32
  13470. return ma_semaphore_wait__win32(pSemaphore);
  13471. #endif
  13472. #ifdef MA_POSIX
  13473. return ma_semaphore_wait__posix(pSemaphore);
  13474. #endif
  13475. }
  13476. MA_API ma_result ma_semaphore_release(ma_semaphore* pSemaphore)
  13477. {
  13478. if (pSemaphore == NULL) {
  13479. MA_ASSERT(MA_FALSE); /* Fire an assert so the caller is aware of this bug. */
  13480. return MA_INVALID_ARGS;
  13481. }
  13482. #ifdef MA_WIN32
  13483. return ma_semaphore_release__win32(pSemaphore);
  13484. #endif
  13485. #ifdef MA_POSIX
  13486. return ma_semaphore_release__posix(pSemaphore);
  13487. #endif
  13488. }
  13489. #else
  13490. /* 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. */
  13491. #ifndef MA_NO_DEVICE_IO
  13492. #error "MA_NO_THREADING cannot be used without MA_NO_DEVICE_IO";
  13493. #endif
  13494. #endif /* MA_NO_THREADING */
  13495. #define MA_FENCE_COUNTER_MAX 0x7FFFFFFF
  13496. MA_API ma_result ma_fence_init(ma_fence* pFence)
  13497. {
  13498. if (pFence == NULL) {
  13499. return MA_INVALID_ARGS;
  13500. }
  13501. MA_ZERO_OBJECT(pFence);
  13502. pFence->counter = 0;
  13503. #ifndef MA_NO_THREADING
  13504. {
  13505. ma_result result;
  13506. result = ma_event_init(&pFence->e);
  13507. if (result != MA_SUCCESS) {
  13508. return result;
  13509. }
  13510. }
  13511. #endif
  13512. return MA_SUCCESS;
  13513. }
  13514. MA_API void ma_fence_uninit(ma_fence* pFence)
  13515. {
  13516. if (pFence == NULL) {
  13517. return;
  13518. }
  13519. #ifndef MA_NO_THREADING
  13520. {
  13521. ma_event_uninit(&pFence->e);
  13522. }
  13523. #endif
  13524. MA_ZERO_OBJECT(pFence);
  13525. }
  13526. MA_API ma_result ma_fence_acquire(ma_fence* pFence)
  13527. {
  13528. if (pFence == NULL) {
  13529. return MA_INVALID_ARGS;
  13530. }
  13531. for (;;) {
  13532. ma_uint32 oldCounter = c89atomic_load_32(&pFence->counter);
  13533. ma_uint32 newCounter = oldCounter + 1;
  13534. /* Make sure we're not about to exceed our maximum value. */
  13535. if (newCounter > MA_FENCE_COUNTER_MAX) {
  13536. MA_ASSERT(MA_FALSE);
  13537. return MA_OUT_OF_RANGE;
  13538. }
  13539. if (c89atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  13540. return MA_SUCCESS;
  13541. } else {
  13542. if (oldCounter == MA_FENCE_COUNTER_MAX) {
  13543. MA_ASSERT(MA_FALSE);
  13544. return MA_OUT_OF_RANGE; /* The other thread took the last available slot. Abort. */
  13545. }
  13546. }
  13547. }
  13548. /* Should never get here. */
  13549. /*return MA_SUCCESS;*/
  13550. }
  13551. MA_API ma_result ma_fence_release(ma_fence* pFence)
  13552. {
  13553. if (pFence == NULL) {
  13554. return MA_INVALID_ARGS;
  13555. }
  13556. for (;;) {
  13557. ma_uint32 oldCounter = c89atomic_load_32(&pFence->counter);
  13558. ma_uint32 newCounter = oldCounter - 1;
  13559. if (oldCounter == 0) {
  13560. MA_ASSERT(MA_FALSE);
  13561. return MA_INVALID_OPERATION; /* Acquire/release mismatch. */
  13562. }
  13563. if (c89atomic_compare_exchange_weak_32(&pFence->counter, &oldCounter, newCounter)) {
  13564. #ifndef MA_NO_THREADING
  13565. {
  13566. if (newCounter == 0) {
  13567. ma_event_signal(&pFence->e); /* <-- ma_fence_wait() will be waiting on this. */
  13568. }
  13569. }
  13570. #endif
  13571. return MA_SUCCESS;
  13572. } else {
  13573. if (oldCounter == 0) {
  13574. MA_ASSERT(MA_FALSE);
  13575. return MA_INVALID_OPERATION; /* Another thread has taken the 0 slot. Acquire/release mismatch. */
  13576. }
  13577. }
  13578. }
  13579. /* Should never get here. */
  13580. /*return MA_SUCCESS;*/
  13581. }
  13582. MA_API ma_result ma_fence_wait(ma_fence* pFence)
  13583. {
  13584. if (pFence == NULL) {
  13585. return MA_INVALID_ARGS;
  13586. }
  13587. for (;;) {
  13588. ma_uint32 counter;
  13589. counter = c89atomic_load_32(&pFence->counter);
  13590. if (counter == 0) {
  13591. /*
  13592. Counter has hit zero. By the time we get here some other thread may have acquired the
  13593. fence again, but that is where the caller needs to take care with how they se the fence.
  13594. */
  13595. return MA_SUCCESS;
  13596. }
  13597. /* Getting here means the counter is > 0. We'll need to wait for something to happen. */
  13598. #ifndef MA_NO_THREADING
  13599. {
  13600. ma_result result;
  13601. result = ma_event_wait(&pFence->e);
  13602. if (result != MA_SUCCESS) {
  13603. return result;
  13604. }
  13605. }
  13606. #endif
  13607. }
  13608. /* Should never get here. */
  13609. /*return MA_INVALID_OPERATION;*/
  13610. }
  13611. MA_API ma_result ma_async_notification_signal(ma_async_notification* pNotification)
  13612. {
  13613. ma_async_notification_callbacks* pNotificationCallbacks = (ma_async_notification_callbacks*)pNotification;
  13614. if (pNotification == NULL) {
  13615. return MA_INVALID_ARGS;
  13616. }
  13617. if (pNotificationCallbacks->onSignal == NULL) {
  13618. return MA_NOT_IMPLEMENTED;
  13619. }
  13620. pNotificationCallbacks->onSignal(pNotification);
  13621. return MA_INVALID_ARGS;
  13622. }
  13623. static void ma_async_notification_poll__on_signal(ma_async_notification* pNotification)
  13624. {
  13625. ((ma_async_notification_poll*)pNotification)->signalled = MA_TRUE;
  13626. }
  13627. MA_API ma_result ma_async_notification_poll_init(ma_async_notification_poll* pNotificationPoll)
  13628. {
  13629. if (pNotificationPoll == NULL) {
  13630. return MA_INVALID_ARGS;
  13631. }
  13632. pNotificationPoll->cb.onSignal = ma_async_notification_poll__on_signal;
  13633. pNotificationPoll->signalled = MA_FALSE;
  13634. return MA_SUCCESS;
  13635. }
  13636. MA_API ma_bool32 ma_async_notification_poll_is_signalled(const ma_async_notification_poll* pNotificationPoll)
  13637. {
  13638. if (pNotificationPoll == NULL) {
  13639. return MA_FALSE;
  13640. }
  13641. return pNotificationPoll->signalled;
  13642. }
  13643. static void ma_async_notification_event__on_signal(ma_async_notification* pNotification)
  13644. {
  13645. ma_async_notification_event_signal((ma_async_notification_event*)pNotification);
  13646. }
  13647. MA_API ma_result ma_async_notification_event_init(ma_async_notification_event* pNotificationEvent)
  13648. {
  13649. if (pNotificationEvent == NULL) {
  13650. return MA_INVALID_ARGS;
  13651. }
  13652. pNotificationEvent->cb.onSignal = ma_async_notification_event__on_signal;
  13653. #ifndef MA_NO_THREADING
  13654. {
  13655. ma_result result;
  13656. result = ma_event_init(&pNotificationEvent->e);
  13657. if (result != MA_SUCCESS) {
  13658. return result;
  13659. }
  13660. return MA_SUCCESS;
  13661. }
  13662. #else
  13663. {
  13664. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  13665. }
  13666. #endif
  13667. }
  13668. MA_API ma_result ma_async_notification_event_uninit(ma_async_notification_event* pNotificationEvent)
  13669. {
  13670. if (pNotificationEvent == NULL) {
  13671. return MA_INVALID_ARGS;
  13672. }
  13673. #ifndef MA_NO_THREADING
  13674. {
  13675. ma_event_uninit(&pNotificationEvent->e);
  13676. return MA_SUCCESS;
  13677. }
  13678. #else
  13679. {
  13680. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  13681. }
  13682. #endif
  13683. }
  13684. MA_API ma_result ma_async_notification_event_wait(ma_async_notification_event* pNotificationEvent)
  13685. {
  13686. if (pNotificationEvent == NULL) {
  13687. return MA_INVALID_ARGS;
  13688. }
  13689. #ifndef MA_NO_THREADING
  13690. {
  13691. return ma_event_wait(&pNotificationEvent->e);
  13692. }
  13693. #else
  13694. {
  13695. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  13696. }
  13697. #endif
  13698. }
  13699. MA_API ma_result ma_async_notification_event_signal(ma_async_notification_event* pNotificationEvent)
  13700. {
  13701. if (pNotificationEvent == NULL) {
  13702. return MA_INVALID_ARGS;
  13703. }
  13704. #ifndef MA_NO_THREADING
  13705. {
  13706. return ma_event_signal(&pNotificationEvent->e);
  13707. }
  13708. #else
  13709. {
  13710. return MA_NOT_IMPLEMENTED; /* Threading is disabled. */
  13711. }
  13712. #endif
  13713. }
  13714. /************************************************************************************************************************************************************
  13715. Job Queue
  13716. ************************************************************************************************************************************************************/
  13717. MA_API ma_slot_allocator_config ma_slot_allocator_config_init(ma_uint32 capacity)
  13718. {
  13719. ma_slot_allocator_config config;
  13720. MA_ZERO_OBJECT(&config);
  13721. config.capacity = capacity;
  13722. return config;
  13723. }
  13724. static MA_INLINE ma_uint32 ma_slot_allocator_calculate_group_capacity(ma_uint32 slotCapacity)
  13725. {
  13726. ma_uint32 cap = slotCapacity / 32;
  13727. if ((slotCapacity % 32) != 0) {
  13728. cap += 1;
  13729. }
  13730. return cap;
  13731. }
  13732. static MA_INLINE ma_uint32 ma_slot_allocator_group_capacity(const ma_slot_allocator* pAllocator)
  13733. {
  13734. return ma_slot_allocator_calculate_group_capacity(pAllocator->capacity);
  13735. }
  13736. typedef struct
  13737. {
  13738. size_t sizeInBytes;
  13739. size_t groupsOffset;
  13740. size_t slotsOffset;
  13741. } ma_slot_allocator_heap_layout;
  13742. static ma_result ma_slot_allocator_get_heap_layout(const ma_slot_allocator_config* pConfig, ma_slot_allocator_heap_layout* pHeapLayout)
  13743. {
  13744. MA_ASSERT(pHeapLayout != NULL);
  13745. MA_ZERO_OBJECT(pHeapLayout);
  13746. if (pConfig == NULL) {
  13747. return MA_INVALID_ARGS;
  13748. }
  13749. if (pConfig->capacity == 0) {
  13750. return MA_INVALID_ARGS;
  13751. }
  13752. pHeapLayout->sizeInBytes = 0;
  13753. /* Groups. */
  13754. pHeapLayout->groupsOffset = pHeapLayout->sizeInBytes;
  13755. pHeapLayout->sizeInBytes += ma_align_64(ma_slot_allocator_calculate_group_capacity(pConfig->capacity) * sizeof(ma_slot_allocator_group));
  13756. /* Slots. */
  13757. pHeapLayout->slotsOffset = pHeapLayout->sizeInBytes;
  13758. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_uint32));
  13759. return MA_SUCCESS;
  13760. }
  13761. MA_API ma_result ma_slot_allocator_get_heap_size(const ma_slot_allocator_config* pConfig, size_t* pHeapSizeInBytes)
  13762. {
  13763. ma_result result;
  13764. ma_slot_allocator_heap_layout layout;
  13765. if (pHeapSizeInBytes == NULL) {
  13766. return MA_INVALID_ARGS;
  13767. }
  13768. *pHeapSizeInBytes = 0;
  13769. result = ma_slot_allocator_get_heap_layout(pConfig, &layout);
  13770. if (result != MA_SUCCESS) {
  13771. return result;
  13772. }
  13773. *pHeapSizeInBytes = layout.sizeInBytes;
  13774. return result;
  13775. }
  13776. MA_API ma_result ma_slot_allocator_init_preallocated(const ma_slot_allocator_config* pConfig, void* pHeap, ma_slot_allocator* pAllocator)
  13777. {
  13778. ma_result result;
  13779. ma_slot_allocator_heap_layout heapLayout;
  13780. if (pAllocator == NULL) {
  13781. return MA_INVALID_ARGS;
  13782. }
  13783. MA_ZERO_OBJECT(pAllocator);
  13784. if (pHeap == NULL) {
  13785. return MA_INVALID_ARGS;
  13786. }
  13787. result = ma_slot_allocator_get_heap_layout(pConfig, &heapLayout);
  13788. if (result != MA_SUCCESS) {
  13789. return result;
  13790. }
  13791. pAllocator->_pHeap = pHeap;
  13792. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  13793. pAllocator->pGroups = (ma_slot_allocator_group*)ma_offset_ptr(pHeap, heapLayout.groupsOffset);
  13794. pAllocator->pSlots = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.slotsOffset);
  13795. pAllocator->capacity = pConfig->capacity;
  13796. return MA_SUCCESS;
  13797. }
  13798. MA_API ma_result ma_slot_allocator_init(const ma_slot_allocator_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_slot_allocator* pAllocator)
  13799. {
  13800. ma_result result;
  13801. size_t heapSizeInBytes;
  13802. void* pHeap;
  13803. result = ma_slot_allocator_get_heap_size(pConfig, &heapSizeInBytes);
  13804. if (result != MA_SUCCESS) {
  13805. return result; /* Failed to retrieve the size of the heap allocation. */
  13806. }
  13807. if (heapSizeInBytes > 0) {
  13808. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  13809. if (pHeap == NULL) {
  13810. return MA_OUT_OF_MEMORY;
  13811. }
  13812. } else {
  13813. pHeap = NULL;
  13814. }
  13815. result = ma_slot_allocator_init_preallocated(pConfig, pHeap, pAllocator);
  13816. if (result != MA_SUCCESS) {
  13817. ma_free(pHeap, pAllocationCallbacks);
  13818. return result;
  13819. }
  13820. pAllocator->_ownsHeap = MA_TRUE;
  13821. return MA_SUCCESS;
  13822. }
  13823. MA_API void ma_slot_allocator_uninit(ma_slot_allocator* pAllocator, const ma_allocation_callbacks* pAllocationCallbacks)
  13824. {
  13825. if (pAllocator == NULL) {
  13826. return;
  13827. }
  13828. if (pAllocator->_ownsHeap) {
  13829. ma_free(pAllocator->_pHeap, pAllocationCallbacks);
  13830. }
  13831. }
  13832. MA_API ma_result ma_slot_allocator_alloc(ma_slot_allocator* pAllocator, ma_uint64* pSlot)
  13833. {
  13834. ma_uint32 iAttempt;
  13835. const ma_uint32 maxAttempts = 2; /* The number of iterations to perform until returning MA_OUT_OF_MEMORY if no slots can be found. */
  13836. if (pAllocator == NULL || pSlot == NULL) {
  13837. return MA_INVALID_ARGS;
  13838. }
  13839. for (iAttempt = 0; iAttempt < maxAttempts; iAttempt += 1) {
  13840. /* We need to acquire a suitable bitfield first. This is a bitfield that's got an available slot within it. */
  13841. ma_uint32 iGroup;
  13842. for (iGroup = 0; iGroup < ma_slot_allocator_group_capacity(pAllocator); iGroup += 1) {
  13843. /* CAS */
  13844. for (;;) {
  13845. ma_uint32 oldBitfield;
  13846. ma_uint32 newBitfield;
  13847. ma_uint32 bitOffset;
  13848. oldBitfield = c89atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  13849. /* Fast check to see if anything is available. */
  13850. if (oldBitfield == 0xFFFFFFFF) {
  13851. break; /* No available bits in this bitfield. */
  13852. }
  13853. bitOffset = ma_ffs_32(~oldBitfield);
  13854. MA_ASSERT(bitOffset < 32);
  13855. newBitfield = oldBitfield | (1 << bitOffset);
  13856. if (c89atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  13857. ma_uint32 slotIndex;
  13858. /* Increment the counter as soon as possible to have other threads report out-of-memory sooner than later. */
  13859. c89atomic_fetch_add_32(&pAllocator->count, 1);
  13860. /* The slot index is required for constructing the output value. */
  13861. slotIndex = (iGroup << 5) + bitOffset; /* iGroup << 5 = iGroup * 32 */
  13862. if (slotIndex >= pAllocator->capacity) {
  13863. return MA_OUT_OF_MEMORY;
  13864. }
  13865. /* Increment the reference count before constructing the output value. */
  13866. pAllocator->pSlots[slotIndex] += 1;
  13867. /* Construct the output value. */
  13868. *pSlot = (((ma_uint64)pAllocator->pSlots[slotIndex] << 32) | slotIndex);
  13869. return MA_SUCCESS;
  13870. }
  13871. }
  13872. }
  13873. /* 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. */
  13874. if (pAllocator->count < pAllocator->capacity) {
  13875. ma_yield();
  13876. } else {
  13877. return MA_OUT_OF_MEMORY;
  13878. }
  13879. }
  13880. /* We couldn't find a slot within the maximum number of attempts. */
  13881. return MA_OUT_OF_MEMORY;
  13882. }
  13883. MA_API ma_result ma_slot_allocator_free(ma_slot_allocator* pAllocator, ma_uint64 slot)
  13884. {
  13885. ma_uint32 iGroup;
  13886. ma_uint32 iBit;
  13887. if (pAllocator == NULL) {
  13888. return MA_INVALID_ARGS;
  13889. }
  13890. iGroup = (ma_uint32)((slot & 0xFFFFFFFF) >> 5); /* slot / 32 */
  13891. iBit = (ma_uint32)((slot & 0xFFFFFFFF) & 31); /* slot % 32 */
  13892. if (iGroup >= ma_slot_allocator_group_capacity(pAllocator)) {
  13893. return MA_INVALID_ARGS;
  13894. }
  13895. MA_ASSERT(iBit < 32); /* This must be true due to the logic we used to actually calculate it. */
  13896. while (c89atomic_load_32(&pAllocator->count) > 0) {
  13897. /* CAS */
  13898. ma_uint32 oldBitfield;
  13899. ma_uint32 newBitfield;
  13900. oldBitfield = c89atomic_load_32(&pAllocator->pGroups[iGroup].bitfield); /* <-- This copy must happen. The compiler must not optimize this away. */
  13901. newBitfield = oldBitfield & ~(1 << iBit);
  13902. /* Debugging for checking for double-frees. */
  13903. #if defined(MA_DEBUG_OUTPUT)
  13904. {
  13905. if ((oldBitfield & (1 << iBit)) == 0) {
  13906. MA_ASSERT(MA_FALSE); /* Double free detected.*/
  13907. }
  13908. }
  13909. #endif
  13910. if (c89atomic_compare_and_swap_32(&pAllocator->pGroups[iGroup].bitfield, oldBitfield, newBitfield) == oldBitfield) {
  13911. c89atomic_fetch_sub_32(&pAllocator->count, 1);
  13912. return MA_SUCCESS;
  13913. }
  13914. }
  13915. /* Getting here means there are no allocations available for freeing. */
  13916. return MA_INVALID_OPERATION;
  13917. }
  13918. #define MA_JOB_ID_NONE ~((ma_uint64)0)
  13919. #define MA_JOB_SLOT_NONE (ma_uint16)(~0)
  13920. static MA_INLINE ma_uint32 ma_job_extract_refcount(ma_uint64 toc)
  13921. {
  13922. return (ma_uint32)(toc >> 32);
  13923. }
  13924. static MA_INLINE ma_uint16 ma_job_extract_slot(ma_uint64 toc)
  13925. {
  13926. return (ma_uint16)(toc & 0x0000FFFF);
  13927. }
  13928. static MA_INLINE ma_uint16 ma_job_extract_code(ma_uint64 toc)
  13929. {
  13930. return (ma_uint16)((toc & 0xFFFF0000) >> 16);
  13931. }
  13932. static MA_INLINE ma_uint64 ma_job_toc_to_allocation(ma_uint64 toc)
  13933. {
  13934. return ((ma_uint64)ma_job_extract_refcount(toc) << 32) | (ma_uint64)ma_job_extract_slot(toc);
  13935. }
  13936. static MA_INLINE ma_uint64 ma_job_set_refcount(ma_uint64 toc, ma_uint32 refcount)
  13937. {
  13938. /* Clear the reference count first. */
  13939. toc = toc & ~((ma_uint64)0xFFFFFFFF << 32);
  13940. toc = toc | ((ma_uint64)refcount << 32);
  13941. return toc;
  13942. }
  13943. MA_API ma_job ma_job_init(ma_uint16 code)
  13944. {
  13945. ma_job job;
  13946. MA_ZERO_OBJECT(&job);
  13947. job.toc.breakup.code = code;
  13948. job.toc.breakup.slot = MA_JOB_SLOT_NONE; /* Temp value. Will be allocated when posted to a queue. */
  13949. job.next = MA_JOB_ID_NONE;
  13950. return job;
  13951. }
  13952. static ma_result ma_job_process__noop(ma_job* pJob);
  13953. static ma_result ma_job_process__quit(ma_job* pJob);
  13954. static ma_result ma_job_process__custom(ma_job* pJob);
  13955. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob);
  13956. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob);
  13957. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob);
  13958. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob);
  13959. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob);
  13960. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob);
  13961. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob);
  13962. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob);
  13963. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob);
  13964. #if !defined(MA_NO_DEVICE_IO)
  13965. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob);
  13966. #endif
  13967. static ma_job_proc g_jobVTable[MA_JOB_TYPE_COUNT] =
  13968. {
  13969. /* Miscellaneous. */
  13970. ma_job_process__quit, /* MA_JOB_TYPE_QUIT */
  13971. ma_job_process__custom, /* MA_JOB_TYPE_CUSTOM */
  13972. /* Resource Manager. */
  13973. ma_job_process__resource_manager__load_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE */
  13974. ma_job_process__resource_manager__free_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE */
  13975. ma_job_process__resource_manager__page_data_buffer_node, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE */
  13976. ma_job_process__resource_manager__load_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER */
  13977. ma_job_process__resource_manager__free_data_buffer, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER */
  13978. ma_job_process__resource_manager__load_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM */
  13979. ma_job_process__resource_manager__free_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM */
  13980. ma_job_process__resource_manager__page_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM */
  13981. ma_job_process__resource_manager__seek_data_stream, /* MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM */
  13982. /* Device. */
  13983. #if !defined(MA_NO_DEVICE_IO)
  13984. ma_job_process__device__aaudio_reroute /*MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE*/
  13985. #endif
  13986. };
  13987. MA_API ma_result ma_job_process(ma_job* pJob)
  13988. {
  13989. if (pJob == NULL) {
  13990. return MA_INVALID_ARGS;
  13991. }
  13992. if (pJob->toc.breakup.code > MA_JOB_TYPE_COUNT) {
  13993. return MA_INVALID_OPERATION;
  13994. }
  13995. return g_jobVTable[pJob->toc.breakup.code](pJob);
  13996. }
  13997. static ma_result ma_job_process__noop(ma_job* pJob)
  13998. {
  13999. MA_ASSERT(pJob != NULL);
  14000. /* No-op. */
  14001. (void)pJob;
  14002. return MA_SUCCESS;
  14003. }
  14004. static ma_result ma_job_process__quit(ma_job* pJob)
  14005. {
  14006. return ma_job_process__noop(pJob);
  14007. }
  14008. static ma_result ma_job_process__custom(ma_job* pJob)
  14009. {
  14010. MA_ASSERT(pJob != NULL);
  14011. /* No-op if there's no callback. */
  14012. if (pJob->data.custom.proc == NULL) {
  14013. return MA_SUCCESS;
  14014. }
  14015. return pJob->data.custom.proc(pJob);
  14016. }
  14017. MA_API ma_job_queue_config ma_job_queue_config_init(ma_uint32 flags, ma_uint32 capacity)
  14018. {
  14019. ma_job_queue_config config;
  14020. config.flags = flags;
  14021. config.capacity = capacity;
  14022. return config;
  14023. }
  14024. typedef struct
  14025. {
  14026. size_t sizeInBytes;
  14027. size_t allocatorOffset;
  14028. size_t jobsOffset;
  14029. } ma_job_queue_heap_layout;
  14030. static ma_result ma_job_queue_get_heap_layout(const ma_job_queue_config* pConfig, ma_job_queue_heap_layout* pHeapLayout)
  14031. {
  14032. ma_result result;
  14033. MA_ASSERT(pHeapLayout != NULL);
  14034. MA_ZERO_OBJECT(pHeapLayout);
  14035. if (pConfig == NULL) {
  14036. return MA_INVALID_ARGS;
  14037. }
  14038. if (pConfig->capacity == 0) {
  14039. return MA_INVALID_ARGS;
  14040. }
  14041. pHeapLayout->sizeInBytes = 0;
  14042. /* Allocator. */
  14043. {
  14044. ma_slot_allocator_config allocatorConfig;
  14045. size_t allocatorHeapSizeInBytes;
  14046. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14047. result = ma_slot_allocator_get_heap_size(&allocatorConfig, &allocatorHeapSizeInBytes);
  14048. if (result != MA_SUCCESS) {
  14049. return result;
  14050. }
  14051. pHeapLayout->allocatorOffset = pHeapLayout->sizeInBytes;
  14052. pHeapLayout->sizeInBytes += allocatorHeapSizeInBytes;
  14053. }
  14054. /* Jobs. */
  14055. pHeapLayout->jobsOffset = pHeapLayout->sizeInBytes;
  14056. pHeapLayout->sizeInBytes += ma_align_64(pConfig->capacity * sizeof(ma_job));
  14057. return MA_SUCCESS;
  14058. }
  14059. MA_API ma_result ma_job_queue_get_heap_size(const ma_job_queue_config* pConfig, size_t* pHeapSizeInBytes)
  14060. {
  14061. ma_result result;
  14062. ma_job_queue_heap_layout layout;
  14063. if (pHeapSizeInBytes == NULL) {
  14064. return MA_INVALID_ARGS;
  14065. }
  14066. *pHeapSizeInBytes = 0;
  14067. result = ma_job_queue_get_heap_layout(pConfig, &layout);
  14068. if (result != MA_SUCCESS) {
  14069. return result;
  14070. }
  14071. *pHeapSizeInBytes = layout.sizeInBytes;
  14072. return MA_SUCCESS;
  14073. }
  14074. MA_API ma_result ma_job_queue_init_preallocated(const ma_job_queue_config* pConfig, void* pHeap, ma_job_queue* pQueue)
  14075. {
  14076. ma_result result;
  14077. ma_job_queue_heap_layout heapLayout;
  14078. ma_slot_allocator_config allocatorConfig;
  14079. if (pQueue == NULL) {
  14080. return MA_INVALID_ARGS;
  14081. }
  14082. MA_ZERO_OBJECT(pQueue);
  14083. result = ma_job_queue_get_heap_layout(pConfig, &heapLayout);
  14084. if (result != MA_SUCCESS) {
  14085. return result;
  14086. }
  14087. pQueue->_pHeap = pHeap;
  14088. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  14089. pQueue->flags = pConfig->flags;
  14090. pQueue->capacity = pConfig->capacity;
  14091. pQueue->pJobs = (ma_job*)ma_offset_ptr(pHeap, heapLayout.jobsOffset);
  14092. allocatorConfig = ma_slot_allocator_config_init(pConfig->capacity);
  14093. result = ma_slot_allocator_init_preallocated(&allocatorConfig, ma_offset_ptr(pHeap, heapLayout.allocatorOffset), &pQueue->allocator);
  14094. if (result != MA_SUCCESS) {
  14095. return result;
  14096. }
  14097. /* We need a semaphore if we're running in non-blocking mode. If threading is disabled we need to return an error. */
  14098. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14099. #ifndef MA_NO_THREADING
  14100. {
  14101. ma_semaphore_init(0, &pQueue->sem);
  14102. }
  14103. #else
  14104. {
  14105. /* Threading is disabled and we've requested non-blocking mode. */
  14106. return MA_INVALID_OPERATION;
  14107. }
  14108. #endif
  14109. }
  14110. /*
  14111. 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
  14112. just a dummy item for giving us the first item in the list which is stored in the "next" member.
  14113. */
  14114. ma_slot_allocator_alloc(&pQueue->allocator, &pQueue->head); /* Will never fail. */
  14115. pQueue->pJobs[ma_job_extract_slot(pQueue->head)].next = MA_JOB_ID_NONE;
  14116. pQueue->tail = pQueue->head;
  14117. return MA_SUCCESS;
  14118. }
  14119. MA_API ma_result ma_job_queue_init(const ma_job_queue_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_job_queue* pQueue)
  14120. {
  14121. ma_result result;
  14122. size_t heapSizeInBytes;
  14123. void* pHeap;
  14124. result = ma_job_queue_get_heap_size(pConfig, &heapSizeInBytes);
  14125. if (result != MA_SUCCESS) {
  14126. return result;
  14127. }
  14128. if (heapSizeInBytes > 0) {
  14129. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  14130. if (pHeap == NULL) {
  14131. return MA_OUT_OF_MEMORY;
  14132. }
  14133. } else {
  14134. pHeap = NULL;
  14135. }
  14136. result = ma_job_queue_init_preallocated(pConfig, pHeap, pQueue);
  14137. if (result != MA_SUCCESS) {
  14138. ma_free(pHeap, pAllocationCallbacks);
  14139. return result;
  14140. }
  14141. pQueue->_ownsHeap = MA_TRUE;
  14142. return MA_SUCCESS;
  14143. }
  14144. MA_API void ma_job_queue_uninit(ma_job_queue* pQueue, const ma_allocation_callbacks* pAllocationCallbacks)
  14145. {
  14146. if (pQueue == NULL) {
  14147. return;
  14148. }
  14149. /* All we need to do is uninitialize the semaphore. */
  14150. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14151. #ifndef MA_NO_THREADING
  14152. {
  14153. ma_semaphore_uninit(&pQueue->sem);
  14154. }
  14155. #else
  14156. {
  14157. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14158. }
  14159. #endif
  14160. }
  14161. ma_slot_allocator_uninit(&pQueue->allocator, pAllocationCallbacks);
  14162. if (pQueue->_ownsHeap) {
  14163. ma_free(pQueue->_pHeap, pAllocationCallbacks);
  14164. }
  14165. }
  14166. static ma_bool32 ma_job_queue_cas(volatile ma_uint64* dst, ma_uint64 expected, ma_uint64 desired)
  14167. {
  14168. /* The new counter is taken from the expected value. */
  14169. return c89atomic_compare_and_swap_64(dst, expected, ma_job_set_refcount(desired, ma_job_extract_refcount(expected) + 1)) == expected;
  14170. }
  14171. MA_API ma_result ma_job_queue_post(ma_job_queue* pQueue, const ma_job* pJob)
  14172. {
  14173. /*
  14174. Lock free queue implementation based on the paper by Michael and Scott: Nonblocking Algorithms and Preemption-Safe Locking on Multiprogrammed Shared Memory Multiprocessors
  14175. */
  14176. ma_result result;
  14177. ma_uint64 slot;
  14178. ma_uint64 tail;
  14179. ma_uint64 next;
  14180. if (pQueue == NULL || pJob == NULL) {
  14181. return MA_INVALID_ARGS;
  14182. }
  14183. /* We need a new slot. */
  14184. result = ma_slot_allocator_alloc(&pQueue->allocator, &slot);
  14185. if (result != MA_SUCCESS) {
  14186. return result; /* Probably ran out of slots. If so, MA_OUT_OF_MEMORY will be returned. */
  14187. }
  14188. /* At this point we should have a slot to place the job. */
  14189. MA_ASSERT(ma_job_extract_slot(slot) < pQueue->capacity);
  14190. /* We need to put the job into memory before we do anything. */
  14191. pQueue->pJobs[ma_job_extract_slot(slot)] = *pJob;
  14192. pQueue->pJobs[ma_job_extract_slot(slot)].toc.allocation = slot; /* This will overwrite the job code. */
  14193. 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. */
  14194. pQueue->pJobs[ma_job_extract_slot(slot)].next = MA_JOB_ID_NONE; /* Reset for safety. */
  14195. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14196. ma_spinlock_lock(&pQueue->lock);
  14197. #endif
  14198. {
  14199. /* 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. */
  14200. for (;;) {
  14201. tail = c89atomic_load_64(&pQueue->tail);
  14202. next = c89atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(tail)].next);
  14203. if (ma_job_toc_to_allocation(tail) == ma_job_toc_to_allocation(c89atomic_load_64(&pQueue->tail))) {
  14204. if (ma_job_extract_slot(next) == 0xFFFF) {
  14205. if (ma_job_queue_cas(&pQueue->pJobs[ma_job_extract_slot(tail)].next, next, slot)) {
  14206. break;
  14207. }
  14208. } else {
  14209. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14210. }
  14211. }
  14212. }
  14213. ma_job_queue_cas(&pQueue->tail, tail, slot);
  14214. }
  14215. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14216. ma_spinlock_unlock(&pQueue->lock);
  14217. #endif
  14218. /* Signal the semaphore as the last step if we're using synchronous mode. */
  14219. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14220. #ifndef MA_NO_THREADING
  14221. {
  14222. ma_semaphore_release(&pQueue->sem);
  14223. }
  14224. #else
  14225. {
  14226. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14227. }
  14228. #endif
  14229. }
  14230. return MA_SUCCESS;
  14231. }
  14232. MA_API ma_result ma_job_queue_next(ma_job_queue* pQueue, ma_job* pJob)
  14233. {
  14234. ma_uint64 head;
  14235. ma_uint64 tail;
  14236. ma_uint64 next;
  14237. if (pQueue == NULL || pJob == NULL) {
  14238. return MA_INVALID_ARGS;
  14239. }
  14240. /* If we're running in synchronous mode we'll need to wait on a semaphore. */
  14241. if ((pQueue->flags & MA_JOB_QUEUE_FLAG_NON_BLOCKING) == 0) {
  14242. #ifndef MA_NO_THREADING
  14243. {
  14244. ma_semaphore_wait(&pQueue->sem);
  14245. }
  14246. #else
  14247. {
  14248. MA_ASSERT(MA_FALSE); /* Should never get here. Should have been checked at initialization time. */
  14249. }
  14250. #endif
  14251. }
  14252. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14253. ma_spinlock_lock(&pQueue->lock);
  14254. #endif
  14255. {
  14256. /*
  14257. BUG: In lock-free mode, multiple threads can be in this section of code. The "head" variable in the loop below
  14258. is stored. One thread can fall through to the freeing of this item while another is still using "head" for the
  14259. retrieval of the "next" variable.
  14260. The slot allocator might need to make use of some reference counting to ensure it's only truely freed when
  14261. there are no more references to the item. This must be fixed before removing these locks.
  14262. */
  14263. /* Now we need to remove the root item from the list. */
  14264. for (;;) {
  14265. head = c89atomic_load_64(&pQueue->head);
  14266. tail = c89atomic_load_64(&pQueue->tail);
  14267. next = c89atomic_load_64(&pQueue->pJobs[ma_job_extract_slot(head)].next);
  14268. if (ma_job_toc_to_allocation(head) == ma_job_toc_to_allocation(c89atomic_load_64(&pQueue->head))) {
  14269. if (ma_job_extract_slot(head) == ma_job_extract_slot(tail)) {
  14270. if (ma_job_extract_slot(next) == 0xFFFF) {
  14271. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14272. ma_spinlock_unlock(&pQueue->lock);
  14273. #endif
  14274. return MA_NO_DATA_AVAILABLE;
  14275. }
  14276. ma_job_queue_cas(&pQueue->tail, tail, ma_job_extract_slot(next));
  14277. } else {
  14278. *pJob = pQueue->pJobs[ma_job_extract_slot(next)];
  14279. if (ma_job_queue_cas(&pQueue->head, head, ma_job_extract_slot(next))) {
  14280. break;
  14281. }
  14282. }
  14283. }
  14284. }
  14285. }
  14286. #ifndef MA_USE_EXPERIMENTAL_LOCK_FREE_JOB_QUEUE
  14287. ma_spinlock_unlock(&pQueue->lock);
  14288. #endif
  14289. ma_slot_allocator_free(&pQueue->allocator, head);
  14290. /*
  14291. 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
  14292. 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
  14293. possible.
  14294. */
  14295. if (pJob->toc.breakup.code == MA_JOB_TYPE_QUIT) {
  14296. ma_job_queue_post(pQueue, pJob);
  14297. return MA_CANCELLED; /* Return a cancelled status just in case the thread is checking return codes and not properly checking for a quit job. */
  14298. }
  14299. return MA_SUCCESS;
  14300. }
  14301. /************************************************************************************************************************************************************
  14302. *************************************************************************************************************************************************************
  14303. DEVICE I/O
  14304. ==========
  14305. *************************************************************************************************************************************************************
  14306. ************************************************************************************************************************************************************/
  14307. #ifndef MA_NO_DEVICE_IO
  14308. #ifdef MA_WIN32
  14309. #include <objbase.h>
  14310. #include <mmreg.h>
  14311. #include <mmsystem.h>
  14312. #endif
  14313. #if defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  14314. #include <mach/mach_time.h> /* For mach_absolute_time() */
  14315. #endif
  14316. #ifdef MA_ANDROID
  14317. #include <sys/system_properties.h>
  14318. #endif
  14319. #ifdef MA_POSIX
  14320. #include <sys/types.h>
  14321. #include <unistd.h>
  14322. #include <dlfcn.h>
  14323. #endif
  14324. /*
  14325. Unfortunately using runtime linking for pthreads causes problems. This has occurred for me when testing on FreeBSD. When
  14326. using runtime linking, deadlocks can occur (for me it happens when loading data from fread()). It turns out that doing
  14327. compile-time linking fixes this. I'm not sure why this happens, but the safest way I can think of to fix this is to simply
  14328. disable runtime linking by default. To enable runtime linking, #define this before the implementation of this file. I am
  14329. not officially supporting this, but I'm leaving it here in case it's useful for somebody, somewhere.
  14330. */
  14331. /*#define MA_USE_RUNTIME_LINKING_FOR_PTHREAD*/
  14332. /* Disable run-time linking on certain backends. */
  14333. #ifndef MA_NO_RUNTIME_LINKING
  14334. #if defined(MA_EMSCRIPTEN)
  14335. #define MA_NO_RUNTIME_LINKING
  14336. #endif
  14337. #endif
  14338. 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)
  14339. {
  14340. if (pDeviceInfo == NULL) {
  14341. return;
  14342. }
  14343. if (pDeviceInfo->nativeDataFormatCount < ma_countof(pDeviceInfo->nativeDataFormats)) {
  14344. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  14345. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  14346. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  14347. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  14348. pDeviceInfo->nativeDataFormatCount += 1;
  14349. }
  14350. }
  14351. MA_API const char* ma_get_backend_name(ma_backend backend)
  14352. {
  14353. switch (backend)
  14354. {
  14355. case ma_backend_wasapi: return "WASAPI";
  14356. case ma_backend_dsound: return "DirectSound";
  14357. case ma_backend_winmm: return "WinMM";
  14358. case ma_backend_coreaudio: return "Core Audio";
  14359. case ma_backend_sndio: return "sndio";
  14360. case ma_backend_audio4: return "audio(4)";
  14361. case ma_backend_oss: return "OSS";
  14362. case ma_backend_pulseaudio: return "PulseAudio";
  14363. case ma_backend_alsa: return "ALSA";
  14364. case ma_backend_jack: return "JACK";
  14365. case ma_backend_aaudio: return "AAudio";
  14366. case ma_backend_opensl: return "OpenSL|ES";
  14367. case ma_backend_webaudio: return "Web Audio";
  14368. case ma_backend_custom: return "Custom";
  14369. case ma_backend_null: return "Null";
  14370. default: return "Unknown";
  14371. }
  14372. }
  14373. MA_API ma_bool32 ma_is_backend_enabled(ma_backend backend)
  14374. {
  14375. /*
  14376. This looks a little bit gross, but we want all backends to be included in the switch to avoid warnings on some compilers
  14377. about some enums not being handled by the switch statement.
  14378. */
  14379. switch (backend)
  14380. {
  14381. case ma_backend_wasapi:
  14382. #if defined(MA_HAS_WASAPI)
  14383. return MA_TRUE;
  14384. #else
  14385. return MA_FALSE;
  14386. #endif
  14387. case ma_backend_dsound:
  14388. #if defined(MA_HAS_DSOUND)
  14389. return MA_TRUE;
  14390. #else
  14391. return MA_FALSE;
  14392. #endif
  14393. case ma_backend_winmm:
  14394. #if defined(MA_HAS_WINMM)
  14395. return MA_TRUE;
  14396. #else
  14397. return MA_FALSE;
  14398. #endif
  14399. case ma_backend_coreaudio:
  14400. #if defined(MA_HAS_COREAUDIO)
  14401. return MA_TRUE;
  14402. #else
  14403. return MA_FALSE;
  14404. #endif
  14405. case ma_backend_sndio:
  14406. #if defined(MA_HAS_SNDIO)
  14407. return MA_TRUE;
  14408. #else
  14409. return MA_FALSE;
  14410. #endif
  14411. case ma_backend_audio4:
  14412. #if defined(MA_HAS_AUDIO4)
  14413. return MA_TRUE;
  14414. #else
  14415. return MA_FALSE;
  14416. #endif
  14417. case ma_backend_oss:
  14418. #if defined(MA_HAS_OSS)
  14419. return MA_TRUE;
  14420. #else
  14421. return MA_FALSE;
  14422. #endif
  14423. case ma_backend_pulseaudio:
  14424. #if defined(MA_HAS_PULSEAUDIO)
  14425. return MA_TRUE;
  14426. #else
  14427. return MA_FALSE;
  14428. #endif
  14429. case ma_backend_alsa:
  14430. #if defined(MA_HAS_ALSA)
  14431. return MA_TRUE;
  14432. #else
  14433. return MA_FALSE;
  14434. #endif
  14435. case ma_backend_jack:
  14436. #if defined(MA_HAS_JACK)
  14437. return MA_TRUE;
  14438. #else
  14439. return MA_FALSE;
  14440. #endif
  14441. case ma_backend_aaudio:
  14442. #if defined(MA_HAS_AAUDIO)
  14443. #if defined(MA_ANDROID)
  14444. {
  14445. char sdkVersion[PROP_VALUE_MAX + 1] = {0, };
  14446. if (__system_property_get("ro.build.version.sdk", sdkVersion)) {
  14447. if (atoi(sdkVersion) >= 26) {
  14448. return MA_TRUE;
  14449. } else {
  14450. return MA_FALSE;
  14451. }
  14452. } else {
  14453. return MA_FALSE;
  14454. }
  14455. }
  14456. #else
  14457. return MA_FALSE;
  14458. #endif
  14459. #else
  14460. return MA_FALSE;
  14461. #endif
  14462. case ma_backend_opensl:
  14463. #if defined(MA_HAS_OPENSL)
  14464. #if defined(MA_ANDROID)
  14465. {
  14466. char sdkVersion[PROP_VALUE_MAX + 1] = {0, };
  14467. if (__system_property_get("ro.build.version.sdk", sdkVersion)) {
  14468. if (atoi(sdkVersion) >= 9) {
  14469. return MA_TRUE;
  14470. } else {
  14471. return MA_FALSE;
  14472. }
  14473. } else {
  14474. return MA_FALSE;
  14475. }
  14476. }
  14477. #else
  14478. return MA_TRUE;
  14479. #endif
  14480. #else
  14481. return MA_FALSE;
  14482. #endif
  14483. case ma_backend_webaudio:
  14484. #if defined(MA_HAS_WEBAUDIO)
  14485. return MA_TRUE;
  14486. #else
  14487. return MA_FALSE;
  14488. #endif
  14489. case ma_backend_custom:
  14490. #if defined(MA_HAS_CUSTOM)
  14491. return MA_TRUE;
  14492. #else
  14493. return MA_FALSE;
  14494. #endif
  14495. case ma_backend_null:
  14496. #if defined(MA_HAS_NULL)
  14497. return MA_TRUE;
  14498. #else
  14499. return MA_FALSE;
  14500. #endif
  14501. default: return MA_FALSE;
  14502. }
  14503. }
  14504. MA_API ma_result ma_get_enabled_backends(ma_backend* pBackends, size_t backendCap, size_t* pBackendCount)
  14505. {
  14506. size_t backendCount;
  14507. size_t iBackend;
  14508. ma_result result = MA_SUCCESS;
  14509. if (pBackendCount == NULL) {
  14510. return MA_INVALID_ARGS;
  14511. }
  14512. backendCount = 0;
  14513. for (iBackend = 0; iBackend <= ma_backend_null; iBackend += 1) {
  14514. ma_backend backend = (ma_backend)iBackend;
  14515. if (ma_is_backend_enabled(backend)) {
  14516. /* The backend is enabled. Try adding it to the list. If there's no room, MA_NO_SPACE needs to be returned. */
  14517. if (backendCount == backendCap) {
  14518. result = MA_NO_SPACE;
  14519. break;
  14520. } else {
  14521. pBackends[backendCount] = backend;
  14522. backendCount += 1;
  14523. }
  14524. }
  14525. }
  14526. if (pBackendCount != NULL) {
  14527. *pBackendCount = backendCount;
  14528. }
  14529. return result;
  14530. }
  14531. MA_API ma_bool32 ma_is_loopback_supported(ma_backend backend)
  14532. {
  14533. switch (backend)
  14534. {
  14535. case ma_backend_wasapi: return MA_TRUE;
  14536. case ma_backend_dsound: return MA_FALSE;
  14537. case ma_backend_winmm: return MA_FALSE;
  14538. case ma_backend_coreaudio: return MA_FALSE;
  14539. case ma_backend_sndio: return MA_FALSE;
  14540. case ma_backend_audio4: return MA_FALSE;
  14541. case ma_backend_oss: return MA_FALSE;
  14542. case ma_backend_pulseaudio: return MA_FALSE;
  14543. case ma_backend_alsa: return MA_FALSE;
  14544. case ma_backend_jack: return MA_FALSE;
  14545. case ma_backend_aaudio: return MA_FALSE;
  14546. case ma_backend_opensl: return MA_FALSE;
  14547. case ma_backend_webaudio: return MA_FALSE;
  14548. case ma_backend_custom: return MA_FALSE; /* <-- Will depend on the implementation of the backend. */
  14549. case ma_backend_null: return MA_FALSE;
  14550. default: return MA_FALSE;
  14551. }
  14552. }
  14553. #ifdef MA_WIN32
  14554. /* WASAPI error codes. */
  14555. #define MA_AUDCLNT_E_NOT_INITIALIZED ((HRESULT)0x88890001)
  14556. #define MA_AUDCLNT_E_ALREADY_INITIALIZED ((HRESULT)0x88890002)
  14557. #define MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE ((HRESULT)0x88890003)
  14558. #define MA_AUDCLNT_E_DEVICE_INVALIDATED ((HRESULT)0x88890004)
  14559. #define MA_AUDCLNT_E_NOT_STOPPED ((HRESULT)0x88890005)
  14560. #define MA_AUDCLNT_E_BUFFER_TOO_LARGE ((HRESULT)0x88890006)
  14561. #define MA_AUDCLNT_E_OUT_OF_ORDER ((HRESULT)0x88890007)
  14562. #define MA_AUDCLNT_E_UNSUPPORTED_FORMAT ((HRESULT)0x88890008)
  14563. #define MA_AUDCLNT_E_INVALID_SIZE ((HRESULT)0x88890009)
  14564. #define MA_AUDCLNT_E_DEVICE_IN_USE ((HRESULT)0x8889000A)
  14565. #define MA_AUDCLNT_E_BUFFER_OPERATION_PENDING ((HRESULT)0x8889000B)
  14566. #define MA_AUDCLNT_E_THREAD_NOT_REGISTERED ((HRESULT)0x8889000C)
  14567. #define MA_AUDCLNT_E_NO_SINGLE_PROCESS ((HRESULT)0x8889000D)
  14568. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED ((HRESULT)0x8889000E)
  14569. #define MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED ((HRESULT)0x8889000F)
  14570. #define MA_AUDCLNT_E_SERVICE_NOT_RUNNING ((HRESULT)0x88890010)
  14571. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED ((HRESULT)0x88890011)
  14572. #define MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY ((HRESULT)0x88890012)
  14573. #define MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL ((HRESULT)0x88890013)
  14574. #define MA_AUDCLNT_E_EVENTHANDLE_NOT_SET ((HRESULT)0x88890014)
  14575. #define MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE ((HRESULT)0x88890015)
  14576. #define MA_AUDCLNT_E_BUFFER_SIZE_ERROR ((HRESULT)0x88890016)
  14577. #define MA_AUDCLNT_E_CPUUSAGE_EXCEEDED ((HRESULT)0x88890017)
  14578. #define MA_AUDCLNT_E_BUFFER_ERROR ((HRESULT)0x88890018)
  14579. #define MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED ((HRESULT)0x88890019)
  14580. #define MA_AUDCLNT_E_INVALID_DEVICE_PERIOD ((HRESULT)0x88890020)
  14581. #define MA_AUDCLNT_E_INVALID_STREAM_FLAG ((HRESULT)0x88890021)
  14582. #define MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE ((HRESULT)0x88890022)
  14583. #define MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES ((HRESULT)0x88890023)
  14584. #define MA_AUDCLNT_E_OFFLOAD_MODE_ONLY ((HRESULT)0x88890024)
  14585. #define MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY ((HRESULT)0x88890025)
  14586. #define MA_AUDCLNT_E_RESOURCES_INVALIDATED ((HRESULT)0x88890026)
  14587. #define MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED ((HRESULT)0x88890027)
  14588. #define MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED ((HRESULT)0x88890028)
  14589. #define MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED ((HRESULT)0x88890029)
  14590. #define MA_AUDCLNT_E_HEADTRACKING_ENABLED ((HRESULT)0x88890030)
  14591. #define MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED ((HRESULT)0x88890040)
  14592. #define MA_AUDCLNT_S_BUFFER_EMPTY ((HRESULT)0x08890001)
  14593. #define MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED ((HRESULT)0x08890002)
  14594. #define MA_AUDCLNT_S_POSITION_STALLED ((HRESULT)0x08890003)
  14595. #define MA_DS_OK ((HRESULT)0)
  14596. #define MA_DS_NO_VIRTUALIZATION ((HRESULT)0x0878000A)
  14597. #define MA_DSERR_ALLOCATED ((HRESULT)0x8878000A)
  14598. #define MA_DSERR_CONTROLUNAVAIL ((HRESULT)0x8878001E)
  14599. #define MA_DSERR_INVALIDPARAM ((HRESULT)0x80070057) /*E_INVALIDARG*/
  14600. #define MA_DSERR_INVALIDCALL ((HRESULT)0x88780032)
  14601. #define MA_DSERR_GENERIC ((HRESULT)0x80004005) /*E_FAIL*/
  14602. #define MA_DSERR_PRIOLEVELNEEDED ((HRESULT)0x88780046)
  14603. #define MA_DSERR_OUTOFMEMORY ((HRESULT)0x8007000E) /*E_OUTOFMEMORY*/
  14604. #define MA_DSERR_BADFORMAT ((HRESULT)0x88780064)
  14605. #define MA_DSERR_UNSUPPORTED ((HRESULT)0x80004001) /*E_NOTIMPL*/
  14606. #define MA_DSERR_NODRIVER ((HRESULT)0x88780078)
  14607. #define MA_DSERR_ALREADYINITIALIZED ((HRESULT)0x88780082)
  14608. #define MA_DSERR_NOAGGREGATION ((HRESULT)0x80040110) /*CLASS_E_NOAGGREGATION*/
  14609. #define MA_DSERR_BUFFERLOST ((HRESULT)0x88780096)
  14610. #define MA_DSERR_OTHERAPPHASPRIO ((HRESULT)0x887800A0)
  14611. #define MA_DSERR_UNINITIALIZED ((HRESULT)0x887800AA)
  14612. #define MA_DSERR_NOINTERFACE ((HRESULT)0x80004002) /*E_NOINTERFACE*/
  14613. #define MA_DSERR_ACCESSDENIED ((HRESULT)0x80070005) /*E_ACCESSDENIED*/
  14614. #define MA_DSERR_BUFFERTOOSMALL ((HRESULT)0x887800B4)
  14615. #define MA_DSERR_DS8_REQUIRED ((HRESULT)0x887800BE)
  14616. #define MA_DSERR_SENDLOOP ((HRESULT)0x887800C8)
  14617. #define MA_DSERR_BADSENDBUFFERGUID ((HRESULT)0x887800D2)
  14618. #define MA_DSERR_OBJECTNOTFOUND ((HRESULT)0x88781161)
  14619. #define MA_DSERR_FXUNAVAILABLE ((HRESULT)0x887800DC)
  14620. static ma_result ma_result_from_HRESULT(HRESULT hr)
  14621. {
  14622. switch (hr)
  14623. {
  14624. case NOERROR: return MA_SUCCESS;
  14625. /*case S_OK: return MA_SUCCESS;*/
  14626. case E_POINTER: return MA_INVALID_ARGS;
  14627. case E_UNEXPECTED: return MA_ERROR;
  14628. case E_NOTIMPL: return MA_NOT_IMPLEMENTED;
  14629. case E_OUTOFMEMORY: return MA_OUT_OF_MEMORY;
  14630. case E_INVALIDARG: return MA_INVALID_ARGS;
  14631. case E_NOINTERFACE: return MA_API_NOT_FOUND;
  14632. case E_HANDLE: return MA_INVALID_ARGS;
  14633. case E_ABORT: return MA_ERROR;
  14634. case E_FAIL: return MA_ERROR;
  14635. case E_ACCESSDENIED: return MA_ACCESS_DENIED;
  14636. /* WASAPI */
  14637. case MA_AUDCLNT_E_NOT_INITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  14638. case MA_AUDCLNT_E_ALREADY_INITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  14639. case MA_AUDCLNT_E_WRONG_ENDPOINT_TYPE: return MA_INVALID_ARGS;
  14640. case MA_AUDCLNT_E_DEVICE_INVALIDATED: return MA_UNAVAILABLE;
  14641. case MA_AUDCLNT_E_NOT_STOPPED: return MA_DEVICE_NOT_STOPPED;
  14642. case MA_AUDCLNT_E_BUFFER_TOO_LARGE: return MA_TOO_BIG;
  14643. case MA_AUDCLNT_E_OUT_OF_ORDER: return MA_INVALID_OPERATION;
  14644. case MA_AUDCLNT_E_UNSUPPORTED_FORMAT: return MA_FORMAT_NOT_SUPPORTED;
  14645. case MA_AUDCLNT_E_INVALID_SIZE: return MA_INVALID_ARGS;
  14646. case MA_AUDCLNT_E_DEVICE_IN_USE: return MA_BUSY;
  14647. case MA_AUDCLNT_E_BUFFER_OPERATION_PENDING: return MA_INVALID_OPERATION;
  14648. case MA_AUDCLNT_E_THREAD_NOT_REGISTERED: return MA_DOES_NOT_EXIST;
  14649. case MA_AUDCLNT_E_NO_SINGLE_PROCESS: return MA_INVALID_OPERATION;
  14650. case MA_AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: return MA_SHARE_MODE_NOT_SUPPORTED;
  14651. case MA_AUDCLNT_E_ENDPOINT_CREATE_FAILED: return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  14652. case MA_AUDCLNT_E_SERVICE_NOT_RUNNING: return MA_NOT_CONNECTED;
  14653. case MA_AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: return MA_INVALID_ARGS;
  14654. case MA_AUDCLNT_E_EXCLUSIVE_MODE_ONLY: return MA_SHARE_MODE_NOT_SUPPORTED;
  14655. case MA_AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: return MA_INVALID_ARGS;
  14656. case MA_AUDCLNT_E_EVENTHANDLE_NOT_SET: return MA_INVALID_ARGS;
  14657. case MA_AUDCLNT_E_INCORRECT_BUFFER_SIZE: return MA_INVALID_ARGS;
  14658. case MA_AUDCLNT_E_BUFFER_SIZE_ERROR: return MA_INVALID_ARGS;
  14659. case MA_AUDCLNT_E_CPUUSAGE_EXCEEDED: return MA_ERROR;
  14660. case MA_AUDCLNT_E_BUFFER_ERROR: return MA_ERROR;
  14661. case MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED: return MA_INVALID_ARGS;
  14662. case MA_AUDCLNT_E_INVALID_DEVICE_PERIOD: return MA_INVALID_ARGS;
  14663. case MA_AUDCLNT_E_INVALID_STREAM_FLAG: return MA_INVALID_ARGS;
  14664. case MA_AUDCLNT_E_ENDPOINT_OFFLOAD_NOT_CAPABLE: return MA_INVALID_OPERATION;
  14665. case MA_AUDCLNT_E_OUT_OF_OFFLOAD_RESOURCES: return MA_OUT_OF_MEMORY;
  14666. case MA_AUDCLNT_E_OFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  14667. case MA_AUDCLNT_E_NONOFFLOAD_MODE_ONLY: return MA_INVALID_OPERATION;
  14668. case MA_AUDCLNT_E_RESOURCES_INVALIDATED: return MA_INVALID_DATA;
  14669. case MA_AUDCLNT_E_RAW_MODE_UNSUPPORTED: return MA_INVALID_OPERATION;
  14670. case MA_AUDCLNT_E_ENGINE_PERIODICITY_LOCKED: return MA_INVALID_OPERATION;
  14671. case MA_AUDCLNT_E_ENGINE_FORMAT_LOCKED: return MA_INVALID_OPERATION;
  14672. case MA_AUDCLNT_E_HEADTRACKING_ENABLED: return MA_INVALID_OPERATION;
  14673. case MA_AUDCLNT_E_HEADTRACKING_UNSUPPORTED: return MA_INVALID_OPERATION;
  14674. case MA_AUDCLNT_S_BUFFER_EMPTY: return MA_NO_SPACE;
  14675. case MA_AUDCLNT_S_THREAD_ALREADY_REGISTERED: return MA_ALREADY_EXISTS;
  14676. case MA_AUDCLNT_S_POSITION_STALLED: return MA_ERROR;
  14677. /* DirectSound */
  14678. /*case MA_DS_OK: return MA_SUCCESS;*/ /* S_OK */
  14679. case MA_DS_NO_VIRTUALIZATION: return MA_SUCCESS;
  14680. case MA_DSERR_ALLOCATED: return MA_ALREADY_IN_USE;
  14681. case MA_DSERR_CONTROLUNAVAIL: return MA_INVALID_OPERATION;
  14682. /*case MA_DSERR_INVALIDPARAM: return MA_INVALID_ARGS;*/ /* E_INVALIDARG */
  14683. case MA_DSERR_INVALIDCALL: return MA_INVALID_OPERATION;
  14684. /*case MA_DSERR_GENERIC: return MA_ERROR;*/ /* E_FAIL */
  14685. case MA_DSERR_PRIOLEVELNEEDED: return MA_INVALID_OPERATION;
  14686. /*case MA_DSERR_OUTOFMEMORY: return MA_OUT_OF_MEMORY;*/ /* E_OUTOFMEMORY */
  14687. case MA_DSERR_BADFORMAT: return MA_FORMAT_NOT_SUPPORTED;
  14688. /*case MA_DSERR_UNSUPPORTED: return MA_NOT_IMPLEMENTED;*/ /* E_NOTIMPL */
  14689. case MA_DSERR_NODRIVER: return MA_FAILED_TO_INIT_BACKEND;
  14690. case MA_DSERR_ALREADYINITIALIZED: return MA_DEVICE_ALREADY_INITIALIZED;
  14691. case MA_DSERR_NOAGGREGATION: return MA_ERROR;
  14692. case MA_DSERR_BUFFERLOST: return MA_UNAVAILABLE;
  14693. case MA_DSERR_OTHERAPPHASPRIO: return MA_ACCESS_DENIED;
  14694. case MA_DSERR_UNINITIALIZED: return MA_DEVICE_NOT_INITIALIZED;
  14695. /*case MA_DSERR_NOINTERFACE: return MA_API_NOT_FOUND;*/ /* E_NOINTERFACE */
  14696. /*case MA_DSERR_ACCESSDENIED: return MA_ACCESS_DENIED;*/ /* E_ACCESSDENIED */
  14697. case MA_DSERR_BUFFERTOOSMALL: return MA_NO_SPACE;
  14698. case MA_DSERR_DS8_REQUIRED: return MA_INVALID_OPERATION;
  14699. case MA_DSERR_SENDLOOP: return MA_DEADLOCK;
  14700. case MA_DSERR_BADSENDBUFFERGUID: return MA_INVALID_ARGS;
  14701. case MA_DSERR_OBJECTNOTFOUND: return MA_NO_DEVICE;
  14702. case MA_DSERR_FXUNAVAILABLE: return MA_UNAVAILABLE;
  14703. default: return MA_ERROR;
  14704. }
  14705. }
  14706. typedef HRESULT (WINAPI * MA_PFN_CoInitializeEx)(LPVOID pvReserved, DWORD dwCoInit);
  14707. typedef void (WINAPI * MA_PFN_CoUninitialize)(void);
  14708. typedef HRESULT (WINAPI * MA_PFN_CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv);
  14709. typedef void (WINAPI * MA_PFN_CoTaskMemFree)(LPVOID pv);
  14710. typedef HRESULT (WINAPI * MA_PFN_PropVariantClear)(PROPVARIANT *pvar);
  14711. typedef int (WINAPI * MA_PFN_StringFromGUID2)(const GUID* const rguid, LPOLESTR lpsz, int cchMax);
  14712. typedef HWND (WINAPI * MA_PFN_GetForegroundWindow)(void);
  14713. typedef HWND (WINAPI * MA_PFN_GetDesktopWindow)(void);
  14714. #if defined(MA_WIN32_DESKTOP)
  14715. /* Microsoft documents these APIs as returning LSTATUS, but the Win32 API shipping with some compilers do not define it. It's just a LONG. */
  14716. typedef LONG (WINAPI * MA_PFN_RegOpenKeyExA)(HKEY hKey, LPCSTR lpSubKey, DWORD ulOptions, REGSAM samDesired, PHKEY phkResult);
  14717. typedef LONG (WINAPI * MA_PFN_RegCloseKey)(HKEY hKey);
  14718. typedef LONG (WINAPI * MA_PFN_RegQueryValueExA)(HKEY hKey, LPCSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData);
  14719. #endif /* MA_WIN32_DESKTOP */
  14720. #endif /* MA_WIN32 */
  14721. #define MA_DEFAULT_PLAYBACK_DEVICE_NAME "Default Playback Device"
  14722. #define MA_DEFAULT_CAPTURE_DEVICE_NAME "Default Capture Device"
  14723. /*******************************************************************************
  14724. Timing
  14725. *******************************************************************************/
  14726. #ifdef MA_WIN32
  14727. static LARGE_INTEGER g_ma_TimerFrequency; /* <-- Initialized to zero since it's static. */
  14728. void ma_timer_init(ma_timer* pTimer)
  14729. {
  14730. LARGE_INTEGER counter;
  14731. if (g_ma_TimerFrequency.QuadPart == 0) {
  14732. QueryPerformanceFrequency(&g_ma_TimerFrequency);
  14733. }
  14734. QueryPerformanceCounter(&counter);
  14735. pTimer->counter = counter.QuadPart;
  14736. }
  14737. double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  14738. {
  14739. LARGE_INTEGER counter;
  14740. if (!QueryPerformanceCounter(&counter)) {
  14741. return 0;
  14742. }
  14743. return (double)(counter.QuadPart - pTimer->counter) / g_ma_TimerFrequency.QuadPart;
  14744. }
  14745. #elif defined(MA_APPLE) && (__MAC_OS_X_VERSION_MIN_REQUIRED < 101200)
  14746. static ma_uint64 g_ma_TimerFrequency = 0;
  14747. static void ma_timer_init(ma_timer* pTimer)
  14748. {
  14749. mach_timebase_info_data_t baseTime;
  14750. mach_timebase_info(&baseTime);
  14751. g_ma_TimerFrequency = (baseTime.denom * 1e9) / baseTime.numer;
  14752. pTimer->counter = mach_absolute_time();
  14753. }
  14754. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  14755. {
  14756. ma_uint64 newTimeCounter = mach_absolute_time();
  14757. ma_uint64 oldTimeCounter = pTimer->counter;
  14758. return (newTimeCounter - oldTimeCounter) / g_ma_TimerFrequency;
  14759. }
  14760. #elif defined(MA_EMSCRIPTEN)
  14761. static MA_INLINE void ma_timer_init(ma_timer* pTimer)
  14762. {
  14763. pTimer->counterD = emscripten_get_now();
  14764. }
  14765. static MA_INLINE double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  14766. {
  14767. return (emscripten_get_now() - pTimer->counterD) / 1000; /* Emscripten is in milliseconds. */
  14768. }
  14769. #else
  14770. #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 199309L
  14771. #if defined(CLOCK_MONOTONIC)
  14772. #define MA_CLOCK_ID CLOCK_MONOTONIC
  14773. #else
  14774. #define MA_CLOCK_ID CLOCK_REALTIME
  14775. #endif
  14776. static void ma_timer_init(ma_timer* pTimer)
  14777. {
  14778. struct timespec newTime;
  14779. clock_gettime(MA_CLOCK_ID, &newTime);
  14780. pTimer->counter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  14781. }
  14782. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  14783. {
  14784. ma_uint64 newTimeCounter;
  14785. ma_uint64 oldTimeCounter;
  14786. struct timespec newTime;
  14787. clock_gettime(MA_CLOCK_ID, &newTime);
  14788. newTimeCounter = (newTime.tv_sec * 1000000000) + newTime.tv_nsec;
  14789. oldTimeCounter = pTimer->counter;
  14790. return (newTimeCounter - oldTimeCounter) / 1000000000.0;
  14791. }
  14792. #else
  14793. static void ma_timer_init(ma_timer* pTimer)
  14794. {
  14795. struct timeval newTime;
  14796. gettimeofday(&newTime, NULL);
  14797. pTimer->counter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  14798. }
  14799. static double ma_timer_get_time_in_seconds(ma_timer* pTimer)
  14800. {
  14801. ma_uint64 newTimeCounter;
  14802. ma_uint64 oldTimeCounter;
  14803. struct timeval newTime;
  14804. gettimeofday(&newTime, NULL);
  14805. newTimeCounter = (newTime.tv_sec * 1000000) + newTime.tv_usec;
  14806. oldTimeCounter = pTimer->counter;
  14807. return (newTimeCounter - oldTimeCounter) / 1000000.0;
  14808. }
  14809. #endif
  14810. #endif
  14811. /*******************************************************************************
  14812. Dynamic Linking
  14813. *******************************************************************************/
  14814. MA_API ma_handle ma_dlopen(ma_context* pContext, const char* filename)
  14815. {
  14816. ma_handle handle;
  14817. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Loading library: %s\n", filename);
  14818. #ifdef _WIN32
  14819. /* From MSDN: Desktop applications cannot use LoadPackagedLibrary; if a desktop application calls this function it fails with APPMODEL_ERROR_NO_PACKAGE.*/
  14820. #if !defined(WINAPI_FAMILY) || (defined(WINAPI_FAMILY) && (defined(WINAPI_FAMILY_DESKTOP_APP) && WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
  14821. handle = (ma_handle)LoadLibraryA(filename);
  14822. #else
  14823. /* *sigh* It appears there is no ANSI version of LoadPackagedLibrary()... */
  14824. WCHAR filenameW[4096];
  14825. if (MultiByteToWideChar(CP_UTF8, 0, filename, -1, filenameW, sizeof(filenameW)) == 0) {
  14826. handle = NULL;
  14827. } else {
  14828. handle = (ma_handle)LoadPackagedLibrary(filenameW, 0);
  14829. }
  14830. #endif
  14831. #else
  14832. handle = (ma_handle)dlopen(filename, RTLD_NOW);
  14833. #endif
  14834. /*
  14835. I'm not considering failure to load a library an error nor a warning because seamlessly falling through to a lower-priority
  14836. backend is a deliberate design choice. Instead I'm logging it as an informational message.
  14837. */
  14838. if (handle == NULL) {
  14839. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "Failed to load library: %s\n", filename);
  14840. }
  14841. (void)pContext; /* It's possible for pContext to be unused. */
  14842. return handle;
  14843. }
  14844. MA_API void ma_dlclose(ma_context* pContext, ma_handle handle)
  14845. {
  14846. #ifdef _WIN32
  14847. FreeLibrary((HMODULE)handle);
  14848. #else
  14849. dlclose((void*)handle);
  14850. #endif
  14851. (void)pContext;
  14852. }
  14853. MA_API ma_proc ma_dlsym(ma_context* pContext, ma_handle handle, const char* symbol)
  14854. {
  14855. ma_proc proc;
  14856. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Loading symbol: %s\n", symbol);
  14857. #ifdef _WIN32
  14858. proc = (ma_proc)GetProcAddress((HMODULE)handle, symbol);
  14859. #else
  14860. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  14861. #pragma GCC diagnostic push
  14862. #pragma GCC diagnostic ignored "-Wpedantic"
  14863. #endif
  14864. proc = (ma_proc)dlsym((void*)handle, symbol);
  14865. #if defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  14866. #pragma GCC diagnostic pop
  14867. #endif
  14868. #endif
  14869. if (proc == NULL) {
  14870. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Failed to load symbol: %s\n", symbol);
  14871. }
  14872. (void)pContext; /* It's possible for pContext to be unused. */
  14873. return proc;
  14874. }
  14875. #if 0
  14876. static ma_uint32 ma_get_closest_standard_sample_rate(ma_uint32 sampleRateIn)
  14877. {
  14878. ma_uint32 closestRate = 0;
  14879. ma_uint32 closestDiff = 0xFFFFFFFF;
  14880. size_t iStandardRate;
  14881. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  14882. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  14883. ma_uint32 diff;
  14884. if (sampleRateIn > standardRate) {
  14885. diff = sampleRateIn - standardRate;
  14886. } else {
  14887. diff = standardRate - sampleRateIn;
  14888. }
  14889. if (diff == 0) {
  14890. return standardRate; /* The input sample rate is a standard rate. */
  14891. }
  14892. if (closestDiff > diff) {
  14893. closestDiff = diff;
  14894. closestRate = standardRate;
  14895. }
  14896. }
  14897. return closestRate;
  14898. }
  14899. #endif
  14900. static MA_INLINE unsigned int ma_device_disable_denormals(ma_device* pDevice)
  14901. {
  14902. MA_ASSERT(pDevice != NULL);
  14903. if (!pDevice->noDisableDenormals) {
  14904. return ma_disable_denormals();
  14905. } else {
  14906. return 0;
  14907. }
  14908. }
  14909. static MA_INLINE void ma_device_restore_denormals(ma_device* pDevice, unsigned int prevState)
  14910. {
  14911. MA_ASSERT(pDevice != NULL);
  14912. if (!pDevice->noDisableDenormals) {
  14913. ma_restore_denormals(prevState);
  14914. } else {
  14915. /* Do nothing. */
  14916. (void)prevState;
  14917. }
  14918. }
  14919. static ma_device_notification ma_device_notification_init(ma_device* pDevice, ma_device_notification_type type)
  14920. {
  14921. ma_device_notification notification;
  14922. MA_ZERO_OBJECT(&notification);
  14923. notification.pDevice = pDevice;
  14924. notification.type = type;
  14925. return notification;
  14926. }
  14927. static void ma_device__on_notification(ma_device_notification notification)
  14928. {
  14929. MA_ASSERT(notification.pDevice != NULL);
  14930. if (notification.pDevice->onNotification != NULL) {
  14931. notification.pDevice->onNotification(&notification);
  14932. }
  14933. /* 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. */
  14934. if (notification.pDevice->onStop != NULL && notification.type == ma_device_notification_type_stopped) {
  14935. notification.pDevice->onStop(notification.pDevice);
  14936. }
  14937. }
  14938. void ma_device__on_notification_started(ma_device* pDevice)
  14939. {
  14940. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_started));
  14941. }
  14942. void ma_device__on_notification_stopped(ma_device* pDevice)
  14943. {
  14944. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_stopped));
  14945. }
  14946. void ma_device__on_notification_rerouted(ma_device* pDevice)
  14947. {
  14948. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_rerouted));
  14949. }
  14950. void ma_device__on_notification_interruption_began(ma_device* pDevice)
  14951. {
  14952. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_began));
  14953. }
  14954. void ma_device__on_notification_interruption_ended(ma_device* pDevice)
  14955. {
  14956. ma_device__on_notification(ma_device_notification_init(pDevice, ma_device_notification_type_interruption_ended));
  14957. }
  14958. static void ma_device__on_data_inner(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  14959. {
  14960. MA_ASSERT(pDevice != NULL);
  14961. MA_ASSERT(pDevice->onData != NULL);
  14962. if (!pDevice->noPreSilencedOutputBuffer && pFramesOut != NULL) {
  14963. ma_silence_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels);
  14964. }
  14965. pDevice->onData(pDevice, pFramesOut, pFramesIn, frameCount);
  14966. }
  14967. static void ma_device__on_data(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  14968. {
  14969. MA_ASSERT(pDevice != NULL);
  14970. /* Don't read more data from the client if we're in the process of stopping. */
  14971. if (ma_device_get_state(pDevice) == ma_device_state_stopping) {
  14972. return;
  14973. }
  14974. if (pDevice->noFixedSizedCallback) {
  14975. /* Fast path. Not using a fixed sized callback. Process directly from the specified buffers. */
  14976. ma_device__on_data_inner(pDevice, pFramesOut, pFramesIn, frameCount);
  14977. } else {
  14978. /* Slow path. Using a fixed sized callback. Need to use the intermediary buffer. */
  14979. ma_uint32 totalFramesProcessed = 0;
  14980. while (totalFramesProcessed < frameCount) {
  14981. ma_uint32 totalFramesRemaining = frameCount - totalFramesProcessed;
  14982. ma_uint32 framesToProcessThisIteration = 0;
  14983. if (pFramesIn != NULL) {
  14984. /* Capturing. Write to the intermediary buffer. If there's no room, fire the callback to empty it. */
  14985. if (pDevice->capture.intermediaryBufferLen < pDevice->capture.intermediaryBufferCap) {
  14986. /* There's some room left in the intermediary buffer. Write to it without firing the callback. */
  14987. framesToProcessThisIteration = totalFramesRemaining;
  14988. if (framesToProcessThisIteration > pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen) {
  14989. framesToProcessThisIteration = pDevice->capture.intermediaryBufferCap - pDevice->capture.intermediaryBufferLen;
  14990. }
  14991. ma_copy_pcm_frames(
  14992. ma_offset_pcm_frames_ptr(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferLen, pDevice->capture.format, pDevice->capture.channels),
  14993. ma_offset_pcm_frames_const_ptr(pFramesIn, totalFramesProcessed, pDevice->capture.format, pDevice->capture.channels),
  14994. framesToProcessThisIteration,
  14995. pDevice->capture.format, pDevice->capture.channels);
  14996. pDevice->capture.intermediaryBufferLen += framesToProcessThisIteration;
  14997. }
  14998. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  14999. /* No room left in the intermediary buffer. Fire the data callback. */
  15000. if (pDevice->type == ma_device_type_duplex) {
  15001. /* We'll do the duplex data callback later after we've processed the playback data. */
  15002. } else {
  15003. ma_device__on_data_inner(pDevice, NULL, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15004. /* The intermediary buffer has just been drained. */
  15005. pDevice->capture.intermediaryBufferLen = 0;
  15006. }
  15007. }
  15008. }
  15009. if (pFramesOut != NULL) {
  15010. /* Playing back. Read from the intermediary buffer. If there's nothing in it, fire the callback to fill it. */
  15011. if (pDevice->playback.intermediaryBufferLen > 0) {
  15012. /* There's some content in the intermediary buffer. Read from that without firing the callback. */
  15013. if (pDevice->type == ma_device_type_duplex) {
  15014. /* The frames processed this iteration for a duplex device will always be based on the capture side. Leave it unmodified. */
  15015. } else {
  15016. framesToProcessThisIteration = totalFramesRemaining;
  15017. if (framesToProcessThisIteration > pDevice->playback.intermediaryBufferLen) {
  15018. framesToProcessThisIteration = pDevice->playback.intermediaryBufferLen;
  15019. }
  15020. }
  15021. ma_copy_pcm_frames(
  15022. ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, pDevice->playback.format, pDevice->playback.channels),
  15023. ma_offset_pcm_frames_ptr(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap - pDevice->playback.intermediaryBufferLen, pDevice->playback.format, pDevice->playback.channels),
  15024. framesToProcessThisIteration,
  15025. pDevice->playback.format, pDevice->playback.channels);
  15026. pDevice->playback.intermediaryBufferLen -= framesToProcessThisIteration;
  15027. }
  15028. if (pDevice->playback.intermediaryBufferLen == 0) {
  15029. /* There's nothing in the intermediary buffer. Fire the data callback to fill it. */
  15030. if (pDevice->type == ma_device_type_duplex) {
  15031. /* In duplex mode, the data callback will be fired later. Nothing to do here. */
  15032. } else {
  15033. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, NULL, pDevice->playback.intermediaryBufferCap);
  15034. /* The intermediary buffer has just been filled. */
  15035. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap;
  15036. }
  15037. }
  15038. }
  15039. /* If we're in duplex mode we might need to do a refill of the data. */
  15040. if (pDevice->type == ma_device_type_duplex) {
  15041. if (pDevice->capture.intermediaryBufferLen == pDevice->capture.intermediaryBufferCap) {
  15042. ma_device__on_data_inner(pDevice, pDevice->playback.pIntermediaryBuffer, pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap);
  15043. pDevice->playback.intermediaryBufferLen = pDevice->playback.intermediaryBufferCap; /* The playback buffer will have just been filled. */
  15044. pDevice->capture.intermediaryBufferLen = 0; /* The intermediary buffer has just been drained. */
  15045. }
  15046. }
  15047. /* Make sure this is only incremented once in the duplex case. */
  15048. totalFramesProcessed += framesToProcessThisIteration;
  15049. }
  15050. }
  15051. }
  15052. static void ma_device__handle_data_callback(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  15053. {
  15054. float masterVolumeFactor;
  15055. ma_device_get_master_volume(pDevice, &masterVolumeFactor); /* Use ma_device_get_master_volume() to ensure the volume is loaded atomically. */
  15056. if (pDevice->onData) {
  15057. unsigned int prevDenormalState = ma_device_disable_denormals(pDevice);
  15058. {
  15059. /* 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. */
  15060. if (pFramesIn != NULL && masterVolumeFactor < 1) {
  15061. ma_uint8 tempFramesIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15062. ma_uint32 bpfCapture = ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15063. ma_uint32 bpfPlayback = ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15064. ma_uint32 totalFramesProcessed = 0;
  15065. while (totalFramesProcessed < frameCount) {
  15066. ma_uint32 framesToProcessThisIteration = frameCount - totalFramesProcessed;
  15067. if (framesToProcessThisIteration > sizeof(tempFramesIn)/bpfCapture) {
  15068. framesToProcessThisIteration = sizeof(tempFramesIn)/bpfCapture;
  15069. }
  15070. ma_copy_and_apply_volume_factor_pcm_frames(tempFramesIn, ma_offset_ptr(pFramesIn, totalFramesProcessed*bpfCapture), framesToProcessThisIteration, pDevice->capture.format, pDevice->capture.channels, masterVolumeFactor);
  15071. ma_device__on_data(pDevice, ma_offset_ptr(pFramesOut, totalFramesProcessed*bpfPlayback), tempFramesIn, framesToProcessThisIteration);
  15072. totalFramesProcessed += framesToProcessThisIteration;
  15073. }
  15074. } else {
  15075. ma_device__on_data(pDevice, pFramesOut, pFramesIn, frameCount);
  15076. }
  15077. /* Volume control and clipping for playback devices. */
  15078. if (pFramesOut != NULL) {
  15079. if (masterVolumeFactor < 1) {
  15080. 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. */
  15081. ma_apply_volume_factor_pcm_frames(pFramesOut, frameCount, pDevice->playback.format, pDevice->playback.channels, masterVolumeFactor);
  15082. }
  15083. }
  15084. if (!pDevice->noClip && pDevice->playback.format == ma_format_f32) {
  15085. 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. */
  15086. }
  15087. }
  15088. }
  15089. ma_device_restore_denormals(pDevice, prevDenormalState);
  15090. }
  15091. }
  15092. /* A helper function for reading sample data from the client. */
  15093. static void ma_device__read_frames_from_client(ma_device* pDevice, ma_uint32 frameCount, void* pFramesOut)
  15094. {
  15095. MA_ASSERT(pDevice != NULL);
  15096. MA_ASSERT(frameCount > 0);
  15097. MA_ASSERT(pFramesOut != NULL);
  15098. if (pDevice->playback.converter.isPassthrough) {
  15099. ma_device__handle_data_callback(pDevice, pFramesOut, NULL, frameCount);
  15100. } else {
  15101. ma_result result;
  15102. ma_uint64 totalFramesReadOut;
  15103. void* pRunningFramesOut;
  15104. totalFramesReadOut = 0;
  15105. pRunningFramesOut = pFramesOut;
  15106. /*
  15107. We run slightly different logic depending on whether or not we're using a heap-allocated
  15108. buffer for caching input data. This will be the case if the data converter does not have
  15109. the ability to retrieve the required input frame count for a given output frame count.
  15110. */
  15111. if (pDevice->playback.pInputCache != NULL) {
  15112. while (totalFramesReadOut < frameCount) {
  15113. ma_uint64 framesToReadThisIterationIn;
  15114. ma_uint64 framesToReadThisIterationOut;
  15115. /* If there's any data available in the cache, that needs to get processed first. */
  15116. if (pDevice->playback.inputCacheRemaining > 0) {
  15117. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15118. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15119. if (framesToReadThisIterationIn > pDevice->playback.inputCacheRemaining) {
  15120. framesToReadThisIterationIn = pDevice->playback.inputCacheRemaining;
  15121. }
  15122. 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);
  15123. if (result != MA_SUCCESS) {
  15124. break;
  15125. }
  15126. pDevice->playback.inputCacheConsumed += framesToReadThisIterationIn;
  15127. pDevice->playback.inputCacheRemaining -= framesToReadThisIterationIn;
  15128. totalFramesReadOut += framesToReadThisIterationOut;
  15129. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15130. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  15131. break; /* We're done. */
  15132. }
  15133. }
  15134. /* Getting here means there's no data in the cache and we need to fill it up with data from the client. */
  15135. if (pDevice->playback.inputCacheRemaining == 0) {
  15136. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, NULL, (ma_uint32)pDevice->playback.inputCacheCap);
  15137. pDevice->playback.inputCacheConsumed = 0;
  15138. pDevice->playback.inputCacheRemaining = pDevice->playback.inputCacheCap;
  15139. }
  15140. }
  15141. } else {
  15142. while (totalFramesReadOut < frameCount) {
  15143. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In client format. */
  15144. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15145. ma_uint64 framesToReadThisIterationIn;
  15146. ma_uint64 framesReadThisIterationIn;
  15147. ma_uint64 framesToReadThisIterationOut;
  15148. ma_uint64 framesReadThisIterationOut;
  15149. ma_uint64 requiredInputFrameCount;
  15150. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  15151. framesToReadThisIterationIn = framesToReadThisIterationOut;
  15152. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  15153. framesToReadThisIterationIn = intermediaryBufferCap;
  15154. }
  15155. ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  15156. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  15157. framesToReadThisIterationIn = requiredInputFrameCount;
  15158. }
  15159. if (framesToReadThisIterationIn > 0) {
  15160. ma_device__handle_data_callback(pDevice, pIntermediaryBuffer, NULL, (ma_uint32)framesToReadThisIterationIn);
  15161. }
  15162. /*
  15163. 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
  15164. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  15165. */
  15166. framesReadThisIterationIn = framesToReadThisIterationIn;
  15167. framesReadThisIterationOut = framesToReadThisIterationOut;
  15168. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  15169. if (result != MA_SUCCESS) {
  15170. break;
  15171. }
  15172. totalFramesReadOut += framesReadThisIterationOut;
  15173. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15174. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  15175. break; /* We're done. */
  15176. }
  15177. }
  15178. }
  15179. }
  15180. }
  15181. /* A helper for sending sample data to the client. */
  15182. static void ma_device__send_frames_to_client(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat)
  15183. {
  15184. MA_ASSERT(pDevice != NULL);
  15185. MA_ASSERT(frameCountInDeviceFormat > 0);
  15186. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15187. if (pDevice->capture.converter.isPassthrough) {
  15188. ma_device__handle_data_callback(pDevice, NULL, pFramesInDeviceFormat, frameCountInDeviceFormat);
  15189. } else {
  15190. ma_result result;
  15191. ma_uint8 pFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15192. ma_uint64 framesInClientFormatCap = sizeof(pFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15193. ma_uint64 totalDeviceFramesProcessed = 0;
  15194. ma_uint64 totalClientFramesProcessed = 0;
  15195. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15196. /* We just keep going until we've exhaused all of our input frames and cannot generate any more output frames. */
  15197. for (;;) {
  15198. ma_uint64 deviceFramesProcessedThisIteration;
  15199. ma_uint64 clientFramesProcessedThisIteration;
  15200. deviceFramesProcessedThisIteration = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15201. clientFramesProcessedThisIteration = framesInClientFormatCap;
  15202. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &deviceFramesProcessedThisIteration, pFramesInClientFormat, &clientFramesProcessedThisIteration);
  15203. if (result != MA_SUCCESS) {
  15204. break;
  15205. }
  15206. if (clientFramesProcessedThisIteration > 0) {
  15207. ma_device__handle_data_callback(pDevice, NULL, pFramesInClientFormat, (ma_uint32)clientFramesProcessedThisIteration); /* Safe cast. */
  15208. }
  15209. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, deviceFramesProcessedThisIteration * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15210. totalDeviceFramesProcessed += deviceFramesProcessedThisIteration;
  15211. totalClientFramesProcessed += clientFramesProcessedThisIteration;
  15212. /* This is just to silence a warning. I might want to use this variable later so leaving in place for now. */
  15213. (void)totalClientFramesProcessed;
  15214. if (deviceFramesProcessedThisIteration == 0 && clientFramesProcessedThisIteration == 0) {
  15215. break; /* We're done. */
  15216. }
  15217. }
  15218. }
  15219. }
  15220. static ma_result ma_device__handle_duplex_callback_capture(ma_device* pDevice, ma_uint32 frameCountInDeviceFormat, const void* pFramesInDeviceFormat, ma_pcm_rb* pRB)
  15221. {
  15222. ma_result result;
  15223. ma_uint32 totalDeviceFramesProcessed = 0;
  15224. const void* pRunningFramesInDeviceFormat = pFramesInDeviceFormat;
  15225. MA_ASSERT(pDevice != NULL);
  15226. MA_ASSERT(frameCountInDeviceFormat > 0);
  15227. MA_ASSERT(pFramesInDeviceFormat != NULL);
  15228. MA_ASSERT(pRB != NULL);
  15229. /* Write to the ring buffer. The ring buffer is in the client format which means we need to convert. */
  15230. for (;;) {
  15231. ma_uint32 framesToProcessInDeviceFormat = (frameCountInDeviceFormat - totalDeviceFramesProcessed);
  15232. ma_uint32 framesToProcessInClientFormat = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15233. ma_uint64 framesProcessedInDeviceFormat;
  15234. ma_uint64 framesProcessedInClientFormat;
  15235. void* pFramesInClientFormat;
  15236. result = ma_pcm_rb_acquire_write(pRB, &framesToProcessInClientFormat, &pFramesInClientFormat);
  15237. if (result != MA_SUCCESS) {
  15238. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to acquire capture PCM frames from ring buffer.");
  15239. break;
  15240. }
  15241. if (framesToProcessInClientFormat == 0) {
  15242. if (ma_pcm_rb_pointer_distance(pRB) == (ma_int32)ma_pcm_rb_get_subbuffer_size(pRB)) {
  15243. break; /* Overrun. Not enough room in the ring buffer for input frame. Excess frames are dropped. */
  15244. }
  15245. }
  15246. /* Convert. */
  15247. framesProcessedInDeviceFormat = framesToProcessInDeviceFormat;
  15248. framesProcessedInClientFormat = framesToProcessInClientFormat;
  15249. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningFramesInDeviceFormat, &framesProcessedInDeviceFormat, pFramesInClientFormat, &framesProcessedInClientFormat);
  15250. if (result != MA_SUCCESS) {
  15251. break;
  15252. }
  15253. result = ma_pcm_rb_commit_write(pRB, (ma_uint32)framesProcessedInClientFormat); /* Safe cast. */
  15254. if (result != MA_SUCCESS) {
  15255. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "Failed to commit capture PCM frames to ring buffer.");
  15256. break;
  15257. }
  15258. pRunningFramesInDeviceFormat = ma_offset_ptr(pRunningFramesInDeviceFormat, framesProcessedInDeviceFormat * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15259. totalDeviceFramesProcessed += (ma_uint32)framesProcessedInDeviceFormat; /* Safe cast. */
  15260. /* We're done when we're unable to process any client nor device frames. */
  15261. if (framesProcessedInClientFormat == 0 && framesProcessedInDeviceFormat == 0) {
  15262. break; /* Done. */
  15263. }
  15264. }
  15265. return MA_SUCCESS;
  15266. }
  15267. static ma_result ma_device__handle_duplex_callback_playback(ma_device* pDevice, ma_uint32 frameCount, void* pFramesInInternalFormat, ma_pcm_rb* pRB)
  15268. {
  15269. ma_result result;
  15270. ma_uint8 silentInputFrames[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15271. ma_uint32 totalFramesReadOut = 0;
  15272. MA_ASSERT(pDevice != NULL);
  15273. MA_ASSERT(frameCount > 0);
  15274. MA_ASSERT(pFramesInInternalFormat != NULL);
  15275. MA_ASSERT(pRB != NULL);
  15276. MA_ASSERT(pDevice->playback.pInputCache != NULL);
  15277. /*
  15278. 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
  15279. the whole frameCount frames we just use silence instead for the input data.
  15280. */
  15281. MA_ZERO_MEMORY(silentInputFrames, sizeof(silentInputFrames));
  15282. while (totalFramesReadOut < frameCount && ma_device_is_started(pDevice)) {
  15283. /*
  15284. We should have a buffer allocated on the heap. Any playback frames still sitting in there
  15285. need to be sent to the internal device before we process any more data from the client.
  15286. */
  15287. if (pDevice->playback.inputCacheRemaining > 0) {
  15288. ma_uint64 framesConvertedIn = pDevice->playback.inputCacheRemaining;
  15289. ma_uint64 framesConvertedOut = (frameCount - totalFramesReadOut);
  15290. 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);
  15291. pDevice->playback.inputCacheConsumed += framesConvertedIn;
  15292. pDevice->playback.inputCacheRemaining -= framesConvertedIn;
  15293. totalFramesReadOut += (ma_uint32)framesConvertedOut; /* Safe cast. */
  15294. pFramesInInternalFormat = ma_offset_ptr(pFramesInInternalFormat, framesConvertedOut * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  15295. }
  15296. /* If there's no more data in the cache we'll need to fill it with some. */
  15297. if (totalFramesReadOut < frameCount && pDevice->playback.inputCacheRemaining == 0) {
  15298. ma_uint32 inputFrameCount;
  15299. void* pInputFrames;
  15300. inputFrameCount = (ma_uint32)pDevice->playback.inputCacheCap;
  15301. result = ma_pcm_rb_acquire_read(pRB, &inputFrameCount, &pInputFrames);
  15302. if (result == MA_SUCCESS) {
  15303. if (inputFrameCount > 0) {
  15304. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, pInputFrames, inputFrameCount);
  15305. } else {
  15306. if (ma_pcm_rb_pointer_distance(pRB) == 0) {
  15307. break; /* Underrun. */
  15308. }
  15309. }
  15310. } else {
  15311. /* No capture data available. Feed in silence. */
  15312. inputFrameCount = (ma_uint32)ma_min(pDevice->playback.inputCacheCap, sizeof(silentInputFrames) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels));
  15313. ma_device__handle_data_callback(pDevice, pDevice->playback.pInputCache, silentInputFrames, inputFrameCount);
  15314. }
  15315. pDevice->playback.inputCacheConsumed = 0;
  15316. pDevice->playback.inputCacheRemaining = inputFrameCount;
  15317. result = ma_pcm_rb_commit_read(pRB, inputFrameCount);
  15318. if (result != MA_SUCCESS) {
  15319. return result; /* Should never happen. */
  15320. }
  15321. }
  15322. }
  15323. return MA_SUCCESS;
  15324. }
  15325. /* A helper for changing the state of the device. */
  15326. static MA_INLINE void ma_device__set_state(ma_device* pDevice, ma_device_state newState)
  15327. {
  15328. c89atomic_exchange_i32((ma_int32*)&pDevice->state, (ma_int32)newState);
  15329. }
  15330. #ifdef MA_WIN32
  15331. GUID MA_GUID_KSDATAFORMAT_SUBTYPE_PCM = {0x00000001, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  15332. GUID MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT = {0x00000003, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};
  15333. /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_ALAW = {0x00000006, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  15334. /*GUID MA_GUID_KSDATAFORMAT_SUBTYPE_MULAW = {0x00000007, 0x0000, 0x0010, {0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71}};*/
  15335. #endif
  15336. MA_API ma_uint32 ma_get_format_priority_index(ma_format format) /* Lower = better. */
  15337. {
  15338. ma_uint32 i;
  15339. for (i = 0; i < ma_countof(g_maFormatPriorities); ++i) {
  15340. if (g_maFormatPriorities[i] == format) {
  15341. return i;
  15342. }
  15343. }
  15344. /* Getting here means the format could not be found or is equal to ma_format_unknown. */
  15345. return (ma_uint32)-1;
  15346. }
  15347. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType);
  15348. static ma_bool32 ma_device_descriptor_is_valid(const ma_device_descriptor* pDeviceDescriptor)
  15349. {
  15350. if (pDeviceDescriptor == NULL) {
  15351. return MA_FALSE;
  15352. }
  15353. if (pDeviceDescriptor->format == ma_format_unknown) {
  15354. return MA_FALSE;
  15355. }
  15356. if (pDeviceDescriptor->channels == 0 || pDeviceDescriptor->channels > MA_MAX_CHANNELS) {
  15357. return MA_FALSE;
  15358. }
  15359. if (pDeviceDescriptor->sampleRate == 0) {
  15360. return MA_FALSE;
  15361. }
  15362. return MA_TRUE;
  15363. }
  15364. static ma_result ma_device_audio_thread__default_read_write(ma_device* pDevice)
  15365. {
  15366. ma_result result = MA_SUCCESS;
  15367. ma_bool32 exitLoop = MA_FALSE;
  15368. ma_uint8 capturedDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15369. ma_uint8 playbackDeviceData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15370. ma_uint32 capturedDeviceDataCapInFrames = 0;
  15371. ma_uint32 playbackDeviceDataCapInFrames = 0;
  15372. MA_ASSERT(pDevice != NULL);
  15373. /* Just some quick validation on the device type and the available callbacks. */
  15374. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  15375. if (pDevice->pContext->callbacks.onDeviceRead == NULL) {
  15376. return MA_NOT_IMPLEMENTED;
  15377. }
  15378. capturedDeviceDataCapInFrames = sizeof(capturedDeviceData) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  15379. }
  15380. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  15381. if (pDevice->pContext->callbacks.onDeviceWrite == NULL) {
  15382. return MA_NOT_IMPLEMENTED;
  15383. }
  15384. playbackDeviceDataCapInFrames = sizeof(playbackDeviceData) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  15385. }
  15386. /* NOTE: The device was started outside of this function, in the worker thread. */
  15387. while (ma_device_get_state(pDevice) == ma_device_state_started && !exitLoop) {
  15388. switch (pDevice->type) {
  15389. case ma_device_type_duplex:
  15390. {
  15391. /* The process is: onDeviceRead() -> convert -> callback -> convert -> onDeviceWrite() */
  15392. ma_uint32 totalCapturedDeviceFramesProcessed = 0;
  15393. ma_uint32 capturedDevicePeriodSizeInFrames = ma_min(pDevice->capture.internalPeriodSizeInFrames, pDevice->playback.internalPeriodSizeInFrames);
  15394. while (totalCapturedDeviceFramesProcessed < capturedDevicePeriodSizeInFrames) {
  15395. ma_uint32 capturedDeviceFramesRemaining;
  15396. ma_uint32 capturedDeviceFramesProcessed;
  15397. ma_uint32 capturedDeviceFramesToProcess;
  15398. ma_uint32 capturedDeviceFramesToTryProcessing = capturedDevicePeriodSizeInFrames - totalCapturedDeviceFramesProcessed;
  15399. if (capturedDeviceFramesToTryProcessing > capturedDeviceDataCapInFrames) {
  15400. capturedDeviceFramesToTryProcessing = capturedDeviceDataCapInFrames;
  15401. }
  15402. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, capturedDeviceFramesToTryProcessing, &capturedDeviceFramesToProcess);
  15403. if (result != MA_SUCCESS) {
  15404. exitLoop = MA_TRUE;
  15405. break;
  15406. }
  15407. capturedDeviceFramesRemaining = capturedDeviceFramesToProcess;
  15408. capturedDeviceFramesProcessed = 0;
  15409. /* At this point we have our captured data in device format and we now need to convert it to client format. */
  15410. for (;;) {
  15411. ma_uint8 capturedClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15412. ma_uint8 playbackClientData[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  15413. ma_uint32 capturedClientDataCapInFrames = sizeof(capturedClientData) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  15414. ma_uint32 playbackClientDataCapInFrames = sizeof(playbackClientData) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  15415. ma_uint64 capturedClientFramesToProcessThisIteration = ma_min(capturedClientDataCapInFrames, playbackClientDataCapInFrames);
  15416. ma_uint64 capturedDeviceFramesToProcessThisIteration = capturedDeviceFramesRemaining;
  15417. ma_uint8* pRunningCapturedDeviceFrames = ma_offset_ptr(capturedDeviceData, capturedDeviceFramesProcessed * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  15418. /* Convert capture data from device format to client format. */
  15419. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningCapturedDeviceFrames, &capturedDeviceFramesToProcessThisIteration, capturedClientData, &capturedClientFramesToProcessThisIteration);
  15420. if (result != MA_SUCCESS) {
  15421. break;
  15422. }
  15423. /*
  15424. 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
  15425. which should never be the case when it's of the size MA_DATA_CONVERTER_STACK_BUFFER_SIZE.
  15426. */
  15427. if (capturedClientFramesToProcessThisIteration == 0) {
  15428. break;
  15429. }
  15430. ma_device__handle_data_callback(pDevice, playbackClientData, capturedClientData, (ma_uint32)capturedClientFramesToProcessThisIteration); /* Safe cast .*/
  15431. capturedDeviceFramesProcessed += (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  15432. capturedDeviceFramesRemaining -= (ma_uint32)capturedDeviceFramesToProcessThisIteration; /* Safe cast. */
  15433. /* At this point the playbackClientData buffer should be holding data that needs to be written to the device. */
  15434. for (;;) {
  15435. ma_uint64 convertedClientFrameCount = capturedClientFramesToProcessThisIteration;
  15436. ma_uint64 convertedDeviceFrameCount = playbackDeviceDataCapInFrames;
  15437. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, playbackClientData, &convertedClientFrameCount, playbackDeviceData, &convertedDeviceFrameCount);
  15438. if (result != MA_SUCCESS) {
  15439. break;
  15440. }
  15441. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, (ma_uint32)convertedDeviceFrameCount, NULL); /* Safe cast. */
  15442. if (result != MA_SUCCESS) {
  15443. exitLoop = MA_TRUE;
  15444. break;
  15445. }
  15446. capturedClientFramesToProcessThisIteration -= (ma_uint32)convertedClientFrameCount; /* Safe cast. */
  15447. if (capturedClientFramesToProcessThisIteration == 0) {
  15448. break;
  15449. }
  15450. }
  15451. /* In case an error happened from ma_device_write__null()... */
  15452. if (result != MA_SUCCESS) {
  15453. exitLoop = MA_TRUE;
  15454. break;
  15455. }
  15456. }
  15457. /* Make sure we don't get stuck in the inner loop. */
  15458. if (capturedDeviceFramesProcessed == 0) {
  15459. break;
  15460. }
  15461. totalCapturedDeviceFramesProcessed += capturedDeviceFramesProcessed;
  15462. }
  15463. } break;
  15464. case ma_device_type_capture:
  15465. case ma_device_type_loopback:
  15466. {
  15467. ma_uint32 periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  15468. ma_uint32 framesReadThisPeriod = 0;
  15469. while (framesReadThisPeriod < periodSizeInFrames) {
  15470. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesReadThisPeriod;
  15471. ma_uint32 framesProcessed;
  15472. ma_uint32 framesToReadThisIteration = framesRemainingInPeriod;
  15473. if (framesToReadThisIteration > capturedDeviceDataCapInFrames) {
  15474. framesToReadThisIteration = capturedDeviceDataCapInFrames;
  15475. }
  15476. result = pDevice->pContext->callbacks.onDeviceRead(pDevice, capturedDeviceData, framesToReadThisIteration, &framesProcessed);
  15477. if (result != MA_SUCCESS) {
  15478. exitLoop = MA_TRUE;
  15479. break;
  15480. }
  15481. /* Make sure we don't get stuck in the inner loop. */
  15482. if (framesProcessed == 0) {
  15483. break;
  15484. }
  15485. ma_device__send_frames_to_client(pDevice, framesProcessed, capturedDeviceData);
  15486. framesReadThisPeriod += framesProcessed;
  15487. }
  15488. } break;
  15489. case ma_device_type_playback:
  15490. {
  15491. /* We write in chunks of the period size, but use a stack allocated buffer for the intermediary. */
  15492. ma_uint32 periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  15493. ma_uint32 framesWrittenThisPeriod = 0;
  15494. while (framesWrittenThisPeriod < periodSizeInFrames) {
  15495. ma_uint32 framesRemainingInPeriod = periodSizeInFrames - framesWrittenThisPeriod;
  15496. ma_uint32 framesProcessed;
  15497. ma_uint32 framesToWriteThisIteration = framesRemainingInPeriod;
  15498. if (framesToWriteThisIteration > playbackDeviceDataCapInFrames) {
  15499. framesToWriteThisIteration = playbackDeviceDataCapInFrames;
  15500. }
  15501. ma_device__read_frames_from_client(pDevice, framesToWriteThisIteration, playbackDeviceData);
  15502. result = pDevice->pContext->callbacks.onDeviceWrite(pDevice, playbackDeviceData, framesToWriteThisIteration, &framesProcessed);
  15503. if (result != MA_SUCCESS) {
  15504. exitLoop = MA_TRUE;
  15505. break;
  15506. }
  15507. /* Make sure we don't get stuck in the inner loop. */
  15508. if (framesProcessed == 0) {
  15509. break;
  15510. }
  15511. framesWrittenThisPeriod += framesProcessed;
  15512. }
  15513. } break;
  15514. /* Should never get here. */
  15515. default: break;
  15516. }
  15517. }
  15518. return result;
  15519. }
  15520. /*******************************************************************************
  15521. Null Backend
  15522. *******************************************************************************/
  15523. #ifdef MA_HAS_NULL
  15524. #define MA_DEVICE_OP_NONE__NULL 0
  15525. #define MA_DEVICE_OP_START__NULL 1
  15526. #define MA_DEVICE_OP_SUSPEND__NULL 2
  15527. #define MA_DEVICE_OP_KILL__NULL 3
  15528. static ma_thread_result MA_THREADCALL ma_device_thread__null(void* pData)
  15529. {
  15530. ma_device* pDevice = (ma_device*)pData;
  15531. MA_ASSERT(pDevice != NULL);
  15532. for (;;) { /* Keep the thread alive until the device is uninitialized. */
  15533. ma_uint32 operation;
  15534. /* Wait for an operation to be requested. */
  15535. ma_event_wait(&pDevice->null_device.operationEvent);
  15536. /* At this point an event should have been triggered. */
  15537. operation = pDevice->null_device.operation;
  15538. /* Starting the device needs to put the thread into a loop. */
  15539. if (operation == MA_DEVICE_OP_START__NULL) {
  15540. /* Reset the timer just in case. */
  15541. ma_timer_init(&pDevice->null_device.timer);
  15542. /* Getting here means a suspend or kill operation has been requested. */
  15543. pDevice->null_device.operationResult = MA_SUCCESS;
  15544. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  15545. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  15546. continue;
  15547. }
  15548. /* Suspending the device means we need to stop the timer and just continue the loop. */
  15549. if (operation == MA_DEVICE_OP_SUSPEND__NULL) {
  15550. /* We need to add the current run time to the prior run time, then reset the timer. */
  15551. pDevice->null_device.priorRunTime += ma_timer_get_time_in_seconds(&pDevice->null_device.timer);
  15552. ma_timer_init(&pDevice->null_device.timer);
  15553. /* We're done. */
  15554. pDevice->null_device.operationResult = MA_SUCCESS;
  15555. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  15556. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  15557. continue;
  15558. }
  15559. /* Killing the device means we need to get out of this loop so that this thread can terminate. */
  15560. if (operation == MA_DEVICE_OP_KILL__NULL) {
  15561. pDevice->null_device.operationResult = MA_SUCCESS;
  15562. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  15563. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  15564. break;
  15565. }
  15566. /* Getting a signal on a "none" operation probably means an error. Return invalid operation. */
  15567. if (operation == MA_DEVICE_OP_NONE__NULL) {
  15568. 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). */
  15569. pDevice->null_device.operationResult = MA_INVALID_OPERATION;
  15570. ma_event_signal(&pDevice->null_device.operationCompletionEvent);
  15571. ma_semaphore_release(&pDevice->null_device.operationSemaphore);
  15572. continue; /* Continue the loop. Don't terminate. */
  15573. }
  15574. }
  15575. return (ma_thread_result)0;
  15576. }
  15577. static ma_result ma_device_do_operation__null(ma_device* pDevice, ma_uint32 operation)
  15578. {
  15579. ma_result result;
  15580. /*
  15581. TODO: Need to review this and consider just using mutual exclusion. I think the original motivation
  15582. for this was to just post the event to a queue and return immediately, but that has since changed
  15583. and now this function is synchronous. I think this can be simplified to just use a mutex.
  15584. */
  15585. /*
  15586. 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
  15587. to support queing of operations.
  15588. */
  15589. result = ma_semaphore_wait(&pDevice->null_device.operationSemaphore);
  15590. if (result != MA_SUCCESS) {
  15591. return result; /* Failed to wait for the event. */
  15592. }
  15593. /*
  15594. 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
  15595. signal an event to the worker thread to let it know that it can start work.
  15596. */
  15597. pDevice->null_device.operation = operation;
  15598. /* Once the operation code has been set, the worker thread can start work. */
  15599. if (ma_event_signal(&pDevice->null_device.operationEvent) != MA_SUCCESS) {
  15600. return MA_ERROR;
  15601. }
  15602. /* We want everything to be synchronous so we're going to wait for the worker thread to complete it's operation. */
  15603. if (ma_event_wait(&pDevice->null_device.operationCompletionEvent) != MA_SUCCESS) {
  15604. return MA_ERROR;
  15605. }
  15606. return pDevice->null_device.operationResult;
  15607. }
  15608. static ma_uint64 ma_device_get_total_run_time_in_frames__null(ma_device* pDevice)
  15609. {
  15610. ma_uint32 internalSampleRate;
  15611. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  15612. internalSampleRate = pDevice->capture.internalSampleRate;
  15613. } else {
  15614. internalSampleRate = pDevice->playback.internalSampleRate;
  15615. }
  15616. return (ma_uint64)((pDevice->null_device.priorRunTime + ma_timer_get_time_in_seconds(&pDevice->null_device.timer)) * internalSampleRate);
  15617. }
  15618. static ma_result ma_context_enumerate_devices__null(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  15619. {
  15620. ma_bool32 cbResult = MA_TRUE;
  15621. MA_ASSERT(pContext != NULL);
  15622. MA_ASSERT(callback != NULL);
  15623. /* Playback. */
  15624. if (cbResult) {
  15625. ma_device_info deviceInfo;
  15626. MA_ZERO_OBJECT(&deviceInfo);
  15627. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Playback Device", (size_t)-1);
  15628. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  15629. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  15630. }
  15631. /* Capture. */
  15632. if (cbResult) {
  15633. ma_device_info deviceInfo;
  15634. MA_ZERO_OBJECT(&deviceInfo);
  15635. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), "NULL Capture Device", (size_t)-1);
  15636. deviceInfo.isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  15637. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  15638. }
  15639. (void)cbResult; /* Silence a static analysis warning. */
  15640. return MA_SUCCESS;
  15641. }
  15642. 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)
  15643. {
  15644. MA_ASSERT(pContext != NULL);
  15645. if (pDeviceID != NULL && pDeviceID->nullbackend != 0) {
  15646. return MA_NO_DEVICE; /* Don't know the device. */
  15647. }
  15648. /* Name / Description */
  15649. if (deviceType == ma_device_type_playback) {
  15650. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Playback Device", (size_t)-1);
  15651. } else {
  15652. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), "NULL Capture Device", (size_t)-1);
  15653. }
  15654. pDeviceInfo->isDefault = MA_TRUE; /* Only one playback and capture device for the null backend, so might as well mark as default. */
  15655. /* Support everything on the null backend. */
  15656. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  15657. pDeviceInfo->nativeDataFormats[0].channels = 0;
  15658. pDeviceInfo->nativeDataFormats[0].sampleRate = 0;
  15659. pDeviceInfo->nativeDataFormats[0].flags = 0;
  15660. pDeviceInfo->nativeDataFormatCount = 1;
  15661. (void)pContext;
  15662. return MA_SUCCESS;
  15663. }
  15664. static ma_result ma_device_uninit__null(ma_device* pDevice)
  15665. {
  15666. MA_ASSERT(pDevice != NULL);
  15667. /* Keep it clean and wait for the device thread to finish before returning. */
  15668. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_KILL__NULL);
  15669. /* Wait for the thread to finish before continuing. */
  15670. ma_thread_wait(&pDevice->null_device.deviceThread);
  15671. /* At this point the loop in the device thread is as good as terminated so we can uninitialize our events. */
  15672. ma_semaphore_uninit(&pDevice->null_device.operationSemaphore);
  15673. ma_event_uninit(&pDevice->null_device.operationCompletionEvent);
  15674. ma_event_uninit(&pDevice->null_device.operationEvent);
  15675. return MA_SUCCESS;
  15676. }
  15677. static ma_result ma_device_init__null(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  15678. {
  15679. ma_result result;
  15680. MA_ASSERT(pDevice != NULL);
  15681. MA_ZERO_OBJECT(&pDevice->null_device);
  15682. if (pConfig->deviceType == ma_device_type_loopback) {
  15683. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  15684. }
  15685. /* The null backend supports everything exactly as we specify it. */
  15686. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  15687. pDescriptorCapture->format = (pDescriptorCapture->format != ma_format_unknown) ? pDescriptorCapture->format : MA_DEFAULT_FORMAT;
  15688. pDescriptorCapture->channels = (pDescriptorCapture->channels != 0) ? pDescriptorCapture->channels : MA_DEFAULT_CHANNELS;
  15689. pDescriptorCapture->sampleRate = (pDescriptorCapture->sampleRate != 0) ? pDescriptorCapture->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  15690. if (pDescriptorCapture->channelMap[0] == MA_CHANNEL_NONE) {
  15691. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  15692. }
  15693. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  15694. }
  15695. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  15696. pDescriptorPlayback->format = (pDescriptorPlayback->format != ma_format_unknown) ? pDescriptorPlayback->format : MA_DEFAULT_FORMAT;
  15697. pDescriptorPlayback->channels = (pDescriptorPlayback->channels != 0) ? pDescriptorPlayback->channels : MA_DEFAULT_CHANNELS;
  15698. pDescriptorPlayback->sampleRate = (pDescriptorPlayback->sampleRate != 0) ? pDescriptorPlayback->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  15699. if (pDescriptorPlayback->channelMap[0] == MA_CHANNEL_NONE) {
  15700. ma_channel_map_init_standard(ma_standard_channel_map_default, pDescriptorPlayback->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorPlayback->channels);
  15701. }
  15702. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  15703. }
  15704. /*
  15705. 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
  15706. first period is "written" to it, and then stopped in ma_device_stop__null().
  15707. */
  15708. result = ma_event_init(&pDevice->null_device.operationEvent);
  15709. if (result != MA_SUCCESS) {
  15710. return result;
  15711. }
  15712. result = ma_event_init(&pDevice->null_device.operationCompletionEvent);
  15713. if (result != MA_SUCCESS) {
  15714. return result;
  15715. }
  15716. result = ma_semaphore_init(1, &pDevice->null_device.operationSemaphore); /* <-- It's important that the initial value is set to 1. */
  15717. if (result != MA_SUCCESS) {
  15718. return result;
  15719. }
  15720. result = ma_thread_create(&pDevice->null_device.deviceThread, pDevice->pContext->threadPriority, 0, ma_device_thread__null, pDevice, &pDevice->pContext->allocationCallbacks);
  15721. if (result != MA_SUCCESS) {
  15722. return result;
  15723. }
  15724. return MA_SUCCESS;
  15725. }
  15726. static ma_result ma_device_start__null(ma_device* pDevice)
  15727. {
  15728. MA_ASSERT(pDevice != NULL);
  15729. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_START__NULL);
  15730. c89atomic_exchange_32(&pDevice->null_device.isStarted, MA_TRUE);
  15731. return MA_SUCCESS;
  15732. }
  15733. static ma_result ma_device_stop__null(ma_device* pDevice)
  15734. {
  15735. MA_ASSERT(pDevice != NULL);
  15736. ma_device_do_operation__null(pDevice, MA_DEVICE_OP_SUSPEND__NULL);
  15737. c89atomic_exchange_32(&pDevice->null_device.isStarted, MA_FALSE);
  15738. return MA_SUCCESS;
  15739. }
  15740. static ma_result ma_device_write__null(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  15741. {
  15742. ma_result result = MA_SUCCESS;
  15743. ma_uint32 totalPCMFramesProcessed;
  15744. ma_bool32 wasStartedOnEntry;
  15745. if (pFramesWritten != NULL) {
  15746. *pFramesWritten = 0;
  15747. }
  15748. wasStartedOnEntry = c89atomic_load_32(&pDevice->null_device.isStarted);
  15749. /* Keep going until everything has been read. */
  15750. totalPCMFramesProcessed = 0;
  15751. while (totalPCMFramesProcessed < frameCount) {
  15752. ma_uint64 targetFrame;
  15753. /* If there are any frames remaining in the current period, consume those first. */
  15754. if (pDevice->null_device.currentPeriodFramesRemainingPlayback > 0) {
  15755. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  15756. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingPlayback;
  15757. if (framesToProcess > framesRemaining) {
  15758. framesToProcess = framesRemaining;
  15759. }
  15760. /* We don't actually do anything with pPCMFrames, so just mark it as unused to prevent a warning. */
  15761. (void)pPCMFrames;
  15762. pDevice->null_device.currentPeriodFramesRemainingPlayback -= framesToProcess;
  15763. totalPCMFramesProcessed += framesToProcess;
  15764. }
  15765. /* 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. */
  15766. if (pDevice->null_device.currentPeriodFramesRemainingPlayback == 0) {
  15767. pDevice->null_device.currentPeriodFramesRemainingPlayback = 0;
  15768. if (!c89atomic_load_32(&pDevice->null_device.isStarted) && !wasStartedOnEntry) {
  15769. result = ma_device_start__null(pDevice);
  15770. if (result != MA_SUCCESS) {
  15771. break;
  15772. }
  15773. }
  15774. }
  15775. /* If we've consumed the whole buffer we can return now. */
  15776. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  15777. if (totalPCMFramesProcessed == frameCount) {
  15778. break;
  15779. }
  15780. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  15781. targetFrame = pDevice->null_device.lastProcessedFramePlayback;
  15782. for (;;) {
  15783. ma_uint64 currentFrame;
  15784. /* Stop waiting if the device has been stopped. */
  15785. if (!c89atomic_load_32(&pDevice->null_device.isStarted)) {
  15786. break;
  15787. }
  15788. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  15789. if (currentFrame >= targetFrame) {
  15790. break;
  15791. }
  15792. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  15793. ma_sleep(10);
  15794. }
  15795. pDevice->null_device.lastProcessedFramePlayback += pDevice->playback.internalPeriodSizeInFrames;
  15796. pDevice->null_device.currentPeriodFramesRemainingPlayback = pDevice->playback.internalPeriodSizeInFrames;
  15797. }
  15798. if (pFramesWritten != NULL) {
  15799. *pFramesWritten = totalPCMFramesProcessed;
  15800. }
  15801. return result;
  15802. }
  15803. static ma_result ma_device_read__null(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  15804. {
  15805. ma_result result = MA_SUCCESS;
  15806. ma_uint32 totalPCMFramesProcessed;
  15807. if (pFramesRead != NULL) {
  15808. *pFramesRead = 0;
  15809. }
  15810. /* Keep going until everything has been read. */
  15811. totalPCMFramesProcessed = 0;
  15812. while (totalPCMFramesProcessed < frameCount) {
  15813. ma_uint64 targetFrame;
  15814. /* If there are any frames remaining in the current period, consume those first. */
  15815. if (pDevice->null_device.currentPeriodFramesRemainingCapture > 0) {
  15816. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  15817. ma_uint32 framesRemaining = (frameCount - totalPCMFramesProcessed);
  15818. ma_uint32 framesToProcess = pDevice->null_device.currentPeriodFramesRemainingCapture;
  15819. if (framesToProcess > framesRemaining) {
  15820. framesToProcess = framesRemaining;
  15821. }
  15822. /* We need to ensure the output buffer is zeroed. */
  15823. MA_ZERO_MEMORY(ma_offset_ptr(pPCMFrames, totalPCMFramesProcessed*bpf), framesToProcess*bpf);
  15824. pDevice->null_device.currentPeriodFramesRemainingCapture -= framesToProcess;
  15825. totalPCMFramesProcessed += framesToProcess;
  15826. }
  15827. /* 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. */
  15828. if (pDevice->null_device.currentPeriodFramesRemainingCapture == 0) {
  15829. pDevice->null_device.currentPeriodFramesRemainingCapture = 0;
  15830. }
  15831. /* If we've consumed the whole buffer we can return now. */
  15832. MA_ASSERT(totalPCMFramesProcessed <= frameCount);
  15833. if (totalPCMFramesProcessed == frameCount) {
  15834. break;
  15835. }
  15836. /* Getting here means we've still got more frames to consume, we but need to wait for it to become available. */
  15837. targetFrame = pDevice->null_device.lastProcessedFrameCapture + pDevice->capture.internalPeriodSizeInFrames;
  15838. for (;;) {
  15839. ma_uint64 currentFrame;
  15840. /* Stop waiting if the device has been stopped. */
  15841. if (!c89atomic_load_32(&pDevice->null_device.isStarted)) {
  15842. break;
  15843. }
  15844. currentFrame = ma_device_get_total_run_time_in_frames__null(pDevice);
  15845. if (currentFrame >= targetFrame) {
  15846. break;
  15847. }
  15848. /* Getting here means we haven't yet reached the target sample, so continue waiting. */
  15849. ma_sleep(10);
  15850. }
  15851. pDevice->null_device.lastProcessedFrameCapture += pDevice->capture.internalPeriodSizeInFrames;
  15852. pDevice->null_device.currentPeriodFramesRemainingCapture = pDevice->capture.internalPeriodSizeInFrames;
  15853. }
  15854. if (pFramesRead != NULL) {
  15855. *pFramesRead = totalPCMFramesProcessed;
  15856. }
  15857. return result;
  15858. }
  15859. static ma_result ma_context_uninit__null(ma_context* pContext)
  15860. {
  15861. MA_ASSERT(pContext != NULL);
  15862. MA_ASSERT(pContext->backend == ma_backend_null);
  15863. (void)pContext;
  15864. return MA_SUCCESS;
  15865. }
  15866. static ma_result ma_context_init__null(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  15867. {
  15868. MA_ASSERT(pContext != NULL);
  15869. (void)pConfig;
  15870. (void)pContext;
  15871. pCallbacks->onContextInit = ma_context_init__null;
  15872. pCallbacks->onContextUninit = ma_context_uninit__null;
  15873. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__null;
  15874. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__null;
  15875. pCallbacks->onDeviceInit = ma_device_init__null;
  15876. pCallbacks->onDeviceUninit = ma_device_uninit__null;
  15877. pCallbacks->onDeviceStart = ma_device_start__null;
  15878. pCallbacks->onDeviceStop = ma_device_stop__null;
  15879. pCallbacks->onDeviceRead = ma_device_read__null;
  15880. pCallbacks->onDeviceWrite = ma_device_write__null;
  15881. 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. */
  15882. /* The null backend always works. */
  15883. return MA_SUCCESS;
  15884. }
  15885. #endif
  15886. /*******************************************************************************
  15887. WIN32 COMMON
  15888. *******************************************************************************/
  15889. #if defined(MA_WIN32)
  15890. #if defined(MA_WIN32_DESKTOP)
  15891. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) ((MA_PFN_CoInitializeEx)pContext->win32.CoInitializeEx)(pvReserved, dwCoInit)
  15892. #define ma_CoUninitialize(pContext) ((MA_PFN_CoUninitialize)pContext->win32.CoUninitialize)()
  15893. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) ((MA_PFN_CoCreateInstance)pContext->win32.CoCreateInstance)(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  15894. #define ma_CoTaskMemFree(pContext, pv) ((MA_PFN_CoTaskMemFree)pContext->win32.CoTaskMemFree)(pv)
  15895. #define ma_PropVariantClear(pContext, pvar) ((MA_PFN_PropVariantClear)pContext->win32.PropVariantClear)(pvar)
  15896. #else
  15897. #define ma_CoInitializeEx(pContext, pvReserved, dwCoInit) CoInitializeEx(pvReserved, dwCoInit)
  15898. #define ma_CoUninitialize(pContext) CoUninitialize()
  15899. #define ma_CoCreateInstance(pContext, rclsid, pUnkOuter, dwClsContext, riid, ppv) CoCreateInstance(rclsid, pUnkOuter, dwClsContext, riid, ppv)
  15900. #define ma_CoTaskMemFree(pContext, pv) CoTaskMemFree(pv)
  15901. #define ma_PropVariantClear(pContext, pvar) PropVariantClear(pvar)
  15902. #endif
  15903. #if !defined(MAXULONG_PTR) && !defined(__WATCOMC__)
  15904. typedef size_t DWORD_PTR;
  15905. #endif
  15906. #if !defined(WAVE_FORMAT_44M08)
  15907. #define WAVE_FORMAT_44M08 0x00000100
  15908. #define WAVE_FORMAT_44S08 0x00000200
  15909. #define WAVE_FORMAT_44M16 0x00000400
  15910. #define WAVE_FORMAT_44S16 0x00000800
  15911. #define WAVE_FORMAT_48M08 0x00001000
  15912. #define WAVE_FORMAT_48S08 0x00002000
  15913. #define WAVE_FORMAT_48M16 0x00004000
  15914. #define WAVE_FORMAT_48S16 0x00008000
  15915. #define WAVE_FORMAT_96M08 0x00010000
  15916. #define WAVE_FORMAT_96S08 0x00020000
  15917. #define WAVE_FORMAT_96M16 0x00040000
  15918. #define WAVE_FORMAT_96S16 0x00080000
  15919. #endif
  15920. #ifndef SPEAKER_FRONT_LEFT
  15921. #define SPEAKER_FRONT_LEFT 0x1
  15922. #define SPEAKER_FRONT_RIGHT 0x2
  15923. #define SPEAKER_FRONT_CENTER 0x4
  15924. #define SPEAKER_LOW_FREQUENCY 0x8
  15925. #define SPEAKER_BACK_LEFT 0x10
  15926. #define SPEAKER_BACK_RIGHT 0x20
  15927. #define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
  15928. #define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
  15929. #define SPEAKER_BACK_CENTER 0x100
  15930. #define SPEAKER_SIDE_LEFT 0x200
  15931. #define SPEAKER_SIDE_RIGHT 0x400
  15932. #define SPEAKER_TOP_CENTER 0x800
  15933. #define SPEAKER_TOP_FRONT_LEFT 0x1000
  15934. #define SPEAKER_TOP_FRONT_CENTER 0x2000
  15935. #define SPEAKER_TOP_FRONT_RIGHT 0x4000
  15936. #define SPEAKER_TOP_BACK_LEFT 0x8000
  15937. #define SPEAKER_TOP_BACK_CENTER 0x10000
  15938. #define SPEAKER_TOP_BACK_RIGHT 0x20000
  15939. #endif
  15940. /*
  15941. The SDK that comes with old versions of MSVC (VC6, for example) does not appear to define WAVEFORMATEXTENSIBLE. We
  15942. define our own implementation in this case.
  15943. */
  15944. #if (defined(_MSC_VER) && !defined(_WAVEFORMATEXTENSIBLE_)) || defined(__DMC__)
  15945. typedef struct
  15946. {
  15947. WAVEFORMATEX Format;
  15948. union
  15949. {
  15950. WORD wValidBitsPerSample;
  15951. WORD wSamplesPerBlock;
  15952. WORD wReserved;
  15953. } Samples;
  15954. DWORD dwChannelMask;
  15955. GUID SubFormat;
  15956. } WAVEFORMATEXTENSIBLE;
  15957. #endif
  15958. #ifndef WAVE_FORMAT_EXTENSIBLE
  15959. #define WAVE_FORMAT_EXTENSIBLE 0xFFFE
  15960. #endif
  15961. #ifndef WAVE_FORMAT_IEEE_FLOAT
  15962. #define WAVE_FORMAT_IEEE_FLOAT 0x0003
  15963. #endif
  15964. /* Converts an individual Win32-style channel identifier (SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  15965. static ma_uint8 ma_channel_id_to_ma__win32(DWORD id)
  15966. {
  15967. switch (id)
  15968. {
  15969. case SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  15970. case SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  15971. case SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  15972. case SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  15973. case SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  15974. case SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  15975. case SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  15976. case SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  15977. case SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  15978. case SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  15979. case SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  15980. case SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  15981. case SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  15982. case SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  15983. case SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  15984. case SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  15985. case SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  15986. case SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  15987. default: return 0;
  15988. }
  15989. }
  15990. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to Win32-style. */
  15991. static DWORD ma_channel_id_to_win32(DWORD id)
  15992. {
  15993. switch (id)
  15994. {
  15995. case MA_CHANNEL_MONO: return SPEAKER_FRONT_CENTER;
  15996. case MA_CHANNEL_FRONT_LEFT: return SPEAKER_FRONT_LEFT;
  15997. case MA_CHANNEL_FRONT_RIGHT: return SPEAKER_FRONT_RIGHT;
  15998. case MA_CHANNEL_FRONT_CENTER: return SPEAKER_FRONT_CENTER;
  15999. case MA_CHANNEL_LFE: return SPEAKER_LOW_FREQUENCY;
  16000. case MA_CHANNEL_BACK_LEFT: return SPEAKER_BACK_LEFT;
  16001. case MA_CHANNEL_BACK_RIGHT: return SPEAKER_BACK_RIGHT;
  16002. case MA_CHANNEL_FRONT_LEFT_CENTER: return SPEAKER_FRONT_LEFT_OF_CENTER;
  16003. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SPEAKER_FRONT_RIGHT_OF_CENTER;
  16004. case MA_CHANNEL_BACK_CENTER: return SPEAKER_BACK_CENTER;
  16005. case MA_CHANNEL_SIDE_LEFT: return SPEAKER_SIDE_LEFT;
  16006. case MA_CHANNEL_SIDE_RIGHT: return SPEAKER_SIDE_RIGHT;
  16007. case MA_CHANNEL_TOP_CENTER: return SPEAKER_TOP_CENTER;
  16008. case MA_CHANNEL_TOP_FRONT_LEFT: return SPEAKER_TOP_FRONT_LEFT;
  16009. case MA_CHANNEL_TOP_FRONT_CENTER: return SPEAKER_TOP_FRONT_CENTER;
  16010. case MA_CHANNEL_TOP_FRONT_RIGHT: return SPEAKER_TOP_FRONT_RIGHT;
  16011. case MA_CHANNEL_TOP_BACK_LEFT: return SPEAKER_TOP_BACK_LEFT;
  16012. case MA_CHANNEL_TOP_BACK_CENTER: return SPEAKER_TOP_BACK_CENTER;
  16013. case MA_CHANNEL_TOP_BACK_RIGHT: return SPEAKER_TOP_BACK_RIGHT;
  16014. default: return 0;
  16015. }
  16016. }
  16017. /* Converts a channel mapping to a Win32-style channel mask. */
  16018. static DWORD ma_channel_map_to_channel_mask__win32(const ma_channel* pChannelMap, ma_uint32 channels)
  16019. {
  16020. DWORD dwChannelMask = 0;
  16021. ma_uint32 iChannel;
  16022. for (iChannel = 0; iChannel < channels; ++iChannel) {
  16023. dwChannelMask |= ma_channel_id_to_win32(pChannelMap[iChannel]);
  16024. }
  16025. return dwChannelMask;
  16026. }
  16027. /* Converts a Win32-style channel mask to a miniaudio channel map. */
  16028. static void ma_channel_mask_to_channel_map__win32(DWORD dwChannelMask, ma_uint32 channels, ma_channel* pChannelMap)
  16029. {
  16030. /* If the channel mask is set to 0, just assume a default Win32 channel map. */
  16031. if (dwChannelMask == 0) {
  16032. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channels, channels);
  16033. } else {
  16034. if (channels == 1 && (dwChannelMask & SPEAKER_FRONT_CENTER) != 0) {
  16035. pChannelMap[0] = MA_CHANNEL_MONO;
  16036. } else {
  16037. /* Just iterate over each bit. */
  16038. ma_uint32 iChannel = 0;
  16039. ma_uint32 iBit;
  16040. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  16041. DWORD bitValue = (dwChannelMask & (1UL << iBit));
  16042. if (bitValue != 0) {
  16043. /* The bit is set. */
  16044. pChannelMap[iChannel] = ma_channel_id_to_ma__win32(bitValue);
  16045. iChannel += 1;
  16046. }
  16047. }
  16048. }
  16049. }
  16050. }
  16051. #ifdef __cplusplus
  16052. static ma_bool32 ma_is_guid_equal(const void* a, const void* b)
  16053. {
  16054. return IsEqualGUID(*(const GUID*)a, *(const GUID*)b);
  16055. }
  16056. #else
  16057. #define ma_is_guid_equal(a, b) IsEqualGUID((const GUID*)a, (const GUID*)b)
  16058. #endif
  16059. static MA_INLINE ma_bool32 ma_is_guid_null(const void* guid)
  16060. {
  16061. static GUID nullguid = {0x00000000, 0x0000, 0x0000, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}};
  16062. return ma_is_guid_equal(guid, &nullguid);
  16063. }
  16064. static ma_format ma_format_from_WAVEFORMATEX(const WAVEFORMATEX* pWF)
  16065. {
  16066. MA_ASSERT(pWF != NULL);
  16067. if (pWF->wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  16068. const WAVEFORMATEXTENSIBLE* pWFEX = (const WAVEFORMATEXTENSIBLE*)pWF;
  16069. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_PCM)) {
  16070. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16071. return ma_format_s32;
  16072. }
  16073. if (pWFEX->Samples.wValidBitsPerSample == 24) {
  16074. if (pWFEX->Format.wBitsPerSample == 32) {
  16075. return ma_format_s32;
  16076. }
  16077. if (pWFEX->Format.wBitsPerSample == 24) {
  16078. return ma_format_s24;
  16079. }
  16080. }
  16081. if (pWFEX->Samples.wValidBitsPerSample == 16) {
  16082. return ma_format_s16;
  16083. }
  16084. if (pWFEX->Samples.wValidBitsPerSample == 8) {
  16085. return ma_format_u8;
  16086. }
  16087. }
  16088. if (ma_is_guid_equal(&pWFEX->SubFormat, &MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT)) {
  16089. if (pWFEX->Samples.wValidBitsPerSample == 32) {
  16090. return ma_format_f32;
  16091. }
  16092. /*
  16093. if (pWFEX->Samples.wValidBitsPerSample == 64) {
  16094. return ma_format_f64;
  16095. }
  16096. */
  16097. }
  16098. } else {
  16099. if (pWF->wFormatTag == WAVE_FORMAT_PCM) {
  16100. if (pWF->wBitsPerSample == 32) {
  16101. return ma_format_s32;
  16102. }
  16103. if (pWF->wBitsPerSample == 24) {
  16104. return ma_format_s24;
  16105. }
  16106. if (pWF->wBitsPerSample == 16) {
  16107. return ma_format_s16;
  16108. }
  16109. if (pWF->wBitsPerSample == 8) {
  16110. return ma_format_u8;
  16111. }
  16112. }
  16113. if (pWF->wFormatTag == WAVE_FORMAT_IEEE_FLOAT) {
  16114. if (pWF->wBitsPerSample == 32) {
  16115. return ma_format_f32;
  16116. }
  16117. if (pWF->wBitsPerSample == 64) {
  16118. /*return ma_format_f64;*/
  16119. }
  16120. }
  16121. }
  16122. return ma_format_unknown;
  16123. }
  16124. #endif
  16125. /*******************************************************************************
  16126. WASAPI Backend
  16127. *******************************************************************************/
  16128. #ifdef MA_HAS_WASAPI
  16129. #if 0
  16130. #if defined(_MSC_VER)
  16131. #pragma warning(push)
  16132. #pragma warning(disable:4091) /* 'typedef ': ignored on left of '' when no variable is declared */
  16133. #endif
  16134. #include <audioclient.h>
  16135. #include <mmdeviceapi.h>
  16136. #if defined(_MSC_VER)
  16137. #pragma warning(pop)
  16138. #endif
  16139. #endif /* 0 */
  16140. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType);
  16141. /* Some compilers don't define VerifyVersionInfoW. Need to write this ourselves. */
  16142. #define MA_WIN32_WINNT_VISTA 0x0600
  16143. #define MA_VER_MINORVERSION 0x01
  16144. #define MA_VER_MAJORVERSION 0x02
  16145. #define MA_VER_SERVICEPACKMAJOR 0x20
  16146. #define MA_VER_GREATER_EQUAL 0x03
  16147. typedef struct {
  16148. DWORD dwOSVersionInfoSize;
  16149. DWORD dwMajorVersion;
  16150. DWORD dwMinorVersion;
  16151. DWORD dwBuildNumber;
  16152. DWORD dwPlatformId;
  16153. WCHAR szCSDVersion[128];
  16154. WORD wServicePackMajor;
  16155. WORD wServicePackMinor;
  16156. WORD wSuiteMask;
  16157. BYTE wProductType;
  16158. BYTE wReserved;
  16159. } ma_OSVERSIONINFOEXW;
  16160. typedef BOOL (WINAPI * ma_PFNVerifyVersionInfoW) (ma_OSVERSIONINFOEXW* lpVersionInfo, DWORD dwTypeMask, DWORDLONG dwlConditionMask);
  16161. typedef ULONGLONG (WINAPI * ma_PFNVerSetConditionMask)(ULONGLONG dwlConditionMask, DWORD dwTypeBitMask, BYTE dwConditionMask);
  16162. #ifndef PROPERTYKEY_DEFINED
  16163. #define PROPERTYKEY_DEFINED
  16164. #ifndef __WATCOMC__
  16165. typedef struct
  16166. {
  16167. GUID fmtid;
  16168. DWORD pid;
  16169. } PROPERTYKEY;
  16170. #endif
  16171. #endif
  16172. /* Some compilers don't define PropVariantInit(). We just do this ourselves since it's just a memset(). */
  16173. static MA_INLINE void ma_PropVariantInit(PROPVARIANT* pProp)
  16174. {
  16175. MA_ZERO_OBJECT(pProp);
  16176. }
  16177. static const PROPERTYKEY MA_PKEY_Device_FriendlyName = {{0xA45C254E, 0xDF1C, 0x4EFD, {0x80, 0x20, 0x67, 0xD1, 0x46, 0xA8, 0x50, 0xE0}}, 14};
  16178. static const PROPERTYKEY MA_PKEY_AudioEngine_DeviceFormat = {{0xF19F064D, 0x82C, 0x4E27, {0xBC, 0x73, 0x68, 0x82, 0xA1, 0xBB, 0x8E, 0x4C}}, 0};
  16179. static const IID MA_IID_IUnknown = {0x00000000, 0x0000, 0x0000, {0xC0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x46}}; /* 00000000-0000-0000-C000-000000000046 */
  16180. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16181. static const IID MA_IID_IAgileObject = {0x94EA2B94, 0xE9CC, 0x49E0, {0xC0, 0xFF, 0xEE, 0x64, 0xCA, 0x8F, 0x5B, 0x90}}; /* 94EA2B94-E9CC-49E0-C0FF-EE64CA8F5B90 */
  16182. #endif
  16183. static const IID MA_IID_IAudioClient = {0x1CB9AD4C, 0xDBFA, 0x4C32, {0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2}}; /* 1CB9AD4C-DBFA-4C32-B178-C2F568A703B2 = __uuidof(IAudioClient) */
  16184. static const IID MA_IID_IAudioClient2 = {0x726778CD, 0xF60A, 0x4EDA, {0x82, 0xDE, 0xE4, 0x76, 0x10, 0xCD, 0x78, 0xAA}}; /* 726778CD-F60A-4EDA-82DE-E47610CD78AA = __uuidof(IAudioClient2) */
  16185. static const IID MA_IID_IAudioClient3 = {0x7ED4EE07, 0x8E67, 0x4CD4, {0x8C, 0x1A, 0x2B, 0x7A, 0x59, 0x87, 0xAD, 0x42}}; /* 7ED4EE07-8E67-4CD4-8C1A-2B7A5987AD42 = __uuidof(IAudioClient3) */
  16186. static const IID MA_IID_IAudioRenderClient = {0xF294ACFC, 0x3146, 0x4483, {0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2}}; /* F294ACFC-3146-4483-A7BF-ADDCA7C260E2 = __uuidof(IAudioRenderClient) */
  16187. static const IID MA_IID_IAudioCaptureClient = {0xC8ADBD64, 0xE71E, 0x48A0, {0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}}; /* C8ADBD64-E71E-48A0-A4DE-185C395CD317 = __uuidof(IAudioCaptureClient) */
  16188. static const IID MA_IID_IMMNotificationClient = {0x7991EEC9, 0x7E89, 0x4D85, {0x83, 0x90, 0x6C, 0x70, 0x3C, 0xEC, 0x60, 0xC0}}; /* 7991EEC9-7E89-4D85-8390-6C703CEC60C0 = __uuidof(IMMNotificationClient) */
  16189. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16190. static const IID MA_IID_DEVINTERFACE_AUDIO_RENDER = {0xE6327CAD, 0xDCEC, 0x4949, {0xAE, 0x8A, 0x99, 0x1E, 0x97, 0x6A, 0x79, 0xD2}}; /* E6327CAD-DCEC-4949-AE8A-991E976A79D2 */
  16191. static const IID MA_IID_DEVINTERFACE_AUDIO_CAPTURE = {0x2EEF81BE, 0x33FA, 0x4800, {0x96, 0x70, 0x1C, 0xD4, 0x74, 0x97, 0x2C, 0x3F}}; /* 2EEF81BE-33FA-4800-9670-1CD474972C3F */
  16192. static const IID MA_IID_IActivateAudioInterfaceCompletionHandler = {0x41D949AB, 0x9862, 0x444A, {0x80, 0xF6, 0xC2, 0x61, 0x33, 0x4D, 0xA5, 0xEB}}; /* 41D949AB-9862-444A-80F6-C261334DA5EB */
  16193. #endif
  16194. static const IID MA_CLSID_MMDeviceEnumerator_Instance = {0xBCDE0395, 0xE52F, 0x467C, {0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E}}; /* BCDE0395-E52F-467C-8E3D-C4579291692E = __uuidof(MMDeviceEnumerator) */
  16195. static const IID MA_IID_IMMDeviceEnumerator_Instance = {0xA95664D2, 0x9614, 0x4F35, {0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6}}; /* A95664D2-9614-4F35-A746-DE8DB63617E6 = __uuidof(IMMDeviceEnumerator) */
  16196. #ifdef __cplusplus
  16197. #define MA_CLSID_MMDeviceEnumerator MA_CLSID_MMDeviceEnumerator_Instance
  16198. #define MA_IID_IMMDeviceEnumerator MA_IID_IMMDeviceEnumerator_Instance
  16199. #else
  16200. #define MA_CLSID_MMDeviceEnumerator &MA_CLSID_MMDeviceEnumerator_Instance
  16201. #define MA_IID_IMMDeviceEnumerator &MA_IID_IMMDeviceEnumerator_Instance
  16202. #endif
  16203. typedef struct ma_IUnknown ma_IUnknown;
  16204. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16205. #define MA_MM_DEVICE_STATE_ACTIVE 1
  16206. #define MA_MM_DEVICE_STATE_DISABLED 2
  16207. #define MA_MM_DEVICE_STATE_NOTPRESENT 4
  16208. #define MA_MM_DEVICE_STATE_UNPLUGGED 8
  16209. typedef struct ma_IMMDeviceEnumerator ma_IMMDeviceEnumerator;
  16210. typedef struct ma_IMMDeviceCollection ma_IMMDeviceCollection;
  16211. typedef struct ma_IMMDevice ma_IMMDevice;
  16212. #else
  16213. typedef struct ma_IActivateAudioInterfaceCompletionHandler ma_IActivateAudioInterfaceCompletionHandler;
  16214. typedef struct ma_IActivateAudioInterfaceAsyncOperation ma_IActivateAudioInterfaceAsyncOperation;
  16215. #endif
  16216. typedef struct ma_IPropertyStore ma_IPropertyStore;
  16217. typedef struct ma_IAudioClient ma_IAudioClient;
  16218. typedef struct ma_IAudioClient2 ma_IAudioClient2;
  16219. typedef struct ma_IAudioClient3 ma_IAudioClient3;
  16220. typedef struct ma_IAudioRenderClient ma_IAudioRenderClient;
  16221. typedef struct ma_IAudioCaptureClient ma_IAudioCaptureClient;
  16222. typedef ma_int64 MA_REFERENCE_TIME;
  16223. #define MA_AUDCLNT_STREAMFLAGS_CROSSPROCESS 0x00010000
  16224. #define MA_AUDCLNT_STREAMFLAGS_LOOPBACK 0x00020000
  16225. #define MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK 0x00040000
  16226. #define MA_AUDCLNT_STREAMFLAGS_NOPERSIST 0x00080000
  16227. #define MA_AUDCLNT_STREAMFLAGS_RATEADJUST 0x00100000
  16228. #define MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY 0x08000000
  16229. #define MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM 0x80000000
  16230. #define MA_AUDCLNT_SESSIONFLAGS_EXPIREWHENUNOWNED 0x10000000
  16231. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDE 0x20000000
  16232. #define MA_AUDCLNT_SESSIONFLAGS_DISPLAY_HIDEWHENEXPIRED 0x40000000
  16233. /* Buffer flags. */
  16234. #define MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY 1
  16235. #define MA_AUDCLNT_BUFFERFLAGS_SILENT 2
  16236. #define MA_AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR 4
  16237. typedef enum
  16238. {
  16239. ma_eRender = 0,
  16240. ma_eCapture = 1,
  16241. ma_eAll = 2
  16242. } ma_EDataFlow;
  16243. typedef enum
  16244. {
  16245. ma_eConsole = 0,
  16246. ma_eMultimedia = 1,
  16247. ma_eCommunications = 2
  16248. } ma_ERole;
  16249. typedef enum
  16250. {
  16251. MA_AUDCLNT_SHAREMODE_SHARED,
  16252. MA_AUDCLNT_SHAREMODE_EXCLUSIVE
  16253. } MA_AUDCLNT_SHAREMODE;
  16254. typedef enum
  16255. {
  16256. MA_AudioCategory_Other = 0 /* <-- miniaudio is only caring about Other. */
  16257. } MA_AUDIO_STREAM_CATEGORY;
  16258. typedef struct
  16259. {
  16260. ma_uint32 cbSize;
  16261. BOOL bIsOffload;
  16262. MA_AUDIO_STREAM_CATEGORY eCategory;
  16263. } ma_AudioClientProperties;
  16264. /* IUnknown */
  16265. typedef struct
  16266. {
  16267. /* IUnknown */
  16268. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IUnknown* pThis, const IID* const riid, void** ppObject);
  16269. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IUnknown* pThis);
  16270. ULONG (STDMETHODCALLTYPE * Release) (ma_IUnknown* pThis);
  16271. } ma_IUnknownVtbl;
  16272. struct ma_IUnknown
  16273. {
  16274. ma_IUnknownVtbl* lpVtbl;
  16275. };
  16276. static MA_INLINE HRESULT ma_IUnknown_QueryInterface(ma_IUnknown* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16277. static MA_INLINE ULONG ma_IUnknown_AddRef(ma_IUnknown* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16278. static MA_INLINE ULONG ma_IUnknown_Release(ma_IUnknown* pThis) { return pThis->lpVtbl->Release(pThis); }
  16279. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16280. /* IMMNotificationClient */
  16281. typedef struct
  16282. {
  16283. /* IUnknown */
  16284. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject);
  16285. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMNotificationClient* pThis);
  16286. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMNotificationClient* pThis);
  16287. /* IMMNotificationClient */
  16288. HRESULT (STDMETHODCALLTYPE * OnDeviceStateChanged) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState);
  16289. HRESULT (STDMETHODCALLTYPE * OnDeviceAdded) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID);
  16290. HRESULT (STDMETHODCALLTYPE * OnDeviceRemoved) (ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID);
  16291. HRESULT (STDMETHODCALLTYPE * OnDefaultDeviceChanged)(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID);
  16292. HRESULT (STDMETHODCALLTYPE * OnPropertyValueChanged)(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key);
  16293. } ma_IMMNotificationClientVtbl;
  16294. /* IMMDeviceEnumerator */
  16295. typedef struct
  16296. {
  16297. /* IUnknown */
  16298. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject);
  16299. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceEnumerator* pThis);
  16300. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceEnumerator* pThis);
  16301. /* IMMDeviceEnumerator */
  16302. HRESULT (STDMETHODCALLTYPE * EnumAudioEndpoints) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, DWORD dwStateMask, ma_IMMDeviceCollection** ppDevices);
  16303. HRESULT (STDMETHODCALLTYPE * GetDefaultAudioEndpoint) (ma_IMMDeviceEnumerator* pThis, ma_EDataFlow dataFlow, ma_ERole role, ma_IMMDevice** ppEndpoint);
  16304. HRESULT (STDMETHODCALLTYPE * GetDevice) (ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice);
  16305. HRESULT (STDMETHODCALLTYPE * RegisterEndpointNotificationCallback) (ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  16306. HRESULT (STDMETHODCALLTYPE * UnregisterEndpointNotificationCallback)(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient);
  16307. } ma_IMMDeviceEnumeratorVtbl;
  16308. struct ma_IMMDeviceEnumerator
  16309. {
  16310. ma_IMMDeviceEnumeratorVtbl* lpVtbl;
  16311. };
  16312. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_QueryInterface(ma_IMMDeviceEnumerator* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16313. static MA_INLINE ULONG ma_IMMDeviceEnumerator_AddRef(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16314. static MA_INLINE ULONG ma_IMMDeviceEnumerator_Release(ma_IMMDeviceEnumerator* pThis) { return pThis->lpVtbl->Release(pThis); }
  16315. 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); }
  16316. 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); }
  16317. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_GetDevice(ma_IMMDeviceEnumerator* pThis, LPCWSTR pID, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->GetDevice(pThis, pID, ppDevice); }
  16318. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_RegisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->RegisterEndpointNotificationCallback(pThis, pClient); }
  16319. static MA_INLINE HRESULT ma_IMMDeviceEnumerator_UnregisterEndpointNotificationCallback(ma_IMMDeviceEnumerator* pThis, ma_IMMNotificationClient* pClient) { return pThis->lpVtbl->UnregisterEndpointNotificationCallback(pThis, pClient); }
  16320. /* IMMDeviceCollection */
  16321. typedef struct
  16322. {
  16323. /* IUnknown */
  16324. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject);
  16325. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDeviceCollection* pThis);
  16326. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDeviceCollection* pThis);
  16327. /* IMMDeviceCollection */
  16328. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IMMDeviceCollection* pThis, UINT* pDevices);
  16329. HRESULT (STDMETHODCALLTYPE * Item) (ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice);
  16330. } ma_IMMDeviceCollectionVtbl;
  16331. struct ma_IMMDeviceCollection
  16332. {
  16333. ma_IMMDeviceCollectionVtbl* lpVtbl;
  16334. };
  16335. static MA_INLINE HRESULT ma_IMMDeviceCollection_QueryInterface(ma_IMMDeviceCollection* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16336. static MA_INLINE ULONG ma_IMMDeviceCollection_AddRef(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16337. static MA_INLINE ULONG ma_IMMDeviceCollection_Release(ma_IMMDeviceCollection* pThis) { return pThis->lpVtbl->Release(pThis); }
  16338. static MA_INLINE HRESULT ma_IMMDeviceCollection_GetCount(ma_IMMDeviceCollection* pThis, UINT* pDevices) { return pThis->lpVtbl->GetCount(pThis, pDevices); }
  16339. static MA_INLINE HRESULT ma_IMMDeviceCollection_Item(ma_IMMDeviceCollection* pThis, UINT nDevice, ma_IMMDevice** ppDevice) { return pThis->lpVtbl->Item(pThis, nDevice, ppDevice); }
  16340. /* IMMDevice */
  16341. typedef struct
  16342. {
  16343. /* IUnknown */
  16344. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IMMDevice* pThis, const IID* const riid, void** ppObject);
  16345. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IMMDevice* pThis);
  16346. ULONG (STDMETHODCALLTYPE * Release) (ma_IMMDevice* pThis);
  16347. /* IMMDevice */
  16348. HRESULT (STDMETHODCALLTYPE * Activate) (ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface);
  16349. HRESULT (STDMETHODCALLTYPE * OpenPropertyStore)(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties);
  16350. HRESULT (STDMETHODCALLTYPE * GetId) (ma_IMMDevice* pThis, LPWSTR *pID);
  16351. HRESULT (STDMETHODCALLTYPE * GetState) (ma_IMMDevice* pThis, DWORD *pState);
  16352. } ma_IMMDeviceVtbl;
  16353. struct ma_IMMDevice
  16354. {
  16355. ma_IMMDeviceVtbl* lpVtbl;
  16356. };
  16357. static MA_INLINE HRESULT ma_IMMDevice_QueryInterface(ma_IMMDevice* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16358. static MA_INLINE ULONG ma_IMMDevice_AddRef(ma_IMMDevice* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16359. static MA_INLINE ULONG ma_IMMDevice_Release(ma_IMMDevice* pThis) { return pThis->lpVtbl->Release(pThis); }
  16360. static MA_INLINE HRESULT ma_IMMDevice_Activate(ma_IMMDevice* pThis, const IID* const iid, DWORD dwClsCtx, PROPVARIANT* pActivationParams, void** ppInterface) { return pThis->lpVtbl->Activate(pThis, iid, dwClsCtx, pActivationParams, ppInterface); }
  16361. static MA_INLINE HRESULT ma_IMMDevice_OpenPropertyStore(ma_IMMDevice* pThis, DWORD stgmAccess, ma_IPropertyStore** ppProperties) { return pThis->lpVtbl->OpenPropertyStore(pThis, stgmAccess, ppProperties); }
  16362. static MA_INLINE HRESULT ma_IMMDevice_GetId(ma_IMMDevice* pThis, LPWSTR *pID) { return pThis->lpVtbl->GetId(pThis, pID); }
  16363. static MA_INLINE HRESULT ma_IMMDevice_GetState(ma_IMMDevice* pThis, DWORD *pState) { return pThis->lpVtbl->GetState(pThis, pState); }
  16364. #else
  16365. /* IActivateAudioInterfaceAsyncOperation */
  16366. typedef struct
  16367. {
  16368. /* IUnknown */
  16369. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject);
  16370. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  16371. ULONG (STDMETHODCALLTYPE * Release) (ma_IActivateAudioInterfaceAsyncOperation* pThis);
  16372. /* IActivateAudioInterfaceAsyncOperation */
  16373. HRESULT (STDMETHODCALLTYPE * GetActivateResult)(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface);
  16374. } ma_IActivateAudioInterfaceAsyncOperationVtbl;
  16375. struct ma_IActivateAudioInterfaceAsyncOperation
  16376. {
  16377. ma_IActivateAudioInterfaceAsyncOperationVtbl* lpVtbl;
  16378. };
  16379. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_QueryInterface(ma_IActivateAudioInterfaceAsyncOperation* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16380. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_AddRef(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16381. static MA_INLINE ULONG ma_IActivateAudioInterfaceAsyncOperation_Release(ma_IActivateAudioInterfaceAsyncOperation* pThis) { return pThis->lpVtbl->Release(pThis); }
  16382. static MA_INLINE HRESULT ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(ma_IActivateAudioInterfaceAsyncOperation* pThis, HRESULT *pActivateResult, ma_IUnknown** ppActivatedInterface) { return pThis->lpVtbl->GetActivateResult(pThis, pActivateResult, ppActivatedInterface); }
  16383. #endif
  16384. /* IPropertyStore */
  16385. typedef struct
  16386. {
  16387. /* IUnknown */
  16388. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject);
  16389. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IPropertyStore* pThis);
  16390. ULONG (STDMETHODCALLTYPE * Release) (ma_IPropertyStore* pThis);
  16391. /* IPropertyStore */
  16392. HRESULT (STDMETHODCALLTYPE * GetCount)(ma_IPropertyStore* pThis, DWORD* pPropCount);
  16393. HRESULT (STDMETHODCALLTYPE * GetAt) (ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey);
  16394. HRESULT (STDMETHODCALLTYPE * GetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar);
  16395. HRESULT (STDMETHODCALLTYPE * SetValue)(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar);
  16396. HRESULT (STDMETHODCALLTYPE * Commit) (ma_IPropertyStore* pThis);
  16397. } ma_IPropertyStoreVtbl;
  16398. struct ma_IPropertyStore
  16399. {
  16400. ma_IPropertyStoreVtbl* lpVtbl;
  16401. };
  16402. static MA_INLINE HRESULT ma_IPropertyStore_QueryInterface(ma_IPropertyStore* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16403. static MA_INLINE ULONG ma_IPropertyStore_AddRef(ma_IPropertyStore* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16404. static MA_INLINE ULONG ma_IPropertyStore_Release(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Release(pThis); }
  16405. static MA_INLINE HRESULT ma_IPropertyStore_GetCount(ma_IPropertyStore* pThis, DWORD* pPropCount) { return pThis->lpVtbl->GetCount(pThis, pPropCount); }
  16406. static MA_INLINE HRESULT ma_IPropertyStore_GetAt(ma_IPropertyStore* pThis, DWORD propIndex, PROPERTYKEY* pPropKey) { return pThis->lpVtbl->GetAt(pThis, propIndex, pPropKey); }
  16407. static MA_INLINE HRESULT ma_IPropertyStore_GetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, PROPVARIANT* pPropVar) { return pThis->lpVtbl->GetValue(pThis, pKey, pPropVar); }
  16408. static MA_INLINE HRESULT ma_IPropertyStore_SetValue(ma_IPropertyStore* pThis, const PROPERTYKEY* const pKey, const PROPVARIANT* const pPropVar) { return pThis->lpVtbl->SetValue(pThis, pKey, pPropVar); }
  16409. static MA_INLINE HRESULT ma_IPropertyStore_Commit(ma_IPropertyStore* pThis) { return pThis->lpVtbl->Commit(pThis); }
  16410. /* IAudioClient */
  16411. typedef struct
  16412. {
  16413. /* IUnknown */
  16414. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient* pThis, const IID* const riid, void** ppObject);
  16415. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient* pThis);
  16416. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient* pThis);
  16417. /* IAudioClient */
  16418. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  16419. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames);
  16420. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency);
  16421. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames);
  16422. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
  16423. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat);
  16424. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  16425. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient* pThis);
  16426. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient* pThis);
  16427. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient* pThis);
  16428. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient* pThis, HANDLE eventHandle);
  16429. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient* pThis, const IID* const riid, void** pp);
  16430. } ma_IAudioClientVtbl;
  16431. struct ma_IAudioClient
  16432. {
  16433. ma_IAudioClientVtbl* lpVtbl;
  16434. };
  16435. static MA_INLINE HRESULT ma_IAudioClient_QueryInterface(ma_IAudioClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16436. static MA_INLINE ULONG ma_IAudioClient_AddRef(ma_IAudioClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16437. static MA_INLINE ULONG ma_IAudioClient_Release(ma_IAudioClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  16438. 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 WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  16439. static MA_INLINE HRESULT ma_IAudioClient_GetBufferSize(ma_IAudioClient* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  16440. static MA_INLINE HRESULT ma_IAudioClient_GetStreamLatency(ma_IAudioClient* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  16441. static MA_INLINE HRESULT ma_IAudioClient_GetCurrentPadding(ma_IAudioClient* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  16442. static MA_INLINE HRESULT ma_IAudioClient_IsFormatSupported(ma_IAudioClient* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  16443. static MA_INLINE HRESULT ma_IAudioClient_GetMixFormat(ma_IAudioClient* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  16444. 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); }
  16445. static MA_INLINE HRESULT ma_IAudioClient_Start(ma_IAudioClient* pThis) { return pThis->lpVtbl->Start(pThis); }
  16446. static MA_INLINE HRESULT ma_IAudioClient_Stop(ma_IAudioClient* pThis) { return pThis->lpVtbl->Stop(pThis); }
  16447. static MA_INLINE HRESULT ma_IAudioClient_Reset(ma_IAudioClient* pThis) { return pThis->lpVtbl->Reset(pThis); }
  16448. static MA_INLINE HRESULT ma_IAudioClient_SetEventHandle(ma_IAudioClient* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  16449. static MA_INLINE HRESULT ma_IAudioClient_GetService(ma_IAudioClient* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  16450. /* IAudioClient2 */
  16451. typedef struct
  16452. {
  16453. /* IUnknown */
  16454. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject);
  16455. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient2* pThis);
  16456. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient2* pThis);
  16457. /* IAudioClient */
  16458. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  16459. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames);
  16460. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency);
  16461. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames);
  16462. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
  16463. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat);
  16464. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  16465. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient2* pThis);
  16466. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient2* pThis);
  16467. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient2* pThis);
  16468. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient2* pThis, HANDLE eventHandle);
  16469. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient2* pThis, const IID* const riid, void** pp);
  16470. /* IAudioClient2 */
  16471. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  16472. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties);
  16473. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  16474. } ma_IAudioClient2Vtbl;
  16475. struct ma_IAudioClient2
  16476. {
  16477. ma_IAudioClient2Vtbl* lpVtbl;
  16478. };
  16479. static MA_INLINE HRESULT ma_IAudioClient2_QueryInterface(ma_IAudioClient2* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16480. static MA_INLINE ULONG ma_IAudioClient2_AddRef(ma_IAudioClient2* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16481. static MA_INLINE ULONG ma_IAudioClient2_Release(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Release(pThis); }
  16482. 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 WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  16483. static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSize(ma_IAudioClient2* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  16484. static MA_INLINE HRESULT ma_IAudioClient2_GetStreamLatency(ma_IAudioClient2* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  16485. static MA_INLINE HRESULT ma_IAudioClient2_GetCurrentPadding(ma_IAudioClient2* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  16486. static MA_INLINE HRESULT ma_IAudioClient2_IsFormatSupported(ma_IAudioClient2* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  16487. static MA_INLINE HRESULT ma_IAudioClient2_GetMixFormat(ma_IAudioClient2* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  16488. 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); }
  16489. static MA_INLINE HRESULT ma_IAudioClient2_Start(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Start(pThis); }
  16490. static MA_INLINE HRESULT ma_IAudioClient2_Stop(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Stop(pThis); }
  16491. static MA_INLINE HRESULT ma_IAudioClient2_Reset(ma_IAudioClient2* pThis) { return pThis->lpVtbl->Reset(pThis); }
  16492. static MA_INLINE HRESULT ma_IAudioClient2_SetEventHandle(ma_IAudioClient2* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  16493. static MA_INLINE HRESULT ma_IAudioClient2_GetService(ma_IAudioClient2* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  16494. static MA_INLINE HRESULT ma_IAudioClient2_IsOffloadCapable(ma_IAudioClient2* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  16495. static MA_INLINE HRESULT ma_IAudioClient2_SetClientProperties(ma_IAudioClient2* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  16496. static MA_INLINE HRESULT ma_IAudioClient2_GetBufferSizeLimits(ma_IAudioClient2* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
  16497. /* IAudioClient3 */
  16498. typedef struct
  16499. {
  16500. /* IUnknown */
  16501. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject);
  16502. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioClient3* pThis);
  16503. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioClient3* pThis);
  16504. /* IAudioClient */
  16505. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, DWORD streamFlags, MA_REFERENCE_TIME bufferDuration, MA_REFERENCE_TIME periodicity, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  16506. HRESULT (STDMETHODCALLTYPE * GetBufferSize) (ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames);
  16507. HRESULT (STDMETHODCALLTYPE * GetStreamLatency) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency);
  16508. HRESULT (STDMETHODCALLTYPE * GetCurrentPadding)(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames);
  16509. HRESULT (STDMETHODCALLTYPE * IsFormatSupported)(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch);
  16510. HRESULT (STDMETHODCALLTYPE * GetMixFormat) (ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat);
  16511. HRESULT (STDMETHODCALLTYPE * GetDevicePeriod) (ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pDefaultDevicePeriod, MA_REFERENCE_TIME* pMinimumDevicePeriod);
  16512. HRESULT (STDMETHODCALLTYPE * Start) (ma_IAudioClient3* pThis);
  16513. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IAudioClient3* pThis);
  16514. HRESULT (STDMETHODCALLTYPE * Reset) (ma_IAudioClient3* pThis);
  16515. HRESULT (STDMETHODCALLTYPE * SetEventHandle) (ma_IAudioClient3* pThis, HANDLE eventHandle);
  16516. HRESULT (STDMETHODCALLTYPE * GetService) (ma_IAudioClient3* pThis, const IID* const riid, void** pp);
  16517. /* IAudioClient2 */
  16518. HRESULT (STDMETHODCALLTYPE * IsOffloadCapable) (ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable);
  16519. HRESULT (STDMETHODCALLTYPE * SetClientProperties)(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties);
  16520. HRESULT (STDMETHODCALLTYPE * GetBufferSizeLimits)(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration);
  16521. /* IAudioClient3 */
  16522. HRESULT (STDMETHODCALLTYPE * GetSharedModeEnginePeriod) (ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames);
  16523. HRESULT (STDMETHODCALLTYPE * GetCurrentSharedModeEnginePeriod)(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames);
  16524. HRESULT (STDMETHODCALLTYPE * InitializeSharedAudioStream) (ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid);
  16525. } ma_IAudioClient3Vtbl;
  16526. struct ma_IAudioClient3
  16527. {
  16528. ma_IAudioClient3Vtbl* lpVtbl;
  16529. };
  16530. static MA_INLINE HRESULT ma_IAudioClient3_QueryInterface(ma_IAudioClient3* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16531. static MA_INLINE ULONG ma_IAudioClient3_AddRef(ma_IAudioClient3* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16532. static MA_INLINE ULONG ma_IAudioClient3_Release(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Release(pThis); }
  16533. 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 WAVEFORMATEX* pFormat, const GUID* pAudioSessionGuid) { return pThis->lpVtbl->Initialize(pThis, shareMode, streamFlags, bufferDuration, periodicity, pFormat, pAudioSessionGuid); }
  16534. static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSize(ma_IAudioClient3* pThis, ma_uint32* pNumBufferFrames) { return pThis->lpVtbl->GetBufferSize(pThis, pNumBufferFrames); }
  16535. static MA_INLINE HRESULT ma_IAudioClient3_GetStreamLatency(ma_IAudioClient3* pThis, MA_REFERENCE_TIME* pLatency) { return pThis->lpVtbl->GetStreamLatency(pThis, pLatency); }
  16536. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentPadding(ma_IAudioClient3* pThis, ma_uint32* pNumPaddingFrames) { return pThis->lpVtbl->GetCurrentPadding(pThis, pNumPaddingFrames); }
  16537. static MA_INLINE HRESULT ma_IAudioClient3_IsFormatSupported(ma_IAudioClient3* pThis, MA_AUDCLNT_SHAREMODE shareMode, const WAVEFORMATEX* pFormat, WAVEFORMATEX** ppClosestMatch) { return pThis->lpVtbl->IsFormatSupported(pThis, shareMode, pFormat, ppClosestMatch); }
  16538. static MA_INLINE HRESULT ma_IAudioClient3_GetMixFormat(ma_IAudioClient3* pThis, WAVEFORMATEX** ppDeviceFormat) { return pThis->lpVtbl->GetMixFormat(pThis, ppDeviceFormat); }
  16539. 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); }
  16540. static MA_INLINE HRESULT ma_IAudioClient3_Start(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Start(pThis); }
  16541. static MA_INLINE HRESULT ma_IAudioClient3_Stop(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Stop(pThis); }
  16542. static MA_INLINE HRESULT ma_IAudioClient3_Reset(ma_IAudioClient3* pThis) { return pThis->lpVtbl->Reset(pThis); }
  16543. static MA_INLINE HRESULT ma_IAudioClient3_SetEventHandle(ma_IAudioClient3* pThis, HANDLE eventHandle) { return pThis->lpVtbl->SetEventHandle(pThis, eventHandle); }
  16544. static MA_INLINE HRESULT ma_IAudioClient3_GetService(ma_IAudioClient3* pThis, const IID* const riid, void** pp) { return pThis->lpVtbl->GetService(pThis, riid, pp); }
  16545. static MA_INLINE HRESULT ma_IAudioClient3_IsOffloadCapable(ma_IAudioClient3* pThis, MA_AUDIO_STREAM_CATEGORY category, BOOL* pOffloadCapable) { return pThis->lpVtbl->IsOffloadCapable(pThis, category, pOffloadCapable); }
  16546. static MA_INLINE HRESULT ma_IAudioClient3_SetClientProperties(ma_IAudioClient3* pThis, const ma_AudioClientProperties* pProperties) { return pThis->lpVtbl->SetClientProperties(pThis, pProperties); }
  16547. static MA_INLINE HRESULT ma_IAudioClient3_GetBufferSizeLimits(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, BOOL eventDriven, MA_REFERENCE_TIME* pMinBufferDuration, MA_REFERENCE_TIME* pMaxBufferDuration) { return pThis->lpVtbl->GetBufferSizeLimits(pThis, pFormat, eventDriven, pMinBufferDuration, pMaxBufferDuration); }
  16548. static MA_INLINE HRESULT ma_IAudioClient3_GetSharedModeEnginePeriod(ma_IAudioClient3* pThis, const WAVEFORMATEX* pFormat, ma_uint32* pDefaultPeriodInFrames, ma_uint32* pFundamentalPeriodInFrames, ma_uint32* pMinPeriodInFrames, ma_uint32* pMaxPeriodInFrames) { return pThis->lpVtbl->GetSharedModeEnginePeriod(pThis, pFormat, pDefaultPeriodInFrames, pFundamentalPeriodInFrames, pMinPeriodInFrames, pMaxPeriodInFrames); }
  16549. static MA_INLINE HRESULT ma_IAudioClient3_GetCurrentSharedModeEnginePeriod(ma_IAudioClient3* pThis, WAVEFORMATEX** ppFormat, ma_uint32* pCurrentPeriodInFrames) { return pThis->lpVtbl->GetCurrentSharedModeEnginePeriod(pThis, ppFormat, pCurrentPeriodInFrames); }
  16550. static MA_INLINE HRESULT ma_IAudioClient3_InitializeSharedAudioStream(ma_IAudioClient3* pThis, DWORD streamFlags, ma_uint32 periodInFrames, const WAVEFORMATEX* pFormat, const GUID* pAudioSessionGUID) { return pThis->lpVtbl->InitializeSharedAudioStream(pThis, streamFlags, periodInFrames, pFormat, pAudioSessionGUID); }
  16551. /* IAudioRenderClient */
  16552. typedef struct
  16553. {
  16554. /* IUnknown */
  16555. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject);
  16556. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioRenderClient* pThis);
  16557. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioRenderClient* pThis);
  16558. /* IAudioRenderClient */
  16559. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData);
  16560. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer)(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags);
  16561. } ma_IAudioRenderClientVtbl;
  16562. struct ma_IAudioRenderClient
  16563. {
  16564. ma_IAudioRenderClientVtbl* lpVtbl;
  16565. };
  16566. static MA_INLINE HRESULT ma_IAudioRenderClient_QueryInterface(ma_IAudioRenderClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16567. static MA_INLINE ULONG ma_IAudioRenderClient_AddRef(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16568. static MA_INLINE ULONG ma_IAudioRenderClient_Release(ma_IAudioRenderClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  16569. static MA_INLINE HRESULT ma_IAudioRenderClient_GetBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesRequested, BYTE** ppData) { return pThis->lpVtbl->GetBuffer(pThis, numFramesRequested, ppData); }
  16570. static MA_INLINE HRESULT ma_IAudioRenderClient_ReleaseBuffer(ma_IAudioRenderClient* pThis, ma_uint32 numFramesWritten, DWORD dwFlags) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesWritten, dwFlags); }
  16571. /* IAudioCaptureClient */
  16572. typedef struct
  16573. {
  16574. /* IUnknown */
  16575. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject);
  16576. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IAudioCaptureClient* pThis);
  16577. ULONG (STDMETHODCALLTYPE * Release) (ma_IAudioCaptureClient* pThis);
  16578. /* IAudioRenderClient */
  16579. HRESULT (STDMETHODCALLTYPE * GetBuffer) (ma_IAudioCaptureClient* pThis, BYTE** ppData, ma_uint32* pNumFramesToRead, DWORD* pFlags, ma_uint64* pDevicePosition, ma_uint64* pQPCPosition);
  16580. HRESULT (STDMETHODCALLTYPE * ReleaseBuffer) (ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead);
  16581. HRESULT (STDMETHODCALLTYPE * GetNextPacketSize)(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket);
  16582. } ma_IAudioCaptureClientVtbl;
  16583. struct ma_IAudioCaptureClient
  16584. {
  16585. ma_IAudioCaptureClientVtbl* lpVtbl;
  16586. };
  16587. static MA_INLINE HRESULT ma_IAudioCaptureClient_QueryInterface(ma_IAudioCaptureClient* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  16588. static MA_INLINE ULONG ma_IAudioCaptureClient_AddRef(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  16589. static MA_INLINE ULONG ma_IAudioCaptureClient_Release(ma_IAudioCaptureClient* pThis) { return pThis->lpVtbl->Release(pThis); }
  16590. 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); }
  16591. static MA_INLINE HRESULT ma_IAudioCaptureClient_ReleaseBuffer(ma_IAudioCaptureClient* pThis, ma_uint32 numFramesRead) { return pThis->lpVtbl->ReleaseBuffer(pThis, numFramesRead); }
  16592. static MA_INLINE HRESULT ma_IAudioCaptureClient_GetNextPacketSize(ma_IAudioCaptureClient* pThis, ma_uint32* pNumFramesInNextPacket) { return pThis->lpVtbl->GetNextPacketSize(pThis, pNumFramesInNextPacket); }
  16593. #if defined(MA_WIN32_UWP)
  16594. /* mmdevapi Functions */
  16595. typedef HRESULT (WINAPI * MA_PFN_ActivateAudioInterfaceAsync)(LPCWSTR deviceInterfacePath, const IID* riid, PROPVARIANT *activationParams, ma_IActivateAudioInterfaceCompletionHandler *completionHandler, ma_IActivateAudioInterfaceAsyncOperation **activationOperation);
  16596. #endif
  16597. /* Avrt Functions */
  16598. typedef HANDLE (WINAPI * MA_PFN_AvSetMmThreadCharacteristicsW)(LPCWSTR TaskName, LPDWORD TaskIndex);
  16599. typedef BOOL (WINAPI * MA_PFN_AvRevertMmThreadCharacteristics)(HANDLE AvrtHandle);
  16600. #if !defined(MA_WIN32_DESKTOP) && !defined(MA_WIN32_GDK)
  16601. typedef struct ma_completion_handler_uwp ma_completion_handler_uwp;
  16602. typedef struct
  16603. {
  16604. /* IUnknown */
  16605. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject);
  16606. ULONG (STDMETHODCALLTYPE * AddRef) (ma_completion_handler_uwp* pThis);
  16607. ULONG (STDMETHODCALLTYPE * Release) (ma_completion_handler_uwp* pThis);
  16608. /* IActivateAudioInterfaceCompletionHandler */
  16609. HRESULT (STDMETHODCALLTYPE * ActivateCompleted)(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation);
  16610. } ma_completion_handler_uwp_vtbl;
  16611. struct ma_completion_handler_uwp
  16612. {
  16613. ma_completion_handler_uwp_vtbl* lpVtbl;
  16614. MA_ATOMIC(4, ma_uint32) counter;
  16615. HANDLE hEvent;
  16616. };
  16617. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_QueryInterface(ma_completion_handler_uwp* pThis, const IID* const riid, void** ppObject)
  16618. {
  16619. /*
  16620. We need to "implement" IAgileObject which is just an indicator that's used internally by WASAPI for some multithreading management. To
  16621. "implement" this, we just make sure we return pThis when the IAgileObject is requested.
  16622. */
  16623. 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)) {
  16624. *ppObject = NULL;
  16625. return E_NOINTERFACE;
  16626. }
  16627. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  16628. *ppObject = (void*)pThis;
  16629. ((ma_completion_handler_uwp_vtbl*)pThis->lpVtbl)->AddRef(pThis);
  16630. return S_OK;
  16631. }
  16632. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_AddRef(ma_completion_handler_uwp* pThis)
  16633. {
  16634. return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
  16635. }
  16636. static ULONG STDMETHODCALLTYPE ma_completion_handler_uwp_Release(ma_completion_handler_uwp* pThis)
  16637. {
  16638. ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  16639. if (newRefCount == 0) {
  16640. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  16641. }
  16642. return (ULONG)newRefCount;
  16643. }
  16644. static HRESULT STDMETHODCALLTYPE ma_completion_handler_uwp_ActivateCompleted(ma_completion_handler_uwp* pThis, ma_IActivateAudioInterfaceAsyncOperation* pActivateOperation)
  16645. {
  16646. (void)pActivateOperation;
  16647. SetEvent(pThis->hEvent);
  16648. return S_OK;
  16649. }
  16650. static ma_completion_handler_uwp_vtbl g_maCompletionHandlerVtblInstance = {
  16651. ma_completion_handler_uwp_QueryInterface,
  16652. ma_completion_handler_uwp_AddRef,
  16653. ma_completion_handler_uwp_Release,
  16654. ma_completion_handler_uwp_ActivateCompleted
  16655. };
  16656. static ma_result ma_completion_handler_uwp_init(ma_completion_handler_uwp* pHandler)
  16657. {
  16658. MA_ASSERT(pHandler != NULL);
  16659. MA_ZERO_OBJECT(pHandler);
  16660. pHandler->lpVtbl = &g_maCompletionHandlerVtblInstance;
  16661. pHandler->counter = 1;
  16662. pHandler->hEvent = CreateEventW(NULL, FALSE, FALSE, NULL);
  16663. if (pHandler->hEvent == NULL) {
  16664. return ma_result_from_GetLastError(GetLastError());
  16665. }
  16666. return MA_SUCCESS;
  16667. }
  16668. static void ma_completion_handler_uwp_uninit(ma_completion_handler_uwp* pHandler)
  16669. {
  16670. if (pHandler->hEvent != NULL) {
  16671. CloseHandle(pHandler->hEvent);
  16672. }
  16673. }
  16674. static void ma_completion_handler_uwp_wait(ma_completion_handler_uwp* pHandler)
  16675. {
  16676. WaitForSingleObject(pHandler->hEvent, INFINITE);
  16677. }
  16678. #endif /* !MA_WIN32_DESKTOP */
  16679. /* We need a virtual table for our notification client object that's used for detecting changes to the default device. */
  16680. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16681. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_QueryInterface(ma_IMMNotificationClient* pThis, const IID* const riid, void** ppObject)
  16682. {
  16683. /*
  16684. We care about two interfaces - IUnknown and IMMNotificationClient. If the requested IID is something else
  16685. we just return E_NOINTERFACE. Otherwise we need to increment the reference counter and return S_OK.
  16686. */
  16687. if (!ma_is_guid_equal(riid, &MA_IID_IUnknown) && !ma_is_guid_equal(riid, &MA_IID_IMMNotificationClient)) {
  16688. *ppObject = NULL;
  16689. return E_NOINTERFACE;
  16690. }
  16691. /* Getting here means the IID is IUnknown or IMMNotificationClient. */
  16692. *ppObject = (void*)pThis;
  16693. ((ma_IMMNotificationClientVtbl*)pThis->lpVtbl)->AddRef(pThis);
  16694. return S_OK;
  16695. }
  16696. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_AddRef(ma_IMMNotificationClient* pThis)
  16697. {
  16698. return (ULONG)c89atomic_fetch_add_32(&pThis->counter, 1) + 1;
  16699. }
  16700. static ULONG STDMETHODCALLTYPE ma_IMMNotificationClient_Release(ma_IMMNotificationClient* pThis)
  16701. {
  16702. ma_uint32 newRefCount = c89atomic_fetch_sub_32(&pThis->counter, 1) - 1;
  16703. if (newRefCount == 0) {
  16704. return 0; /* We don't free anything here because we never allocate the object on the heap. */
  16705. }
  16706. return (ULONG)newRefCount;
  16707. }
  16708. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceStateChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, DWORD dwNewState)
  16709. {
  16710. ma_bool32 isThisDevice = MA_FALSE;
  16711. ma_bool32 isCapture = MA_FALSE;
  16712. ma_bool32 isPlayback = MA_FALSE;
  16713. #ifdef MA_DEBUG_OUTPUT
  16714. /*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);*/
  16715. #endif
  16716. /*
  16717. 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
  16718. that the device is disabled or has been unplugged.
  16719. */
  16720. 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)) {
  16721. isCapture = MA_TRUE;
  16722. if (wcscmp(pThis->pDevice->capture.id.wasapi, pDeviceID) == 0) {
  16723. isThisDevice = MA_TRUE;
  16724. }
  16725. }
  16726. if (pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting && (pThis->pDevice->type == ma_device_type_playback || pThis->pDevice->type == ma_device_type_duplex)) {
  16727. isPlayback = MA_TRUE;
  16728. if (wcscmp(pThis->pDevice->playback.id.wasapi, pDeviceID) == 0) {
  16729. isThisDevice = MA_TRUE;
  16730. }
  16731. }
  16732. /*
  16733. If the device ID matches our device we need to mark our device as detached and stop it. When a
  16734. device is added in OnDeviceAdded(), we'll restart it. We only mark it as detached if the device
  16735. was started at the time of being removed.
  16736. */
  16737. if (isThisDevice) {
  16738. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) == 0) {
  16739. /*
  16740. Unplugged or otherwise unavailable. Mark as detached if we were in a playing state. We'll
  16741. use this to determine whether or not we need to automatically start the device when it's
  16742. plugged back in again.
  16743. */
  16744. if (ma_device_get_state(pThis->pDevice) == ma_device_state_started) {
  16745. if (isPlayback) {
  16746. pThis->pDevice->wasapi.isDetachedPlayback = MA_TRUE;
  16747. }
  16748. if (isCapture) {
  16749. pThis->pDevice->wasapi.isDetachedCapture = MA_TRUE;
  16750. }
  16751. ma_device_stop(pThis->pDevice);
  16752. }
  16753. }
  16754. if ((dwNewState & MA_MM_DEVICE_STATE_ACTIVE) != 0) {
  16755. /* The device was activated. If we were detached, we need to start it again. */
  16756. ma_bool8 tryRestartingDevice = MA_FALSE;
  16757. if (isPlayback) {
  16758. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  16759. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  16760. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  16761. tryRestartingDevice = MA_TRUE;
  16762. }
  16763. }
  16764. if (isCapture) {
  16765. if (pThis->pDevice->wasapi.isDetachedCapture) {
  16766. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  16767. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  16768. tryRestartingDevice = MA_TRUE;
  16769. }
  16770. }
  16771. if (tryRestartingDevice) {
  16772. if (pThis->pDevice->wasapi.isDetachedPlayback == MA_FALSE && pThis->pDevice->wasapi.isDetachedCapture == MA_FALSE) {
  16773. ma_device_start(pThis->pDevice);
  16774. }
  16775. }
  16776. }
  16777. }
  16778. return S_OK;
  16779. }
  16780. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceAdded(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID)
  16781. {
  16782. #ifdef MA_DEBUG_OUTPUT
  16783. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceAdded(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  16784. #endif
  16785. /* We don't need to worry about this event for our purposes. */
  16786. (void)pThis;
  16787. (void)pDeviceID;
  16788. return S_OK;
  16789. }
  16790. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDeviceRemoved(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID)
  16791. {
  16792. #ifdef MA_DEBUG_OUTPUT
  16793. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnDeviceRemoved(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  16794. #endif
  16795. /* We don't need to worry about this event for our purposes. */
  16796. (void)pThis;
  16797. (void)pDeviceID;
  16798. return S_OK;
  16799. }
  16800. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnDefaultDeviceChanged(ma_IMMNotificationClient* pThis, ma_EDataFlow dataFlow, ma_ERole role, LPCWSTR pDefaultDeviceID)
  16801. {
  16802. #ifdef MA_DEBUG_OUTPUT
  16803. /*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)");*/
  16804. #endif
  16805. /* We only ever use the eConsole role in miniaudio. */
  16806. if (role != ma_eConsole) {
  16807. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting: role != eConsole\n");
  16808. return S_OK;
  16809. }
  16810. /* We only care about devices with the same data flow and role as the current device. */
  16811. if ((pThis->pDevice->type == ma_device_type_playback && dataFlow != ma_eRender) ||
  16812. (pThis->pDevice->type == ma_device_type_capture && dataFlow != ma_eCapture)) {
  16813. ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Stream rerouting abandoned because dataFlow does match device type.\n");
  16814. return S_OK;
  16815. }
  16816. /* Don't do automatic stream routing if we're not allowed. */
  16817. if ((dataFlow == ma_eRender && pThis->pDevice->wasapi.allowPlaybackAutoStreamRouting == MA_FALSE) ||
  16818. (dataFlow == ma_eCapture && pThis->pDevice->wasapi.allowCaptureAutoStreamRouting == MA_FALSE)) {
  16819. 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");
  16820. return S_OK;
  16821. }
  16822. /*
  16823. Not currently supporting automatic stream routing in exclusive mode. This is not working correctly on my machine due to
  16824. AUDCLNT_E_DEVICE_IN_USE errors when reinitializing the device. If this is a bug in miniaudio, we can try re-enabling this once
  16825. it's fixed.
  16826. */
  16827. if ((dataFlow == ma_eRender && pThis->pDevice->playback.shareMode == ma_share_mode_exclusive) ||
  16828. (dataFlow == ma_eCapture && pThis->pDevice->capture.shareMode == ma_share_mode_exclusive)) {
  16829. 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");
  16830. return S_OK;
  16831. }
  16832. /*
  16833. Second attempt at device rerouting. We're going to retrieve the device's state at the time of
  16834. the route change. We're then going to stop the device, reinitialize the device, and then start
  16835. it again if the state before stopping was ma_device_state_started.
  16836. */
  16837. {
  16838. ma_uint32 previousState = ma_device_get_state(pThis->pDevice);
  16839. ma_bool8 restartDevice = MA_FALSE;
  16840. if (previousState == ma_device_state_started) {
  16841. ma_device_stop(pThis->pDevice);
  16842. restartDevice = MA_TRUE;
  16843. }
  16844. if (pDefaultDeviceID != NULL) { /* <-- The input device ID will be null if there's no other device available. */
  16845. if (dataFlow == ma_eRender) {
  16846. ma_device_reroute__wasapi(pThis->pDevice, ma_device_type_playback);
  16847. if (pThis->pDevice->wasapi.isDetachedPlayback) {
  16848. pThis->pDevice->wasapi.isDetachedPlayback = MA_FALSE;
  16849. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedCapture) {
  16850. restartDevice = MA_FALSE; /* It's a duplex device and the capture side is detached. We cannot be restarting the device just yet. */
  16851. } else {
  16852. 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. */
  16853. }
  16854. }
  16855. } else {
  16856. ma_device_reroute__wasapi(pThis->pDevice, (pThis->pDevice->type == ma_device_type_loopback) ? ma_device_type_loopback : ma_device_type_capture);
  16857. if (pThis->pDevice->wasapi.isDetachedCapture) {
  16858. pThis->pDevice->wasapi.isDetachedCapture = MA_FALSE;
  16859. if (pThis->pDevice->type == ma_device_type_duplex && pThis->pDevice->wasapi.isDetachedPlayback) {
  16860. restartDevice = MA_FALSE; /* It's a duplex device and the playback side is detached. We cannot be restarting the device just yet. */
  16861. } else {
  16862. 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. */
  16863. }
  16864. }
  16865. }
  16866. if (restartDevice) {
  16867. ma_device_start(pThis->pDevice);
  16868. }
  16869. }
  16870. }
  16871. return S_OK;
  16872. }
  16873. static HRESULT STDMETHODCALLTYPE ma_IMMNotificationClient_OnPropertyValueChanged(ma_IMMNotificationClient* pThis, LPCWSTR pDeviceID, const PROPERTYKEY key)
  16874. {
  16875. #ifdef MA_DEBUG_OUTPUT
  16876. /*ma_log_postf(ma_device_get_log(pThis->pDevice), MA_LOG_LEVEL_DEBUG, "IMMNotificationClient_OnPropertyValueChanged(pDeviceID=%S)\n", (pDeviceID != NULL) ? pDeviceID : L"(NULL)");*/
  16877. #endif
  16878. (void)pThis;
  16879. (void)pDeviceID;
  16880. (void)key;
  16881. return S_OK;
  16882. }
  16883. static ma_IMMNotificationClientVtbl g_maNotificationCientVtbl = {
  16884. ma_IMMNotificationClient_QueryInterface,
  16885. ma_IMMNotificationClient_AddRef,
  16886. ma_IMMNotificationClient_Release,
  16887. ma_IMMNotificationClient_OnDeviceStateChanged,
  16888. ma_IMMNotificationClient_OnDeviceAdded,
  16889. ma_IMMNotificationClient_OnDeviceRemoved,
  16890. ma_IMMNotificationClient_OnDefaultDeviceChanged,
  16891. ma_IMMNotificationClient_OnPropertyValueChanged
  16892. };
  16893. #endif /* MA_WIN32_DESKTOP */
  16894. static LPCWSTR ma_to_usage_string__wasapi(ma_wasapi_usage usage)
  16895. {
  16896. switch (usage) {
  16897. case ma_wasapi_usage_default: return NULL;
  16898. case ma_wasapi_usage_games: return L"Games";
  16899. case ma_wasapi_usage_pro_audio: return L"Pro Audio";
  16900. default: break;
  16901. }
  16902. return NULL;
  16903. }
  16904. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  16905. typedef ma_IMMDevice ma_WASAPIDeviceInterface;
  16906. #else
  16907. typedef ma_IUnknown ma_WASAPIDeviceInterface;
  16908. #endif
  16909. #define MA_CONTEXT_COMMAND_QUIT__WASAPI 1
  16910. #define MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI 2
  16911. #define MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI 3
  16912. static ma_context_command__wasapi ma_context_init_command__wasapi(int code)
  16913. {
  16914. ma_context_command__wasapi cmd;
  16915. MA_ZERO_OBJECT(&cmd);
  16916. cmd.code = code;
  16917. return cmd;
  16918. }
  16919. static ma_result ma_context_post_command__wasapi(ma_context* pContext, const ma_context_command__wasapi* pCmd)
  16920. {
  16921. /* For now we are doing everything synchronously, but I might relax this later if the need arises. */
  16922. ma_result result;
  16923. ma_bool32 isUsingLocalEvent = MA_FALSE;
  16924. ma_event localEvent;
  16925. MA_ASSERT(pContext != NULL);
  16926. MA_ASSERT(pCmd != NULL);
  16927. if (pCmd->pEvent == NULL) {
  16928. isUsingLocalEvent = MA_TRUE;
  16929. result = ma_event_init(&localEvent);
  16930. if (result != MA_SUCCESS) {
  16931. return result; /* Failed to create the event for this command. */
  16932. }
  16933. }
  16934. /* Here is where we add the command to the list. If there's not enough room we'll spin until there is. */
  16935. ma_mutex_lock(&pContext->wasapi.commandLock);
  16936. {
  16937. ma_uint32 index;
  16938. /* Spin until we've got some space available. */
  16939. while (pContext->wasapi.commandCount == ma_countof(pContext->wasapi.commands)) {
  16940. ma_yield();
  16941. }
  16942. /* Space is now available. Can safely add to the list. */
  16943. index = (pContext->wasapi.commandIndex + pContext->wasapi.commandCount) % ma_countof(pContext->wasapi.commands);
  16944. pContext->wasapi.commands[index] = *pCmd;
  16945. pContext->wasapi.commands[index].pEvent = &localEvent;
  16946. pContext->wasapi.commandCount += 1;
  16947. /* Now that the command has been added, release the semaphore so ma_context_next_command__wasapi() can return. */
  16948. ma_semaphore_release(&pContext->wasapi.commandSem);
  16949. }
  16950. ma_mutex_unlock(&pContext->wasapi.commandLock);
  16951. if (isUsingLocalEvent) {
  16952. ma_event_wait(&localEvent);
  16953. ma_event_uninit(&localEvent);
  16954. }
  16955. return MA_SUCCESS;
  16956. }
  16957. static ma_result ma_context_next_command__wasapi(ma_context* pContext, ma_context_command__wasapi* pCmd)
  16958. {
  16959. ma_result result = MA_SUCCESS;
  16960. MA_ASSERT(pContext != NULL);
  16961. MA_ASSERT(pCmd != NULL);
  16962. result = ma_semaphore_wait(&pContext->wasapi.commandSem);
  16963. if (result == MA_SUCCESS) {
  16964. ma_mutex_lock(&pContext->wasapi.commandLock);
  16965. {
  16966. *pCmd = pContext->wasapi.commands[pContext->wasapi.commandIndex];
  16967. pContext->wasapi.commandIndex = (pContext->wasapi.commandIndex + 1) % ma_countof(pContext->wasapi.commands);
  16968. pContext->wasapi.commandCount -= 1;
  16969. }
  16970. ma_mutex_unlock(&pContext->wasapi.commandLock);
  16971. }
  16972. return result;
  16973. }
  16974. static ma_thread_result MA_THREADCALL ma_context_command_thread__wasapi(void* pUserData)
  16975. {
  16976. ma_result result;
  16977. ma_context* pContext = (ma_context*)pUserData;
  16978. MA_ASSERT(pContext != NULL);
  16979. for (;;) {
  16980. ma_context_command__wasapi cmd;
  16981. result = ma_context_next_command__wasapi(pContext, &cmd);
  16982. if (result != MA_SUCCESS) {
  16983. break;
  16984. }
  16985. switch (cmd.code)
  16986. {
  16987. case MA_CONTEXT_COMMAND_QUIT__WASAPI:
  16988. {
  16989. /* Do nothing. Handled after the switch. */
  16990. } break;
  16991. case MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI:
  16992. {
  16993. if (cmd.data.createAudioClient.deviceType == ma_device_type_playback) {
  16994. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioRenderClient, cmd.data.createAudioClient.ppAudioClientService));
  16995. } else {
  16996. *cmd.data.createAudioClient.pResult = ma_result_from_HRESULT(ma_IAudioClient_GetService((ma_IAudioClient*)cmd.data.createAudioClient.pAudioClient, &MA_IID_IAudioCaptureClient, cmd.data.createAudioClient.ppAudioClientService));
  16997. }
  16998. } break;
  16999. case MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI:
  17000. {
  17001. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_playback) {
  17002. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback != NULL) {
  17003. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback);
  17004. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientPlayback = NULL;
  17005. }
  17006. }
  17007. if (cmd.data.releaseAudioClient.deviceType == ma_device_type_capture) {
  17008. if (cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture != NULL) {
  17009. ma_IAudioClient_Release((ma_IAudioClient*)cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture);
  17010. cmd.data.releaseAudioClient.pDevice->wasapi.pAudioClientCapture = NULL;
  17011. }
  17012. }
  17013. } break;
  17014. default:
  17015. {
  17016. /* Unknown command. Ignore it, but trigger an assert in debug mode so we're aware of it. */
  17017. MA_ASSERT(MA_FALSE);
  17018. } break;
  17019. }
  17020. if (cmd.pEvent != NULL) {
  17021. ma_event_signal(cmd.pEvent);
  17022. }
  17023. if (cmd.code == MA_CONTEXT_COMMAND_QUIT__WASAPI) {
  17024. break; /* Received a quit message. Get out of here. */
  17025. }
  17026. }
  17027. return (ma_thread_result)0;
  17028. }
  17029. static ma_result ma_device_create_IAudioClient_service__wasapi(ma_context* pContext, ma_device_type deviceType, ma_IAudioClient* pAudioClient, void** ppAudioClientService)
  17030. {
  17031. ma_result result;
  17032. ma_result cmdResult;
  17033. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_CREATE_IAUDIOCLIENT__WASAPI);
  17034. cmd.data.createAudioClient.deviceType = deviceType;
  17035. cmd.data.createAudioClient.pAudioClient = (void*)pAudioClient;
  17036. cmd.data.createAudioClient.ppAudioClientService = ppAudioClientService;
  17037. cmd.data.createAudioClient.pResult = &cmdResult; /* Declared locally, but won't be dereferenced after this function returns since execution of the command will wait here. */
  17038. result = ma_context_post_command__wasapi(pContext, &cmd); /* This will not return until the command has actually been run. */
  17039. if (result != MA_SUCCESS) {
  17040. return result;
  17041. }
  17042. return *cmd.data.createAudioClient.pResult;
  17043. }
  17044. #if 0 /* Not used at the moment, but leaving here for future use. */
  17045. static ma_result ma_device_release_IAudioClient_service__wasapi(ma_device* pDevice, ma_device_type deviceType)
  17046. {
  17047. ma_result result;
  17048. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_RELEASE_IAUDIOCLIENT__WASAPI);
  17049. cmd.data.releaseAudioClient.pDevice = pDevice;
  17050. cmd.data.releaseAudioClient.deviceType = deviceType;
  17051. result = ma_context_post_command__wasapi(pDevice->pContext, &cmd); /* This will not return until the command has actually been run. */
  17052. if (result != MA_SUCCESS) {
  17053. return result;
  17054. }
  17055. return MA_SUCCESS;
  17056. }
  17057. #endif
  17058. static void ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(const WAVEFORMATEX* pWF, ma_share_mode shareMode, ma_device_info* pInfo)
  17059. {
  17060. MA_ASSERT(pWF != NULL);
  17061. MA_ASSERT(pInfo != NULL);
  17062. if (pInfo->nativeDataFormatCount >= ma_countof(pInfo->nativeDataFormats)) {
  17063. return; /* Too many data formats. Need to ignore this one. Don't think this should ever happen with WASAPI. */
  17064. }
  17065. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].format = ma_format_from_WAVEFORMATEX(pWF);
  17066. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].channels = pWF->nChannels;
  17067. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].sampleRate = pWF->nSamplesPerSec;
  17068. pInfo->nativeDataFormats[pInfo->nativeDataFormatCount].flags = (shareMode == ma_share_mode_exclusive) ? MA_DATA_FORMAT_FLAG_EXCLUSIVE_MODE : 0;
  17069. pInfo->nativeDataFormatCount += 1;
  17070. }
  17071. 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)
  17072. {
  17073. HRESULT hr;
  17074. WAVEFORMATEX* pWF = NULL;
  17075. MA_ASSERT(pAudioClient != NULL);
  17076. MA_ASSERT(pInfo != NULL);
  17077. /* Shared Mode. We use GetMixFormat() here. */
  17078. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pAudioClient, (WAVEFORMATEX**)&pWF);
  17079. if (SUCCEEDED(hr)) {
  17080. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_shared, pInfo);
  17081. } else {
  17082. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve mix format for device info retrieval.");
  17083. return ma_result_from_HRESULT(hr);
  17084. }
  17085. /*
  17086. Exlcusive Mode. We repeatedly call IsFormatSupported() here. This is not currently supported on
  17087. UWP. Failure to retrieve the exclusive mode format is not considered an error, so from here on
  17088. out, MA_SUCCESS is guaranteed to be returned.
  17089. */
  17090. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17091. {
  17092. ma_IPropertyStore *pProperties;
  17093. /*
  17094. The first thing to do is get the format from PKEY_AudioEngine_DeviceFormat. This should give us a channel count we assume is
  17095. correct which will simplify our searching.
  17096. */
  17097. hr = ma_IMMDevice_OpenPropertyStore((ma_IMMDevice*)pMMDevice, STGM_READ, &pProperties);
  17098. if (SUCCEEDED(hr)) {
  17099. PROPVARIANT var;
  17100. ma_PropVariantInit(&var);
  17101. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_AudioEngine_DeviceFormat, &var);
  17102. if (SUCCEEDED(hr)) {
  17103. pWF = (WAVEFORMATEX*)var.blob.pBlobData;
  17104. /*
  17105. In my testing, the format returned by PKEY_AudioEngine_DeviceFormat is suitable for exclusive mode so we check this format
  17106. first. If this fails, fall back to a search.
  17107. */
  17108. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pWF, NULL);
  17109. if (SUCCEEDED(hr)) {
  17110. /* The format returned by PKEY_AudioEngine_DeviceFormat is supported. */
  17111. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX(pWF, ma_share_mode_exclusive, pInfo);
  17112. } else {
  17113. /*
  17114. The format returned by PKEY_AudioEngine_DeviceFormat is not supported, so fall back to a search. We assume the channel
  17115. count returned by MA_PKEY_AudioEngine_DeviceFormat is valid and correct. For simplicity we're only returning one format.
  17116. */
  17117. ma_uint32 channels = pWF->nChannels;
  17118. ma_channel defaultChannelMap[MA_MAX_CHANNELS];
  17119. WAVEFORMATEXTENSIBLE wf;
  17120. ma_bool32 found;
  17121. ma_uint32 iFormat;
  17122. /* Make sure we don't overflow the channel map. */
  17123. if (channels > MA_MAX_CHANNELS) {
  17124. channels = MA_MAX_CHANNELS;
  17125. }
  17126. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, defaultChannelMap, ma_countof(defaultChannelMap), channels);
  17127. MA_ZERO_OBJECT(&wf);
  17128. wf.Format.cbSize = sizeof(wf);
  17129. wf.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  17130. wf.Format.nChannels = (WORD)channels;
  17131. wf.dwChannelMask = ma_channel_map_to_channel_mask__win32(defaultChannelMap, channels);
  17132. found = MA_FALSE;
  17133. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  17134. ma_format format = g_maFormatPriorities[iFormat];
  17135. ma_uint32 iSampleRate;
  17136. wf.Format.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  17137. wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
  17138. wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
  17139. wf.Samples.wValidBitsPerSample = /*(format == ma_format_s24_32) ? 24 :*/ wf.Format.wBitsPerSample;
  17140. if (format == ma_format_f32) {
  17141. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  17142. } else {
  17143. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  17144. }
  17145. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iSampleRate) {
  17146. wf.Format.nSamplesPerSec = g_maStandardSampleRatePriorities[iSampleRate];
  17147. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, (WAVEFORMATEX*)&wf, NULL);
  17148. if (SUCCEEDED(hr)) {
  17149. ma_add_native_data_format_to_device_info_from_WAVEFORMATEX((WAVEFORMATEX*)&wf, ma_share_mode_exclusive, pInfo);
  17150. found = MA_TRUE;
  17151. break;
  17152. }
  17153. }
  17154. if (found) {
  17155. break;
  17156. }
  17157. }
  17158. ma_PropVariantClear(pContext, &var);
  17159. if (!found) {
  17160. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to find suitable device format for device info retrieval.");
  17161. }
  17162. }
  17163. } else {
  17164. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to retrieve device format for device info retrieval.");
  17165. }
  17166. ma_IPropertyStore_Release(pProperties);
  17167. } else {
  17168. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "[WASAPI] Failed to open property store for device info retrieval.");
  17169. }
  17170. }
  17171. #else
  17172. {
  17173. (void)pMMDevice; /* Unused. */
  17174. }
  17175. #endif
  17176. return MA_SUCCESS;
  17177. }
  17178. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17179. static ma_EDataFlow ma_device_type_to_EDataFlow(ma_device_type deviceType)
  17180. {
  17181. if (deviceType == ma_device_type_playback) {
  17182. return ma_eRender;
  17183. } else if (deviceType == ma_device_type_capture) {
  17184. return ma_eCapture;
  17185. } else {
  17186. MA_ASSERT(MA_FALSE);
  17187. return ma_eRender; /* Should never hit this. */
  17188. }
  17189. }
  17190. static ma_result ma_context_create_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator** ppDeviceEnumerator)
  17191. {
  17192. HRESULT hr;
  17193. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17194. MA_ASSERT(pContext != NULL);
  17195. MA_ASSERT(ppDeviceEnumerator != NULL);
  17196. *ppDeviceEnumerator = NULL; /* Safety. */
  17197. hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17198. if (FAILED(hr)) {
  17199. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  17200. return ma_result_from_HRESULT(hr);
  17201. }
  17202. *ppDeviceEnumerator = pDeviceEnumerator;
  17203. return MA_SUCCESS;
  17204. }
  17205. static LPWSTR ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(ma_context* pContext, ma_IMMDeviceEnumerator* pDeviceEnumerator, ma_device_type deviceType)
  17206. {
  17207. HRESULT hr;
  17208. ma_IMMDevice* pMMDefaultDevice = NULL;
  17209. LPWSTR pDefaultDeviceID = NULL;
  17210. ma_EDataFlow dataFlow;
  17211. ma_ERole role;
  17212. MA_ASSERT(pContext != NULL);
  17213. MA_ASSERT(pDeviceEnumerator != NULL);
  17214. (void)pContext;
  17215. /* Grab the EDataFlow type from the device type. */
  17216. dataFlow = ma_device_type_to_EDataFlow(deviceType);
  17217. /* The role is always eConsole, but we may make this configurable later. */
  17218. role = ma_eConsole;
  17219. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, dataFlow, role, &pMMDefaultDevice);
  17220. if (FAILED(hr)) {
  17221. return NULL;
  17222. }
  17223. hr = ma_IMMDevice_GetId(pMMDefaultDevice, &pDefaultDeviceID);
  17224. ma_IMMDevice_Release(pMMDefaultDevice);
  17225. pMMDefaultDevice = NULL;
  17226. if (FAILED(hr)) {
  17227. return NULL;
  17228. }
  17229. return pDefaultDeviceID;
  17230. }
  17231. static LPWSTR ma_context_get_default_device_id__wasapi(ma_context* pContext, ma_device_type deviceType) /* Free the returned pointer with ma_CoTaskMemFree() */
  17232. {
  17233. ma_result result;
  17234. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17235. LPWSTR pDefaultDeviceID = NULL;
  17236. MA_ASSERT(pContext != NULL);
  17237. result = ma_context_create_IMMDeviceEnumerator__wasapi(pContext, &pDeviceEnumerator);
  17238. if (result != MA_SUCCESS) {
  17239. return NULL;
  17240. }
  17241. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  17242. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17243. return pDefaultDeviceID;
  17244. }
  17245. static ma_result ma_context_get_MMDevice__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, ma_IMMDevice** ppMMDevice)
  17246. {
  17247. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17248. HRESULT hr;
  17249. MA_ASSERT(pContext != NULL);
  17250. MA_ASSERT(ppMMDevice != NULL);
  17251. hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17252. if (FAILED(hr)) {
  17253. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create IMMDeviceEnumerator.\n");
  17254. return ma_result_from_HRESULT(hr);
  17255. }
  17256. if (pDeviceID == NULL) {
  17257. hr = ma_IMMDeviceEnumerator_GetDefaultAudioEndpoint(pDeviceEnumerator, (deviceType == ma_device_type_capture) ? ma_eCapture : ma_eRender, ma_eConsole, ppMMDevice);
  17258. } else {
  17259. hr = ma_IMMDeviceEnumerator_GetDevice(pDeviceEnumerator, pDeviceID->wasapi, ppMMDevice);
  17260. }
  17261. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17262. if (FAILED(hr)) {
  17263. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to retrieve IMMDevice.\n");
  17264. return ma_result_from_HRESULT(hr);
  17265. }
  17266. return MA_SUCCESS;
  17267. }
  17268. static ma_result ma_context_get_device_id_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, ma_device_id* pDeviceID)
  17269. {
  17270. LPWSTR pDeviceIDString;
  17271. HRESULT hr;
  17272. MA_ASSERT(pDeviceID != NULL);
  17273. hr = ma_IMMDevice_GetId(pMMDevice, &pDeviceIDString);
  17274. if (SUCCEEDED(hr)) {
  17275. size_t idlen = wcslen(pDeviceIDString);
  17276. if (idlen+1 > ma_countof(pDeviceID->wasapi)) {
  17277. ma_CoTaskMemFree(pContext, pDeviceIDString);
  17278. 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. */
  17279. return MA_ERROR;
  17280. }
  17281. MA_COPY_MEMORY(pDeviceID->wasapi, pDeviceIDString, idlen * sizeof(wchar_t));
  17282. pDeviceID->wasapi[idlen] = '\0';
  17283. ma_CoTaskMemFree(pContext, pDeviceIDString);
  17284. return MA_SUCCESS;
  17285. }
  17286. return MA_ERROR;
  17287. }
  17288. static ma_result ma_context_get_device_info_from_MMDevice__wasapi(ma_context* pContext, ma_IMMDevice* pMMDevice, LPWSTR pDefaultDeviceID, ma_bool32 onlySimpleInfo, ma_device_info* pInfo)
  17289. {
  17290. ma_result result;
  17291. HRESULT hr;
  17292. MA_ASSERT(pContext != NULL);
  17293. MA_ASSERT(pMMDevice != NULL);
  17294. MA_ASSERT(pInfo != NULL);
  17295. /* ID. */
  17296. result = ma_context_get_device_id_from_MMDevice__wasapi(pContext, pMMDevice, &pInfo->id);
  17297. if (result == MA_SUCCESS) {
  17298. if (pDefaultDeviceID != NULL) {
  17299. if (wcscmp(pInfo->id.wasapi, pDefaultDeviceID) == 0) {
  17300. pInfo->isDefault = MA_TRUE;
  17301. }
  17302. }
  17303. }
  17304. /* Description / Friendly Name */
  17305. {
  17306. ma_IPropertyStore *pProperties;
  17307. hr = ma_IMMDevice_OpenPropertyStore(pMMDevice, STGM_READ, &pProperties);
  17308. if (SUCCEEDED(hr)) {
  17309. PROPVARIANT var;
  17310. ma_PropVariantInit(&var);
  17311. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &var);
  17312. if (SUCCEEDED(hr)) {
  17313. WideCharToMultiByte(CP_UTF8, 0, var.pwszVal, -1, pInfo->name, sizeof(pInfo->name), 0, FALSE);
  17314. ma_PropVariantClear(pContext, &var);
  17315. }
  17316. ma_IPropertyStore_Release(pProperties);
  17317. }
  17318. }
  17319. /* Format */
  17320. if (!onlySimpleInfo) {
  17321. ma_IAudioClient* pAudioClient;
  17322. hr = ma_IMMDevice_Activate(pMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pAudioClient);
  17323. if (SUCCEEDED(hr)) {
  17324. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, pMMDevice, pAudioClient, pInfo);
  17325. ma_IAudioClient_Release(pAudioClient);
  17326. return result;
  17327. } else {
  17328. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate audio client for device info retrieval.");
  17329. return ma_result_from_HRESULT(hr);
  17330. }
  17331. }
  17332. return MA_SUCCESS;
  17333. }
  17334. 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)
  17335. {
  17336. ma_result result = MA_SUCCESS;
  17337. UINT deviceCount;
  17338. HRESULT hr;
  17339. ma_uint32 iDevice;
  17340. LPWSTR pDefaultDeviceID = NULL;
  17341. ma_IMMDeviceCollection* pDeviceCollection = NULL;
  17342. MA_ASSERT(pContext != NULL);
  17343. MA_ASSERT(callback != NULL);
  17344. /* Grab the default device. We use this to know whether or not flag the returned device info as being the default. */
  17345. pDefaultDeviceID = ma_context_get_default_device_id_from_IMMDeviceEnumerator__wasapi(pContext, pDeviceEnumerator, deviceType);
  17346. /* We need to enumerate the devices which returns a device collection. */
  17347. hr = ma_IMMDeviceEnumerator_EnumAudioEndpoints(pDeviceEnumerator, ma_device_type_to_EDataFlow(deviceType), MA_MM_DEVICE_STATE_ACTIVE, &pDeviceCollection);
  17348. if (SUCCEEDED(hr)) {
  17349. hr = ma_IMMDeviceCollection_GetCount(pDeviceCollection, &deviceCount);
  17350. if (FAILED(hr)) {
  17351. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to get device count.\n");
  17352. result = ma_result_from_HRESULT(hr);
  17353. goto done;
  17354. }
  17355. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  17356. ma_device_info deviceInfo;
  17357. ma_IMMDevice* pMMDevice;
  17358. MA_ZERO_OBJECT(&deviceInfo);
  17359. hr = ma_IMMDeviceCollection_Item(pDeviceCollection, iDevice, &pMMDevice);
  17360. if (SUCCEEDED(hr)) {
  17361. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_TRUE, &deviceInfo); /* MA_TRUE = onlySimpleInfo. */
  17362. ma_IMMDevice_Release(pMMDevice);
  17363. if (result == MA_SUCCESS) {
  17364. ma_bool32 cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  17365. if (cbResult == MA_FALSE) {
  17366. break;
  17367. }
  17368. }
  17369. }
  17370. }
  17371. }
  17372. done:
  17373. if (pDefaultDeviceID != NULL) {
  17374. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  17375. pDefaultDeviceID = NULL;
  17376. }
  17377. if (pDeviceCollection != NULL) {
  17378. ma_IMMDeviceCollection_Release(pDeviceCollection);
  17379. pDeviceCollection = NULL;
  17380. }
  17381. return result;
  17382. }
  17383. static ma_result ma_context_get_IAudioClient_Desktop__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, PROPVARIANT* pActivationParams, ma_IAudioClient** ppAudioClient, ma_IMMDevice** ppMMDevice)
  17384. {
  17385. ma_result result;
  17386. HRESULT hr;
  17387. MA_ASSERT(pContext != NULL);
  17388. MA_ASSERT(ppAudioClient != NULL);
  17389. MA_ASSERT(ppMMDevice != NULL);
  17390. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, ppMMDevice);
  17391. if (result != MA_SUCCESS) {
  17392. return result;
  17393. }
  17394. hr = ma_IMMDevice_Activate(*ppMMDevice, &MA_IID_IAudioClient, CLSCTX_ALL, pActivationParams, (void**)ppAudioClient);
  17395. if (FAILED(hr)) {
  17396. return ma_result_from_HRESULT(hr);
  17397. }
  17398. return MA_SUCCESS;
  17399. }
  17400. #else
  17401. static ma_result ma_context_get_IAudioClient_UWP__wasapi(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, PROPVARIANT* pActivationParams, ma_IAudioClient** ppAudioClient, ma_IUnknown** ppActivatedInterface)
  17402. {
  17403. ma_IActivateAudioInterfaceAsyncOperation *pAsyncOp = NULL;
  17404. ma_completion_handler_uwp completionHandler;
  17405. IID iid;
  17406. LPOLESTR iidStr;
  17407. HRESULT hr;
  17408. ma_result result;
  17409. HRESULT activateResult;
  17410. ma_IUnknown* pActivatedInterface;
  17411. MA_ASSERT(pContext != NULL);
  17412. MA_ASSERT(ppAudioClient != NULL);
  17413. if (pDeviceID != NULL) {
  17414. iidStr = (LPOLESTR)pDeviceID->wasapi;
  17415. } else {
  17416. if (deviceType == ma_device_type_capture) {
  17417. iid = MA_IID_DEVINTERFACE_AUDIO_CAPTURE;
  17418. } else {
  17419. iid = MA_IID_DEVINTERFACE_AUDIO_RENDER;
  17420. }
  17421. #if defined(__cplusplus)
  17422. hr = StringFromIID(iid, &iidStr);
  17423. #else
  17424. hr = StringFromIID(&iid, &iidStr);
  17425. #endif
  17426. if (FAILED(hr)) {
  17427. 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");
  17428. return ma_result_from_HRESULT(hr);
  17429. }
  17430. }
  17431. result = ma_completion_handler_uwp_init(&completionHandler);
  17432. if (result != MA_SUCCESS) {
  17433. ma_CoTaskMemFree(pContext, iidStr);
  17434. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for waiting for ActivateAudioInterfaceAsync().\n");
  17435. return result;
  17436. }
  17437. hr = ((MA_PFN_ActivateAudioInterfaceAsync)pContext->wasapi.ActivateAudioInterfaceAsync)(iidStr, &MA_IID_IAudioClient, pActivationParams, (ma_IActivateAudioInterfaceCompletionHandler*)&completionHandler, (ma_IActivateAudioInterfaceAsyncOperation**)&pAsyncOp);
  17438. if (FAILED(hr)) {
  17439. ma_completion_handler_uwp_uninit(&completionHandler);
  17440. ma_CoTaskMemFree(pContext, iidStr);
  17441. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] ActivateAudioInterfaceAsync() failed.\n");
  17442. return ma_result_from_HRESULT(hr);
  17443. }
  17444. if (pDeviceID == NULL) {
  17445. ma_CoTaskMemFree(pContext, iidStr);
  17446. }
  17447. /* Wait for the async operation for finish. */
  17448. ma_completion_handler_uwp_wait(&completionHandler);
  17449. ma_completion_handler_uwp_uninit(&completionHandler);
  17450. hr = ma_IActivateAudioInterfaceAsyncOperation_GetActivateResult(pAsyncOp, &activateResult, &pActivatedInterface);
  17451. ma_IActivateAudioInterfaceAsyncOperation_Release(pAsyncOp);
  17452. if (FAILED(hr) || FAILED(activateResult)) {
  17453. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to activate device.\n");
  17454. return FAILED(hr) ? ma_result_from_HRESULT(hr) : ma_result_from_HRESULT(activateResult);
  17455. }
  17456. /* Here is where we grab the IAudioClient interface. */
  17457. hr = ma_IUnknown_QueryInterface(pActivatedInterface, &MA_IID_IAudioClient, (void**)ppAudioClient);
  17458. if (FAILED(hr)) {
  17459. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to query IAudioClient interface.\n");
  17460. return ma_result_from_HRESULT(hr);
  17461. }
  17462. if (ppActivatedInterface) {
  17463. *ppActivatedInterface = pActivatedInterface;
  17464. } else {
  17465. ma_IUnknown_Release(pActivatedInterface);
  17466. }
  17467. return MA_SUCCESS;
  17468. }
  17469. #endif
  17470. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-audioclient_activation_type */
  17471. typedef enum
  17472. {
  17473. MA_AUDIOCLIENT_ACTIVATION_TYPE_DEFAULT,
  17474. MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK
  17475. } MA_AUDIOCLIENT_ACTIVATION_TYPE;
  17476. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ne-audioclientactivationparams-process_loopback_mode */
  17477. typedef enum
  17478. {
  17479. MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE,
  17480. MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE
  17481. } MA_PROCESS_LOOPBACK_MODE;
  17482. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params */
  17483. typedef struct
  17484. {
  17485. DWORD TargetProcessId;
  17486. MA_PROCESS_LOOPBACK_MODE ProcessLoopbackMode;
  17487. } MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS;
  17488. #if defined(_MSC_VER) && !defined(__clang__)
  17489. #pragma warning(push)
  17490. #pragma warning(disable:4201) /* nonstandard extension used: nameless struct/union */
  17491. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  17492. #pragma GCC diagnostic push
  17493. #pragma GCC diagnostic ignored "-Wpedantic" /* For ISO C99 doesn't support unnamed structs/unions [-Wpedantic] */
  17494. #if defined(__clang__)
  17495. #pragma GCC diagnostic ignored "-Wc11-extensions" /* anonymous unions are a C11 extension */
  17496. #endif
  17497. #endif
  17498. /* https://docs.microsoft.com/en-us/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_activation_params */
  17499. typedef struct
  17500. {
  17501. MA_AUDIOCLIENT_ACTIVATION_TYPE ActivationType;
  17502. union
  17503. {
  17504. MA_AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS ProcessLoopbackParams;
  17505. };
  17506. } MA_AUDIOCLIENT_ACTIVATION_PARAMS;
  17507. #if defined(_MSC_VER) && !defined(__clang__)
  17508. #pragma warning(pop)
  17509. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)))
  17510. #pragma GCC diagnostic pop
  17511. #endif
  17512. #define MA_VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK L"VAD\\Process_Loopback"
  17513. 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)
  17514. {
  17515. ma_result result;
  17516. ma_bool32 usingProcessLoopback = MA_FALSE;
  17517. MA_AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams;
  17518. PROPVARIANT activationParams;
  17519. PROPVARIANT* pActivationParams = NULL;
  17520. ma_device_id virtualDeviceID;
  17521. /* Activation parameters specific to loopback mode. Note that process-specific loopback will only work when a default device ID is specified. */
  17522. if (deviceType == ma_device_type_loopback && loopbackProcessID != 0 && pDeviceID == NULL) {
  17523. usingProcessLoopback = MA_TRUE;
  17524. }
  17525. if (usingProcessLoopback) {
  17526. MA_ZERO_OBJECT(&audioclientActivationParams);
  17527. audioclientActivationParams.ActivationType = MA_AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK;
  17528. audioclientActivationParams.ProcessLoopbackParams.ProcessLoopbackMode = (loopbackProcessExclude) ? MA_PROCESS_LOOPBACK_MODE_EXCLUDE_TARGET_PROCESS_TREE : MA_PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE;
  17529. audioclientActivationParams.ProcessLoopbackParams.TargetProcessId = (DWORD)loopbackProcessID;
  17530. ma_PropVariantInit(&activationParams);
  17531. activationParams.vt = VT_BLOB;
  17532. activationParams.blob.cbSize = sizeof(audioclientActivationParams);
  17533. activationParams.blob.pBlobData = (BYTE*)&audioclientActivationParams;
  17534. pActivationParams = &activationParams;
  17535. /* When requesting a specific device ID we need to use a special device ID. */
  17536. 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. */
  17537. pDeviceID = &virtualDeviceID;
  17538. } else {
  17539. pActivationParams = NULL; /* No activation parameters required. */
  17540. }
  17541. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17542. result = ma_context_get_IAudioClient_Desktop__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  17543. #else
  17544. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, pActivationParams, ppAudioClient, ppDeviceInterface);
  17545. #endif
  17546. /*
  17547. If loopback mode was requested with a process ID and initialization failed, it could be because it's
  17548. trying to run on an older version of Windows where it's not supported. We need to let the caller
  17549. know about this with a log message.
  17550. */
  17551. if (result != MA_SUCCESS) {
  17552. if (usingProcessLoopback) {
  17553. 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);
  17554. }
  17555. }
  17556. return result;
  17557. }
  17558. static ma_result ma_context_enumerate_devices__wasapi(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  17559. {
  17560. /* Different enumeration for desktop and UWP. */
  17561. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17562. /* Desktop */
  17563. HRESULT hr;
  17564. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  17565. hr = ma_CoCreateInstance(pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  17566. if (FAILED(hr)) {
  17567. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  17568. return ma_result_from_HRESULT(hr);
  17569. }
  17570. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_playback, callback, pUserData);
  17571. ma_context_enumerate_devices_by_type__wasapi(pContext, pDeviceEnumerator, ma_device_type_capture, callback, pUserData);
  17572. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  17573. #else
  17574. /*
  17575. UWP
  17576. The MMDevice API is only supported on desktop applications. For now, while I'm still figuring out how to properly enumerate
  17577. over devices without using MMDevice, I'm restricting devices to defaults.
  17578. 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/
  17579. */
  17580. if (callback) {
  17581. ma_bool32 cbResult = MA_TRUE;
  17582. /* Playback. */
  17583. if (cbResult) {
  17584. ma_device_info deviceInfo;
  17585. MA_ZERO_OBJECT(&deviceInfo);
  17586. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  17587. deviceInfo.isDefault = MA_TRUE;
  17588. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  17589. }
  17590. /* Capture. */
  17591. if (cbResult) {
  17592. ma_device_info deviceInfo;
  17593. MA_ZERO_OBJECT(&deviceInfo);
  17594. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  17595. deviceInfo.isDefault = MA_TRUE;
  17596. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  17597. }
  17598. }
  17599. #endif
  17600. return MA_SUCCESS;
  17601. }
  17602. 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)
  17603. {
  17604. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17605. ma_result result;
  17606. ma_IMMDevice* pMMDevice = NULL;
  17607. LPWSTR pDefaultDeviceID = NULL;
  17608. result = ma_context_get_MMDevice__wasapi(pContext, deviceType, pDeviceID, &pMMDevice);
  17609. if (result != MA_SUCCESS) {
  17610. return result;
  17611. }
  17612. /* We need the default device ID so we can set the isDefault flag in the device info. */
  17613. pDefaultDeviceID = ma_context_get_default_device_id__wasapi(pContext, deviceType);
  17614. result = ma_context_get_device_info_from_MMDevice__wasapi(pContext, pMMDevice, pDefaultDeviceID, MA_FALSE, pDeviceInfo); /* MA_FALSE = !onlySimpleInfo. */
  17615. if (pDefaultDeviceID != NULL) {
  17616. ma_CoTaskMemFree(pContext, pDefaultDeviceID);
  17617. pDefaultDeviceID = NULL;
  17618. }
  17619. ma_IMMDevice_Release(pMMDevice);
  17620. return result;
  17621. #else
  17622. ma_IAudioClient* pAudioClient;
  17623. ma_result result;
  17624. /* UWP currently only uses default devices. */
  17625. if (deviceType == ma_device_type_playback) {
  17626. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  17627. } else {
  17628. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  17629. }
  17630. result = ma_context_get_IAudioClient_UWP__wasapi(pContext, deviceType, pDeviceID, NULL, &pAudioClient, NULL);
  17631. if (result != MA_SUCCESS) {
  17632. return result;
  17633. }
  17634. result = ma_context_get_device_info_from_IAudioClient__wasapi(pContext, NULL, pAudioClient, pDeviceInfo);
  17635. pDeviceInfo->isDefault = MA_TRUE; /* UWP only supports default devices. */
  17636. ma_IAudioClient_Release(pAudioClient);
  17637. return result;
  17638. #endif
  17639. }
  17640. static ma_result ma_device_uninit__wasapi(ma_device* pDevice)
  17641. {
  17642. MA_ASSERT(pDevice != NULL);
  17643. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17644. if (pDevice->wasapi.pDeviceEnumerator) {
  17645. ((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator)->lpVtbl->UnregisterEndpointNotificationCallback((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  17646. ma_IMMDeviceEnumerator_Release((ma_IMMDeviceEnumerator*)pDevice->wasapi.pDeviceEnumerator);
  17647. }
  17648. #endif
  17649. if (pDevice->wasapi.pRenderClient) {
  17650. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  17651. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  17652. pDevice->wasapi.pMappedBufferPlayback = NULL;
  17653. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  17654. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  17655. }
  17656. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  17657. }
  17658. if (pDevice->wasapi.pCaptureClient) {
  17659. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  17660. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  17661. pDevice->wasapi.pMappedBufferCapture = NULL;
  17662. pDevice->wasapi.mappedBufferCaptureCap = 0;
  17663. pDevice->wasapi.mappedBufferCaptureLen = 0;
  17664. }
  17665. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  17666. }
  17667. if (pDevice->wasapi.pAudioClientPlayback) {
  17668. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  17669. }
  17670. if (pDevice->wasapi.pAudioClientCapture) {
  17671. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  17672. }
  17673. if (pDevice->wasapi.hEventPlayback) {
  17674. CloseHandle(pDevice->wasapi.hEventPlayback);
  17675. }
  17676. if (pDevice->wasapi.hEventCapture) {
  17677. CloseHandle(pDevice->wasapi.hEventCapture);
  17678. }
  17679. return MA_SUCCESS;
  17680. }
  17681. typedef struct
  17682. {
  17683. /* Input. */
  17684. ma_format formatIn;
  17685. ma_uint32 channelsIn;
  17686. ma_uint32 sampleRateIn;
  17687. ma_channel channelMapIn[MA_MAX_CHANNELS];
  17688. ma_uint32 periodSizeInFramesIn;
  17689. ma_uint32 periodSizeInMillisecondsIn;
  17690. ma_uint32 periodsIn;
  17691. ma_share_mode shareMode;
  17692. ma_performance_profile performanceProfile;
  17693. ma_bool32 noAutoConvertSRC;
  17694. ma_bool32 noDefaultQualitySRC;
  17695. ma_bool32 noHardwareOffloading;
  17696. ma_uint32 loopbackProcessID;
  17697. ma_bool32 loopbackProcessExclude;
  17698. /* Output. */
  17699. ma_IAudioClient* pAudioClient;
  17700. ma_IAudioRenderClient* pRenderClient;
  17701. ma_IAudioCaptureClient* pCaptureClient;
  17702. ma_format formatOut;
  17703. ma_uint32 channelsOut;
  17704. ma_uint32 sampleRateOut;
  17705. ma_channel channelMapOut[MA_MAX_CHANNELS];
  17706. ma_uint32 periodSizeInFramesOut;
  17707. ma_uint32 periodsOut;
  17708. ma_bool32 usingAudioClient3;
  17709. char deviceName[256];
  17710. ma_device_id id;
  17711. } ma_device_init_internal_data__wasapi;
  17712. 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)
  17713. {
  17714. HRESULT hr;
  17715. ma_result result = MA_SUCCESS;
  17716. const char* errorMsg = "";
  17717. MA_AUDCLNT_SHAREMODE shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  17718. DWORD streamFlags = 0;
  17719. MA_REFERENCE_TIME periodDurationInMicroseconds;
  17720. ma_bool32 wasInitializedUsingIAudioClient3 = MA_FALSE;
  17721. WAVEFORMATEXTENSIBLE wf;
  17722. ma_WASAPIDeviceInterface* pDeviceInterface = NULL;
  17723. ma_IAudioClient2* pAudioClient2;
  17724. ma_uint32 nativeSampleRate;
  17725. MA_ASSERT(pContext != NULL);
  17726. MA_ASSERT(pData != NULL);
  17727. /* This function is only used to initialize one device type: either playback, capture or loopback. Never full-duplex. */
  17728. if (deviceType == ma_device_type_duplex) {
  17729. return MA_INVALID_ARGS;
  17730. }
  17731. pData->pAudioClient = NULL;
  17732. pData->pRenderClient = NULL;
  17733. pData->pCaptureClient = NULL;
  17734. streamFlags = MA_AUDCLNT_STREAMFLAGS_EVENTCALLBACK;
  17735. if (!pData->noAutoConvertSRC && pData->sampleRateIn != 0 && pData->shareMode != ma_share_mode_exclusive) { /* <-- Exclusive streams must use the native sample rate. */
  17736. streamFlags |= MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
  17737. }
  17738. if (!pData->noDefaultQualitySRC && pData->sampleRateIn != 0 && (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) != 0) {
  17739. streamFlags |= MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
  17740. }
  17741. if (deviceType == ma_device_type_loopback) {
  17742. streamFlags |= MA_AUDCLNT_STREAMFLAGS_LOOPBACK;
  17743. }
  17744. result = ma_context_get_IAudioClient__wasapi(pContext, deviceType, pDeviceID, pData->loopbackProcessID, pData->loopbackProcessExclude, &pData->pAudioClient, &pDeviceInterface);
  17745. if (result != MA_SUCCESS) {
  17746. goto done;
  17747. }
  17748. MA_ZERO_OBJECT(&wf);
  17749. /* Try enabling hardware offloading. */
  17750. if (!pData->noHardwareOffloading) {
  17751. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient2, (void**)&pAudioClient2);
  17752. if (SUCCEEDED(hr)) {
  17753. BOOL isHardwareOffloadingSupported = 0;
  17754. hr = ma_IAudioClient2_IsOffloadCapable(pAudioClient2, MA_AudioCategory_Other, &isHardwareOffloadingSupported);
  17755. if (SUCCEEDED(hr) && isHardwareOffloadingSupported) {
  17756. ma_AudioClientProperties clientProperties;
  17757. MA_ZERO_OBJECT(&clientProperties);
  17758. clientProperties.cbSize = sizeof(clientProperties);
  17759. clientProperties.bIsOffload = 1;
  17760. clientProperties.eCategory = MA_AudioCategory_Other;
  17761. ma_IAudioClient2_SetClientProperties(pAudioClient2, &clientProperties);
  17762. }
  17763. pAudioClient2->lpVtbl->Release(pAudioClient2);
  17764. }
  17765. }
  17766. /* 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. */
  17767. result = MA_FORMAT_NOT_SUPPORTED;
  17768. if (pData->shareMode == ma_share_mode_exclusive) {
  17769. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17770. /* In exclusive mode on desktop we always use the backend's native format. */
  17771. ma_IPropertyStore* pStore = NULL;
  17772. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pStore);
  17773. if (SUCCEEDED(hr)) {
  17774. PROPVARIANT prop;
  17775. ma_PropVariantInit(&prop);
  17776. hr = ma_IPropertyStore_GetValue(pStore, &MA_PKEY_AudioEngine_DeviceFormat, &prop);
  17777. if (SUCCEEDED(hr)) {
  17778. WAVEFORMATEX* pActualFormat = (WAVEFORMATEX*)prop.blob.pBlobData;
  17779. hr = ma_IAudioClient_IsFormatSupported((ma_IAudioClient*)pData->pAudioClient, MA_AUDCLNT_SHAREMODE_EXCLUSIVE, pActualFormat, NULL);
  17780. if (SUCCEEDED(hr)) {
  17781. MA_COPY_MEMORY(&wf, pActualFormat, sizeof(WAVEFORMATEXTENSIBLE));
  17782. }
  17783. ma_PropVariantClear(pContext, &prop);
  17784. }
  17785. ma_IPropertyStore_Release(pStore);
  17786. }
  17787. #else
  17788. /*
  17789. I do not know how to query the device's native format on UWP so for now I'm just disabling support for
  17790. exclusive mode. The alternative is to enumerate over different formats and check IsFormatSupported()
  17791. until you find one that works.
  17792. TODO: Add support for exclusive mode to UWP.
  17793. */
  17794. hr = S_FALSE;
  17795. #endif
  17796. if (hr == S_OK) {
  17797. shareMode = MA_AUDCLNT_SHAREMODE_EXCLUSIVE;
  17798. result = MA_SUCCESS;
  17799. } else {
  17800. result = MA_SHARE_MODE_NOT_SUPPORTED;
  17801. }
  17802. } else {
  17803. /* In shared mode we are always using the format reported by the operating system. */
  17804. WAVEFORMATEXTENSIBLE* pNativeFormat = NULL;
  17805. hr = ma_IAudioClient_GetMixFormat((ma_IAudioClient*)pData->pAudioClient, (WAVEFORMATEX**)&pNativeFormat);
  17806. if (hr != S_OK) {
  17807. result = MA_FORMAT_NOT_SUPPORTED;
  17808. } else {
  17809. MA_COPY_MEMORY(&wf, pNativeFormat, sizeof(wf));
  17810. result = MA_SUCCESS;
  17811. }
  17812. ma_CoTaskMemFree(pContext, pNativeFormat);
  17813. shareMode = MA_AUDCLNT_SHAREMODE_SHARED;
  17814. }
  17815. /* Return an error if we still haven't found a format. */
  17816. if (result != MA_SUCCESS) {
  17817. errorMsg = "[WASAPI] Failed to find best device mix format.";
  17818. goto done;
  17819. }
  17820. /*
  17821. 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
  17822. WASAPI to perform the sample rate conversion.
  17823. */
  17824. nativeSampleRate = wf.Format.nSamplesPerSec;
  17825. if (streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) {
  17826. wf.Format.nSamplesPerSec = (pData->sampleRateIn != 0) ? pData->sampleRateIn : MA_DEFAULT_SAMPLE_RATE;
  17827. wf.Format.nAvgBytesPerSec = wf.Format.nSamplesPerSec * wf.Format.nBlockAlign;
  17828. }
  17829. pData->formatOut = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)&wf);
  17830. if (pData->formatOut == ma_format_unknown) {
  17831. /*
  17832. 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
  17833. 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
  17834. completeness we'll check for it and return MA_FORMAT_NOT_SUPPORTED.
  17835. */
  17836. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  17837. result = MA_SHARE_MODE_NOT_SUPPORTED;
  17838. } else {
  17839. result = MA_FORMAT_NOT_SUPPORTED;
  17840. }
  17841. errorMsg = "[WASAPI] Native format not supported.";
  17842. goto done;
  17843. }
  17844. pData->channelsOut = wf.Format.nChannels;
  17845. pData->sampleRateOut = wf.Format.nSamplesPerSec;
  17846. /* Get the internal channel map based on the channel mask. */
  17847. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pData->channelsOut, pData->channelMapOut);
  17848. /* Period size. */
  17849. pData->periodsOut = (pData->periodsIn != 0) ? pData->periodsIn : MA_DEFAULT_PERIODS;
  17850. pData->periodSizeInFramesOut = pData->periodSizeInFramesIn;
  17851. if (pData->periodSizeInFramesOut == 0) {
  17852. if (pData->periodSizeInMillisecondsIn == 0) {
  17853. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  17854. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, wf.Format.nSamplesPerSec);
  17855. } else {
  17856. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, wf.Format.nSamplesPerSec);
  17857. }
  17858. } else {
  17859. pData->periodSizeInFramesOut = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, wf.Format.nSamplesPerSec);
  17860. }
  17861. }
  17862. periodDurationInMicroseconds = ((ma_uint64)pData->periodSizeInFramesOut * 1000 * 1000) / wf.Format.nSamplesPerSec;
  17863. /* Slightly different initialization for shared and exclusive modes. We try exclusive mode first, and if it fails, fall back to shared mode. */
  17864. if (shareMode == MA_AUDCLNT_SHAREMODE_EXCLUSIVE) {
  17865. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10;
  17866. /*
  17867. If the periodicy is too small, Initialize() will fail with AUDCLNT_E_INVALID_DEVICE_PERIOD. In this case we should just keep increasing
  17868. it and trying it again.
  17869. */
  17870. hr = E_FAIL;
  17871. for (;;) {
  17872. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL);
  17873. if (hr == MA_AUDCLNT_E_INVALID_DEVICE_PERIOD) {
  17874. if (bufferDuration > 500*10000) {
  17875. break;
  17876. } else {
  17877. if (bufferDuration == 0) { /* <-- Just a sanity check to prevent an infinit loop. Should never happen, but it makes me feel better. */
  17878. break;
  17879. }
  17880. bufferDuration = bufferDuration * 2;
  17881. continue;
  17882. }
  17883. } else {
  17884. break;
  17885. }
  17886. }
  17887. if (hr == MA_AUDCLNT_E_BUFFER_SIZE_NOT_ALIGNED) {
  17888. ma_uint32 bufferSizeInFrames;
  17889. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  17890. if (SUCCEEDED(hr)) {
  17891. bufferDuration = (MA_REFERENCE_TIME)((10000.0 * 1000 / wf.Format.nSamplesPerSec * bufferSizeInFrames) + 0.5);
  17892. /* Unfortunately we need to release and re-acquire the audio client according to MSDN. Seems silly - why not just call IAudioClient_Initialize() again?! */
  17893. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  17894. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  17895. hr = ma_IMMDevice_Activate(pDeviceInterface, &MA_IID_IAudioClient, CLSCTX_ALL, NULL, (void**)&pData->pAudioClient);
  17896. #else
  17897. hr = ma_IUnknown_QueryInterface(pDeviceInterface, &MA_IID_IAudioClient, (void**)&pData->pAudioClient);
  17898. #endif
  17899. if (SUCCEEDED(hr)) {
  17900. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, bufferDuration, (WAVEFORMATEX*)&wf, NULL);
  17901. }
  17902. }
  17903. }
  17904. if (FAILED(hr)) {
  17905. /* 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. */
  17906. if (hr == E_ACCESSDENIED) {
  17907. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Access denied.", result = MA_ACCESS_DENIED;
  17908. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  17909. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode. Device in use.", result = MA_BUSY;
  17910. } else {
  17911. errorMsg = "[WASAPI] Failed to initialize device in exclusive mode."; result = ma_result_from_HRESULT(hr);
  17912. }
  17913. goto done;
  17914. }
  17915. }
  17916. if (shareMode == MA_AUDCLNT_SHAREMODE_SHARED) {
  17917. /*
  17918. Low latency shared mode via IAudioClient3.
  17919. NOTE
  17920. ====
  17921. Contrary to the documentation on MSDN (https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nf-audioclient-iaudioclient3-initializesharedaudiostream), the
  17922. use of AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM and AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY with IAudioClient3_InitializeSharedAudioStream() absolutely does not work. Using
  17923. any of these flags will result in HRESULT code 0x88890021. The other problem is that calling IAudioClient3_GetSharedModeEnginePeriod() with a sample rate different to
  17924. that returned by IAudioClient_GetMixFormat() also results in an error. I'm therefore disabling low-latency shared mode with AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM.
  17925. */
  17926. #ifndef MA_WASAPI_NO_LOW_LATENCY_SHARED_MODE
  17927. {
  17928. if ((streamFlags & MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM) == 0 || nativeSampleRate == wf.Format.nSamplesPerSec) {
  17929. ma_IAudioClient3* pAudioClient3 = NULL;
  17930. hr = ma_IAudioClient_QueryInterface(pData->pAudioClient, &MA_IID_IAudioClient3, (void**)&pAudioClient3);
  17931. if (SUCCEEDED(hr)) {
  17932. ma_uint32 defaultPeriodInFrames;
  17933. ma_uint32 fundamentalPeriodInFrames;
  17934. ma_uint32 minPeriodInFrames;
  17935. ma_uint32 maxPeriodInFrames;
  17936. hr = ma_IAudioClient3_GetSharedModeEnginePeriod(pAudioClient3, (WAVEFORMATEX*)&wf, &defaultPeriodInFrames, &fundamentalPeriodInFrames, &minPeriodInFrames, &maxPeriodInFrames);
  17937. if (SUCCEEDED(hr)) {
  17938. ma_uint32 desiredPeriodInFrames = pData->periodSizeInFramesOut;
  17939. ma_uint32 actualPeriodInFrames = desiredPeriodInFrames;
  17940. /* Make sure the period size is a multiple of fundamentalPeriodInFrames. */
  17941. actualPeriodInFrames = actualPeriodInFrames / fundamentalPeriodInFrames;
  17942. actualPeriodInFrames = actualPeriodInFrames * fundamentalPeriodInFrames;
  17943. /* The period needs to be clamped between minPeriodInFrames and maxPeriodInFrames. */
  17944. actualPeriodInFrames = ma_clamp(actualPeriodInFrames, minPeriodInFrames, maxPeriodInFrames);
  17945. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Trying IAudioClient3_InitializeSharedAudioStream(actualPeriodInFrames=%d)\n", actualPeriodInFrames);
  17946. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " defaultPeriodInFrames=%d\n", defaultPeriodInFrames);
  17947. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " fundamentalPeriodInFrames=%d\n", fundamentalPeriodInFrames);
  17948. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " minPeriodInFrames=%d\n", minPeriodInFrames);
  17949. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " maxPeriodInFrames=%d\n", maxPeriodInFrames);
  17950. /* If the client requested a largish buffer than we don't actually want to use low latency shared mode because it forces small buffers. */
  17951. if (actualPeriodInFrames >= desiredPeriodInFrames) {
  17952. /*
  17953. MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY must not be in the stream flags. If either of these are specified,
  17954. IAudioClient3_InitializeSharedAudioStream() will fail.
  17955. */
  17956. hr = ma_IAudioClient3_InitializeSharedAudioStream(pAudioClient3, streamFlags & ~(MA_AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM | MA_AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY), actualPeriodInFrames, (WAVEFORMATEX*)&wf, NULL);
  17957. if (SUCCEEDED(hr)) {
  17958. wasInitializedUsingIAudioClient3 = MA_TRUE;
  17959. pData->periodSizeInFramesOut = actualPeriodInFrames;
  17960. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] Using IAudioClient3\n");
  17961. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " periodSizeInFramesOut=%d\n", pData->periodSizeInFramesOut);
  17962. } else {
  17963. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_InitializeSharedAudioStream failed. Falling back to IAudioClient.\n");
  17964. }
  17965. } else {
  17966. 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");
  17967. }
  17968. } else {
  17969. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[WASAPI] IAudioClient3_GetSharedModeEnginePeriod failed. Falling back to IAudioClient.\n");
  17970. }
  17971. ma_IAudioClient3_Release(pAudioClient3);
  17972. pAudioClient3 = NULL;
  17973. }
  17974. }
  17975. }
  17976. #else
  17977. {
  17978. 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");
  17979. }
  17980. #endif
  17981. /* If we don't have an IAudioClient3 then we need to use the normal initialization routine. */
  17982. if (!wasInitializedUsingIAudioClient3) {
  17983. MA_REFERENCE_TIME bufferDuration = periodDurationInMicroseconds * pData->periodsOut * 10; /* <-- Multiply by 10 for microseconds to 100-nanoseconds. */
  17984. hr = ma_IAudioClient_Initialize((ma_IAudioClient*)pData->pAudioClient, shareMode, streamFlags, bufferDuration, 0, (WAVEFORMATEX*)&wf, NULL);
  17985. if (FAILED(hr)) {
  17986. if (hr == E_ACCESSDENIED) {
  17987. errorMsg = "[WASAPI] Failed to initialize device. Access denied.", result = MA_ACCESS_DENIED;
  17988. } else if (hr == MA_AUDCLNT_E_DEVICE_IN_USE) {
  17989. errorMsg = "[WASAPI] Failed to initialize device. Device in use.", result = MA_BUSY;
  17990. } else {
  17991. errorMsg = "[WASAPI] Failed to initialize device.", result = ma_result_from_HRESULT(hr);
  17992. }
  17993. goto done;
  17994. }
  17995. }
  17996. }
  17997. if (!wasInitializedUsingIAudioClient3) {
  17998. ma_uint32 bufferSizeInFrames;
  17999. hr = ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pData->pAudioClient, &bufferSizeInFrames);
  18000. if (FAILED(hr)) {
  18001. errorMsg = "[WASAPI] Failed to get audio client's actual buffer size.", result = ma_result_from_HRESULT(hr);
  18002. goto done;
  18003. }
  18004. pData->periodSizeInFramesOut = bufferSizeInFrames / pData->periodsOut;
  18005. }
  18006. pData->usingAudioClient3 = wasInitializedUsingIAudioClient3;
  18007. if (deviceType == ma_device_type_playback) {
  18008. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pRenderClient);
  18009. } else {
  18010. result = ma_device_create_IAudioClient_service__wasapi(pContext, deviceType, (ma_IAudioClient*)pData->pAudioClient, (void**)&pData->pCaptureClient);
  18011. }
  18012. /*if (FAILED(hr)) {*/
  18013. if (result != MA_SUCCESS) {
  18014. errorMsg = "[WASAPI] Failed to get audio client service.";
  18015. goto done;
  18016. }
  18017. /* Grab the name of the device. */
  18018. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18019. {
  18020. ma_IPropertyStore *pProperties;
  18021. hr = ma_IMMDevice_OpenPropertyStore(pDeviceInterface, STGM_READ, &pProperties);
  18022. if (SUCCEEDED(hr)) {
  18023. PROPVARIANT varName;
  18024. ma_PropVariantInit(&varName);
  18025. hr = ma_IPropertyStore_GetValue(pProperties, &MA_PKEY_Device_FriendlyName, &varName);
  18026. if (SUCCEEDED(hr)) {
  18027. WideCharToMultiByte(CP_UTF8, 0, varName.pwszVal, -1, pData->deviceName, sizeof(pData->deviceName), 0, FALSE);
  18028. ma_PropVariantClear(pContext, &varName);
  18029. }
  18030. ma_IPropertyStore_Release(pProperties);
  18031. }
  18032. }
  18033. #endif
  18034. /*
  18035. For the WASAPI backend we need to know the actual IDs of the device in order to do automatic
  18036. stream routing so that IDs can be compared and we can determine which device has been detached
  18037. and whether or not it matches with our ma_device.
  18038. */
  18039. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18040. {
  18041. /* Desktop */
  18042. ma_context_get_device_id_from_MMDevice__wasapi(pContext, pDeviceInterface, &pData->id);
  18043. }
  18044. #else
  18045. {
  18046. /* UWP */
  18047. /* TODO: Implement me. Need to figure out how to get the ID of the default device. */
  18048. }
  18049. #endif
  18050. done:
  18051. /* Clean up. */
  18052. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18053. if (pDeviceInterface != NULL) {
  18054. ma_IMMDevice_Release(pDeviceInterface);
  18055. }
  18056. #else
  18057. if (pDeviceInterface != NULL) {
  18058. ma_IUnknown_Release(pDeviceInterface);
  18059. }
  18060. #endif
  18061. if (result != MA_SUCCESS) {
  18062. if (pData->pRenderClient) {
  18063. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pData->pRenderClient);
  18064. pData->pRenderClient = NULL;
  18065. }
  18066. if (pData->pCaptureClient) {
  18067. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pData->pCaptureClient);
  18068. pData->pCaptureClient = NULL;
  18069. }
  18070. if (pData->pAudioClient) {
  18071. ma_IAudioClient_Release((ma_IAudioClient*)pData->pAudioClient);
  18072. pData->pAudioClient = NULL;
  18073. }
  18074. if (errorMsg != NULL && errorMsg[0] != '\0') {
  18075. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "%s\n", errorMsg);
  18076. }
  18077. return result;
  18078. } else {
  18079. return MA_SUCCESS;
  18080. }
  18081. }
  18082. static ma_result ma_device_reinit__wasapi(ma_device* pDevice, ma_device_type deviceType)
  18083. {
  18084. ma_device_init_internal_data__wasapi data;
  18085. ma_result result;
  18086. MA_ASSERT(pDevice != NULL);
  18087. /* We only re-initialize the playback or capture device. Never a full-duplex device. */
  18088. if (deviceType == ma_device_type_duplex) {
  18089. return MA_INVALID_ARGS;
  18090. }
  18091. /*
  18092. Before reinitializing the device we need to free the previous audio clients.
  18093. There's a known memory leak here. We will be calling this from the routing change callback that
  18094. is fired by WASAPI. If we attempt to release the IAudioClient we will deadlock. In my opinion
  18095. this is a bug. I'm not sure what I need to do to handle this cleanly, but I think we'll probably
  18096. need some system where we post an event, but delay the execution of it until the callback has
  18097. returned. I'm not sure how to do this reliably, however. I have set up some infrastructure for
  18098. a command thread which might be useful for this.
  18099. */
  18100. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18101. if (pDevice->wasapi.pCaptureClient) {
  18102. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18103. pDevice->wasapi.pCaptureClient = NULL;
  18104. }
  18105. if (pDevice->wasapi.pAudioClientCapture) {
  18106. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_capture);*/
  18107. pDevice->wasapi.pAudioClientCapture = NULL;
  18108. }
  18109. }
  18110. if (deviceType == ma_device_type_playback) {
  18111. if (pDevice->wasapi.pRenderClient) {
  18112. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18113. pDevice->wasapi.pRenderClient = NULL;
  18114. }
  18115. if (pDevice->wasapi.pAudioClientPlayback) {
  18116. /*ma_device_release_IAudioClient_service__wasapi(pDevice, ma_device_type_playback);*/
  18117. pDevice->wasapi.pAudioClientPlayback = NULL;
  18118. }
  18119. }
  18120. if (deviceType == ma_device_type_playback) {
  18121. data.formatIn = pDevice->playback.format;
  18122. data.channelsIn = pDevice->playback.channels;
  18123. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  18124. data.shareMode = pDevice->playback.shareMode;
  18125. } else {
  18126. data.formatIn = pDevice->capture.format;
  18127. data.channelsIn = pDevice->capture.channels;
  18128. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  18129. data.shareMode = pDevice->capture.shareMode;
  18130. }
  18131. data.sampleRateIn = pDevice->sampleRate;
  18132. data.periodSizeInFramesIn = pDevice->wasapi.originalPeriodSizeInFrames;
  18133. data.periodSizeInMillisecondsIn = pDevice->wasapi.originalPeriodSizeInMilliseconds;
  18134. data.periodsIn = pDevice->wasapi.originalPeriods;
  18135. data.performanceProfile = pDevice->wasapi.originalPerformanceProfile;
  18136. data.noAutoConvertSRC = pDevice->wasapi.noAutoConvertSRC;
  18137. data.noDefaultQualitySRC = pDevice->wasapi.noDefaultQualitySRC;
  18138. data.noHardwareOffloading = pDevice->wasapi.noHardwareOffloading;
  18139. data.loopbackProcessID = pDevice->wasapi.loopbackProcessID;
  18140. data.loopbackProcessExclude = pDevice->wasapi.loopbackProcessExclude;
  18141. result = ma_device_init_internal__wasapi(pDevice->pContext, deviceType, NULL, &data);
  18142. if (result != MA_SUCCESS) {
  18143. return result;
  18144. }
  18145. /* At this point we have some new objects ready to go. We need to uninitialize the previous ones and then set the new ones. */
  18146. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_loopback) {
  18147. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  18148. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  18149. pDevice->capture.internalFormat = data.formatOut;
  18150. pDevice->capture.internalChannels = data.channelsOut;
  18151. pDevice->capture.internalSampleRate = data.sampleRateOut;
  18152. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18153. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18154. pDevice->capture.internalPeriods = data.periodsOut;
  18155. ma_strcpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), data.deviceName);
  18156. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture);
  18157. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  18158. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  18159. /* We must always have a valid ID. */
  18160. ma_wcscpy_s(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  18161. }
  18162. if (deviceType == ma_device_type_playback) {
  18163. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  18164. pDevice->wasapi.pRenderClient = data.pRenderClient;
  18165. pDevice->playback.internalFormat = data.formatOut;
  18166. pDevice->playback.internalChannels = data.channelsOut;
  18167. pDevice->playback.internalSampleRate = data.sampleRateOut;
  18168. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18169. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  18170. pDevice->playback.internalPeriods = data.periodsOut;
  18171. ma_strcpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), data.deviceName);
  18172. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback);
  18173. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  18174. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  18175. /* We must always have a valid ID because rerouting will look at it. */
  18176. ma_wcscpy_s(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  18177. }
  18178. return MA_SUCCESS;
  18179. }
  18180. static ma_result ma_device_init__wasapi(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  18181. {
  18182. ma_result result = MA_SUCCESS;
  18183. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18184. HRESULT hr;
  18185. ma_IMMDeviceEnumerator* pDeviceEnumerator;
  18186. #endif
  18187. MA_ASSERT(pDevice != NULL);
  18188. MA_ZERO_OBJECT(&pDevice->wasapi);
  18189. pDevice->wasapi.usage = pConfig->wasapi.usage;
  18190. pDevice->wasapi.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18191. pDevice->wasapi.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18192. pDevice->wasapi.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18193. pDevice->wasapi.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18194. pDevice->wasapi.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18195. /* Exclusive mode is not allowed with loopback. */
  18196. if (pConfig->deviceType == ma_device_type_loopback && pConfig->playback.shareMode == ma_share_mode_exclusive) {
  18197. return MA_INVALID_DEVICE_CONFIG;
  18198. }
  18199. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  18200. ma_device_init_internal_data__wasapi data;
  18201. data.formatIn = pDescriptorCapture->format;
  18202. data.channelsIn = pDescriptorCapture->channels;
  18203. data.sampleRateIn = pDescriptorCapture->sampleRate;
  18204. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  18205. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  18206. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  18207. data.periodsIn = pDescriptorCapture->periodCount;
  18208. data.shareMode = pDescriptorCapture->shareMode;
  18209. data.performanceProfile = pConfig->performanceProfile;
  18210. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18211. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18212. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18213. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18214. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18215. 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);
  18216. if (result != MA_SUCCESS) {
  18217. return result;
  18218. }
  18219. pDevice->wasapi.pAudioClientCapture = data.pAudioClient;
  18220. pDevice->wasapi.pCaptureClient = data.pCaptureClient;
  18221. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  18222. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  18223. pDevice->wasapi.originalPeriods = pDescriptorCapture->periodCount;
  18224. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  18225. /*
  18226. The event for capture needs to be manual reset for the same reason as playback. We keep the initial state set to unsignaled,
  18227. however, because we want to block until we actually have something for the first call to ma_device_read().
  18228. */
  18229. pDevice->wasapi.hEventCapture = CreateEventW(NULL, FALSE, FALSE, NULL); /* Auto reset, unsignaled by default. */
  18230. if (pDevice->wasapi.hEventCapture == NULL) {
  18231. result = ma_result_from_GetLastError(GetLastError());
  18232. if (pDevice->wasapi.pCaptureClient != NULL) {
  18233. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18234. pDevice->wasapi.pCaptureClient = NULL;
  18235. }
  18236. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  18237. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18238. pDevice->wasapi.pAudioClientCapture = NULL;
  18239. }
  18240. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for capture.");
  18241. return result;
  18242. }
  18243. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, pDevice->wasapi.hEventCapture);
  18244. pDevice->wasapi.periodSizeInFramesCapture = data.periodSizeInFramesOut;
  18245. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture, &pDevice->wasapi.actualBufferSizeInFramesCapture);
  18246. /* We must always have a valid ID. */
  18247. ma_wcscpy_s(pDevice->capture.id.wasapi, sizeof(pDevice->capture.id.wasapi), data.id.wasapi);
  18248. /* The descriptor needs to be updated with actual values. */
  18249. pDescriptorCapture->format = data.formatOut;
  18250. pDescriptorCapture->channels = data.channelsOut;
  18251. pDescriptorCapture->sampleRate = data.sampleRateOut;
  18252. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18253. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  18254. pDescriptorCapture->periodCount = data.periodsOut;
  18255. }
  18256. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  18257. ma_device_init_internal_data__wasapi data;
  18258. data.formatIn = pDescriptorPlayback->format;
  18259. data.channelsIn = pDescriptorPlayback->channels;
  18260. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  18261. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  18262. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  18263. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  18264. data.periodsIn = pDescriptorPlayback->periodCount;
  18265. data.shareMode = pDescriptorPlayback->shareMode;
  18266. data.performanceProfile = pConfig->performanceProfile;
  18267. data.noAutoConvertSRC = pConfig->wasapi.noAutoConvertSRC;
  18268. data.noDefaultQualitySRC = pConfig->wasapi.noDefaultQualitySRC;
  18269. data.noHardwareOffloading = pConfig->wasapi.noHardwareOffloading;
  18270. data.loopbackProcessID = pConfig->wasapi.loopbackProcessID;
  18271. data.loopbackProcessExclude = pConfig->wasapi.loopbackProcessExclude;
  18272. result = ma_device_init_internal__wasapi(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data);
  18273. if (result != MA_SUCCESS) {
  18274. if (pConfig->deviceType == ma_device_type_duplex) {
  18275. if (pDevice->wasapi.pCaptureClient != NULL) {
  18276. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18277. pDevice->wasapi.pCaptureClient = NULL;
  18278. }
  18279. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  18280. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18281. pDevice->wasapi.pAudioClientCapture = NULL;
  18282. }
  18283. CloseHandle(pDevice->wasapi.hEventCapture);
  18284. pDevice->wasapi.hEventCapture = NULL;
  18285. }
  18286. return result;
  18287. }
  18288. pDevice->wasapi.pAudioClientPlayback = data.pAudioClient;
  18289. pDevice->wasapi.pRenderClient = data.pRenderClient;
  18290. pDevice->wasapi.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  18291. pDevice->wasapi.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  18292. pDevice->wasapi.originalPeriods = pDescriptorPlayback->periodCount;
  18293. pDevice->wasapi.originalPerformanceProfile = pConfig->performanceProfile;
  18294. /*
  18295. The event for playback is needs to be manual reset because we want to explicitly control the fact that it becomes signalled
  18296. only after the whole available space has been filled, never before.
  18297. The playback event also needs to be initially set to a signaled state so that the first call to ma_device_write() is able
  18298. to get passed WaitForMultipleObjects().
  18299. */
  18300. pDevice->wasapi.hEventPlayback = CreateEventW(NULL, FALSE, TRUE, NULL); /* Auto reset, signaled by default. */
  18301. if (pDevice->wasapi.hEventPlayback == NULL) {
  18302. result = ma_result_from_GetLastError(GetLastError());
  18303. if (pConfig->deviceType == ma_device_type_duplex) {
  18304. if (pDevice->wasapi.pCaptureClient != NULL) {
  18305. ma_IAudioCaptureClient_Release((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient);
  18306. pDevice->wasapi.pCaptureClient = NULL;
  18307. }
  18308. if (pDevice->wasapi.pAudioClientCapture != NULL) {
  18309. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18310. pDevice->wasapi.pAudioClientCapture = NULL;
  18311. }
  18312. CloseHandle(pDevice->wasapi.hEventCapture);
  18313. pDevice->wasapi.hEventCapture = NULL;
  18314. }
  18315. if (pDevice->wasapi.pRenderClient != NULL) {
  18316. ma_IAudioRenderClient_Release((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient);
  18317. pDevice->wasapi.pRenderClient = NULL;
  18318. }
  18319. if (pDevice->wasapi.pAudioClientPlayback != NULL) {
  18320. ma_IAudioClient_Release((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18321. pDevice->wasapi.pAudioClientPlayback = NULL;
  18322. }
  18323. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create event for playback.");
  18324. return result;
  18325. }
  18326. ma_IAudioClient_SetEventHandle((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, pDevice->wasapi.hEventPlayback);
  18327. pDevice->wasapi.periodSizeInFramesPlayback = data.periodSizeInFramesOut;
  18328. ma_IAudioClient_GetBufferSize((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &pDevice->wasapi.actualBufferSizeInFramesPlayback);
  18329. /* We must always have a valid ID because rerouting will look at it. */
  18330. ma_wcscpy_s(pDevice->playback.id.wasapi, sizeof(pDevice->playback.id.wasapi), data.id.wasapi);
  18331. /* The descriptor needs to be updated with actual values. */
  18332. pDescriptorPlayback->format = data.formatOut;
  18333. pDescriptorPlayback->channels = data.channelsOut;
  18334. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  18335. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  18336. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  18337. pDescriptorPlayback->periodCount = data.periodsOut;
  18338. }
  18339. /*
  18340. 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
  18341. 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
  18342. stop the device outright and let the application handle it.
  18343. */
  18344. #if defined(MA_WIN32_DESKTOP) || defined(MA_WIN32_GDK)
  18345. if (pConfig->wasapi.noAutoStreamRouting == MA_FALSE) {
  18346. if ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.pDeviceID == NULL) {
  18347. pDevice->wasapi.allowCaptureAutoStreamRouting = MA_TRUE;
  18348. }
  18349. if ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.pDeviceID == NULL) {
  18350. pDevice->wasapi.allowPlaybackAutoStreamRouting = MA_TRUE;
  18351. }
  18352. }
  18353. hr = ma_CoCreateInstance(pDevice->pContext, MA_CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, MA_IID_IMMDeviceEnumerator, (void**)&pDeviceEnumerator);
  18354. if (FAILED(hr)) {
  18355. ma_device_uninit__wasapi(pDevice);
  18356. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to create device enumerator.");
  18357. return ma_result_from_HRESULT(hr);
  18358. }
  18359. pDevice->wasapi.notificationClient.lpVtbl = (void*)&g_maNotificationCientVtbl;
  18360. pDevice->wasapi.notificationClient.counter = 1;
  18361. pDevice->wasapi.notificationClient.pDevice = pDevice;
  18362. hr = pDeviceEnumerator->lpVtbl->RegisterEndpointNotificationCallback(pDeviceEnumerator, &pDevice->wasapi.notificationClient);
  18363. if (SUCCEEDED(hr)) {
  18364. pDevice->wasapi.pDeviceEnumerator = (ma_ptr)pDeviceEnumerator;
  18365. } else {
  18366. /* Not the end of the world if we fail to register the notification callback. We just won't support automatic stream routing. */
  18367. ma_IMMDeviceEnumerator_Release(pDeviceEnumerator);
  18368. }
  18369. #endif
  18370. c89atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  18371. c89atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  18372. return MA_SUCCESS;
  18373. }
  18374. static ma_result ma_device__get_available_frames__wasapi(ma_device* pDevice, ma_IAudioClient* pAudioClient, ma_uint32* pFrameCount)
  18375. {
  18376. ma_uint32 paddingFramesCount;
  18377. HRESULT hr;
  18378. ma_share_mode shareMode;
  18379. MA_ASSERT(pDevice != NULL);
  18380. MA_ASSERT(pFrameCount != NULL);
  18381. *pFrameCount = 0;
  18382. if ((ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientPlayback && (ma_ptr)pAudioClient != pDevice->wasapi.pAudioClientCapture) {
  18383. return MA_INVALID_OPERATION;
  18384. }
  18385. /*
  18386. I've had a report that GetCurrentPadding() is returning a frame count of 0 which is preventing
  18387. higher level function calls from doing anything because it thinks nothing is available. I have
  18388. taken a look at the documentation and it looks like this is unnecessary in exclusive mode.
  18389. From Microsoft's documentation:
  18390. For an exclusive-mode rendering or capture stream that was initialized with the
  18391. AUDCLNT_STREAMFLAGS_EVENTCALLBACK flag, the client typically has no use for the padding
  18392. value reported by GetCurrentPadding. Instead, the client accesses an entire buffer during
  18393. each processing pass.
  18394. Considering this, I'm going to skip GetCurrentPadding() for exclusive mode and just report the
  18395. entire buffer. This depends on the caller making sure they wait on the event handler.
  18396. */
  18397. shareMode = ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) ? pDevice->playback.shareMode : pDevice->capture.shareMode;
  18398. if (shareMode == ma_share_mode_shared) {
  18399. /* Shared mode. */
  18400. hr = ma_IAudioClient_GetCurrentPadding(pAudioClient, &paddingFramesCount);
  18401. if (FAILED(hr)) {
  18402. return ma_result_from_HRESULT(hr);
  18403. }
  18404. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  18405. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback - paddingFramesCount;
  18406. } else {
  18407. *pFrameCount = paddingFramesCount;
  18408. }
  18409. } else {
  18410. /* Exclusive mode. */
  18411. if ((ma_ptr)pAudioClient == pDevice->wasapi.pAudioClientPlayback) {
  18412. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  18413. } else {
  18414. *pFrameCount = pDevice->wasapi.actualBufferSizeInFramesCapture;
  18415. }
  18416. }
  18417. return MA_SUCCESS;
  18418. }
  18419. static ma_result ma_device_reroute__wasapi(ma_device* pDevice, ma_device_type deviceType)
  18420. {
  18421. ma_result result;
  18422. if (deviceType == ma_device_type_duplex) {
  18423. return MA_INVALID_ARGS;
  18424. }
  18425. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "=== CHANGING DEVICE ===\n");
  18426. result = ma_device_reinit__wasapi(pDevice, deviceType);
  18427. if (result != MA_SUCCESS) {
  18428. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WASAPI] Reinitializing device after route change failed.\n");
  18429. return result;
  18430. }
  18431. ma_device__post_init_setup(pDevice, deviceType);
  18432. ma_device__on_notification_rerouted(pDevice);
  18433. return MA_SUCCESS;
  18434. }
  18435. static ma_result ma_device_start__wasapi(ma_device* pDevice)
  18436. {
  18437. HRESULT hr;
  18438. MA_ASSERT(pDevice != NULL);
  18439. if (pDevice->pContext->wasapi.hAvrt) {
  18440. LPCWSTR pTaskName = ma_to_usage_string__wasapi(pDevice->wasapi.usage);
  18441. if (pTaskName) {
  18442. DWORD idx = 0;
  18443. pDevice->wasapi.hAvrtHandle = ((MA_PFN_AvSetMmThreadCharacteristicsW)pDevice->pContext->wasapi.AvSetMmThreadCharacteristicsW)(pTaskName, &idx);
  18444. }
  18445. }
  18446. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  18447. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18448. if (FAILED(hr)) {
  18449. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal capture device.");
  18450. return ma_result_from_HRESULT(hr);
  18451. }
  18452. c89atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_TRUE);
  18453. }
  18454. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  18455. hr = ma_IAudioClient_Start((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18456. if (FAILED(hr)) {
  18457. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to start internal playback device.");
  18458. return ma_result_from_HRESULT(hr);
  18459. }
  18460. c89atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_TRUE);
  18461. }
  18462. return MA_SUCCESS;
  18463. }
  18464. static ma_result ma_device_stop__wasapi(ma_device* pDevice)
  18465. {
  18466. ma_result result;
  18467. HRESULT hr;
  18468. MA_ASSERT(pDevice != NULL);
  18469. if (pDevice->wasapi.hAvrtHandle) {
  18470. ((MA_PFN_AvRevertMmThreadCharacteristics)pDevice->pContext->wasapi.AvRevertMmThreadcharacteristics)((HANDLE)pDevice->wasapi.hAvrtHandle);
  18471. pDevice->wasapi.hAvrtHandle = NULL;
  18472. }
  18473. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  18474. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18475. if (FAILED(hr)) {
  18476. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal capture device.");
  18477. return ma_result_from_HRESULT(hr);
  18478. }
  18479. /* The audio client needs to be reset otherwise restarting will fail. */
  18480. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientCapture);
  18481. if (FAILED(hr)) {
  18482. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal capture device.");
  18483. return ma_result_from_HRESULT(hr);
  18484. }
  18485. /* If we have a mapped buffer we need to release it. */
  18486. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  18487. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18488. pDevice->wasapi.pMappedBufferCapture = NULL;
  18489. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18490. pDevice->wasapi.mappedBufferCaptureLen = 0;
  18491. }
  18492. c89atomic_exchange_32(&pDevice->wasapi.isStartedCapture, MA_FALSE);
  18493. }
  18494. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  18495. /*
  18496. The buffer needs to be drained before stopping the device. Not doing this will result in the last few frames not getting output to
  18497. the speakers. This is a problem for very short sounds because it'll result in a significant portion of it not getting played.
  18498. */
  18499. if (c89atomic_load_32(&pDevice->wasapi.isStartedPlayback)) {
  18500. /* We need to make sure we put a timeout here or else we'll risk getting stuck in a deadlock in some cases. */
  18501. DWORD waitTime = pDevice->wasapi.actualBufferSizeInFramesPlayback / pDevice->playback.internalSampleRate;
  18502. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  18503. WaitForSingleObject(pDevice->wasapi.hEventPlayback, waitTime);
  18504. } else {
  18505. ma_uint32 prevFramesAvaialablePlayback = (ma_uint32)-1;
  18506. ma_uint32 framesAvailablePlayback;
  18507. for (;;) {
  18508. result = ma_device__get_available_frames__wasapi(pDevice, (ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback, &framesAvailablePlayback);
  18509. if (result != MA_SUCCESS) {
  18510. break;
  18511. }
  18512. if (framesAvailablePlayback >= pDevice->wasapi.actualBufferSizeInFramesPlayback) {
  18513. break;
  18514. }
  18515. /*
  18516. Just a safety check to avoid an infinite loop. If this iteration results in a situation where the number of available frames
  18517. 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.
  18518. */
  18519. if (framesAvailablePlayback == prevFramesAvaialablePlayback) {
  18520. break;
  18521. }
  18522. prevFramesAvaialablePlayback = framesAvailablePlayback;
  18523. WaitForSingleObject(pDevice->wasapi.hEventPlayback, waitTime * 1000);
  18524. ResetEvent(pDevice->wasapi.hEventPlayback); /* Manual reset. */
  18525. }
  18526. }
  18527. }
  18528. hr = ma_IAudioClient_Stop((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18529. if (FAILED(hr)) {
  18530. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to stop internal playback device.");
  18531. return ma_result_from_HRESULT(hr);
  18532. }
  18533. /* The audio client needs to be reset otherwise restarting will fail. */
  18534. hr = ma_IAudioClient_Reset((ma_IAudioClient*)pDevice->wasapi.pAudioClientPlayback);
  18535. if (FAILED(hr)) {
  18536. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WASAPI] Failed to reset internal playback device.");
  18537. return ma_result_from_HRESULT(hr);
  18538. }
  18539. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  18540. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  18541. pDevice->wasapi.pMappedBufferPlayback = NULL;
  18542. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  18543. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  18544. }
  18545. c89atomic_exchange_32(&pDevice->wasapi.isStartedPlayback, MA_FALSE);
  18546. }
  18547. return MA_SUCCESS;
  18548. }
  18549. #ifndef MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS
  18550. #define MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS 5000
  18551. #endif
  18552. static ma_result ma_device_read__wasapi(ma_device* pDevice, void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  18553. {
  18554. ma_result result = MA_SUCCESS;
  18555. ma_uint32 totalFramesProcessed = 0;
  18556. /*
  18557. When reading, we need to get a buffer and process all of it before releasing it. Because the
  18558. frame count (frameCount) can be different to the size of the buffer, we'll need to cache the
  18559. pointer to the buffer.
  18560. */
  18561. /* Keep running until we've processed the requested number of frames. */
  18562. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  18563. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  18564. /* If we have a mapped data buffer, consume that first. */
  18565. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  18566. /* We have a cached data pointer so consume that before grabbing another one from WASAPI. */
  18567. ma_uint32 framesToProcessNow = framesRemaining;
  18568. if (framesToProcessNow > pDevice->wasapi.mappedBufferCaptureLen) {
  18569. framesToProcessNow = pDevice->wasapi.mappedBufferCaptureLen;
  18570. }
  18571. /* Now just copy the data over to the output buffer. */
  18572. ma_copy_pcm_frames(
  18573. ma_offset_pcm_frames_ptr(pFrames, totalFramesProcessed, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  18574. ma_offset_pcm_frames_const_ptr(pDevice->wasapi.pMappedBufferCapture, pDevice->wasapi.mappedBufferCaptureCap - pDevice->wasapi.mappedBufferCaptureLen, pDevice->capture.internalFormat, pDevice->capture.internalChannels),
  18575. framesToProcessNow,
  18576. pDevice->capture.internalFormat, pDevice->capture.internalChannels
  18577. );
  18578. totalFramesProcessed += framesToProcessNow;
  18579. pDevice->wasapi.mappedBufferCaptureLen -= framesToProcessNow;
  18580. /* If the data buffer has been fully consumed we need to release it. */
  18581. if (pDevice->wasapi.mappedBufferCaptureLen == 0) {
  18582. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18583. pDevice->wasapi.pMappedBufferCapture = NULL;
  18584. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18585. }
  18586. } else {
  18587. /* We don't have any cached data pointer, so grab another one. */
  18588. HRESULT hr;
  18589. DWORD flags = 0;
  18590. /* First just ask WASAPI for a data buffer. If it's not available, we'll wait for more. */
  18591. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  18592. if (hr == S_OK) {
  18593. /* We got a data buffer. Continue to the next loop iteration which will then read from the mapped pointer. */
  18594. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  18595. /*
  18596. There have been reports that indicate that at times the AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY is reported for every
  18597. call to IAudioCaptureClient_GetBuffer() above which results in spamming of the debug messages below. To partially
  18598. work around this, I'm only outputting these messages when MA_DEBUG_OUTPUT is explicitly defined. The better solution
  18599. would be to figure out why the flag is always getting reported.
  18600. */
  18601. #if defined(MA_DEBUG_OUTPUT)
  18602. {
  18603. if (flags != 0) {
  18604. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Capture Flags: %ld\n", flags);
  18605. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  18606. 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);
  18607. }
  18608. }
  18609. }
  18610. #endif
  18611. /* Overrun detection. */
  18612. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  18613. /* Glitched. Probably due to an overrun. */
  18614. /*
  18615. If we got an overrun it probably means we're straddling the end of the buffer. In normal capture
  18616. mode this is the fault of the client application because they're responsible for ensuring data is
  18617. processed fast enough. In duplex mode, however, the processing of audio is tied to the playback
  18618. device, so this can possibly be the result of a timing de-sync.
  18619. In capture mode we're not going to do any kind of recovery because the real fix is for the client
  18620. application to process faster. In duplex mode, we'll treat this as a desync and reset the buffers
  18621. to prevent a never-ending sequence of glitches due to straddling the end of the buffer.
  18622. */
  18623. if (pDevice->type == ma_device_type_duplex) {
  18624. /*
  18625. Experiment:
  18626. If we empty out the *entire* buffer we may end up putting ourselves into an underrun position
  18627. which isn't really any better than the overrun we're probably in right now. Instead we'll just
  18628. empty out about half.
  18629. */
  18630. ma_uint32 i;
  18631. ma_uint32 periodCount = (pDevice->wasapi.actualBufferSizeInFramesCapture / pDevice->wasapi.periodSizeInFramesCapture);
  18632. ma_uint32 iterationCount = periodCount / 2;
  18633. if ((periodCount % 2) > 0) {
  18634. iterationCount += 1;
  18635. }
  18636. for (i = 0; i < iterationCount; i += 1) {
  18637. hr = ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18638. if (FAILED(hr)) {
  18639. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_ReleaseBuffer() failed with %d.\n", hr);
  18640. break;
  18641. }
  18642. flags = 0;
  18643. hr = ma_IAudioCaptureClient_GetBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, (BYTE**)&pDevice->wasapi.pMappedBufferCapture, &pDevice->wasapi.mappedBufferCaptureCap, &flags, NULL, NULL);
  18644. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || FAILED(hr)) {
  18645. /*
  18646. The buffer has been completely emptied or an error occurred. In this case we'll need
  18647. to reset the state of the mapped buffer which will trigger the next iteration to get
  18648. a fresh buffer from WASAPI.
  18649. */
  18650. pDevice->wasapi.pMappedBufferCapture = NULL;
  18651. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18652. pDevice->wasapi.mappedBufferCaptureLen = 0;
  18653. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY) {
  18654. if ((flags & MA_AUDCLNT_BUFFERFLAGS_DATA_DISCONTINUITY) != 0) {
  18655. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied, and data discontinuity still reported.\n");
  18656. } else {
  18657. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: Buffer emptied.\n");
  18658. }
  18659. }
  18660. if (FAILED(hr)) {
  18661. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[WASAPI] Data discontinuity recovery: IAudioCaptureClient_GetBuffer() failed with %d.\n", hr);
  18662. }
  18663. break;
  18664. }
  18665. }
  18666. /* If at this point we have a valid buffer mapped, make sure the buffer length is set appropriately. */
  18667. if (pDevice->wasapi.pMappedBufferCapture != NULL) {
  18668. pDevice->wasapi.mappedBufferCaptureLen = pDevice->wasapi.mappedBufferCaptureCap;
  18669. }
  18670. }
  18671. }
  18672. continue;
  18673. } else {
  18674. if (hr == MA_AUDCLNT_S_BUFFER_EMPTY || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  18675. /*
  18676. No data is available. We need to wait for more. There's two situations to consider
  18677. here. The first is normal capture mode. If this times out it probably means the
  18678. microphone isn't delivering data for whatever reason. In this case we'll just
  18679. abort the read and return whatever we were able to get. The other situations is
  18680. loopback mode, in which case a timeout probably just means the nothing is playing
  18681. through the speakers.
  18682. */
  18683. /* Experiment: Use a shorter timeout for loopback mode. */
  18684. DWORD timeoutInMilliseconds = MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS;
  18685. if (pDevice->type == ma_device_type_loopback) {
  18686. timeoutInMilliseconds = 10;
  18687. }
  18688. if (WaitForSingleObject(pDevice->wasapi.hEventCapture, timeoutInMilliseconds) != WAIT_OBJECT_0) {
  18689. if (pDevice->type == ma_device_type_loopback) {
  18690. continue; /* Keep waiting in loopback mode. */
  18691. } else {
  18692. result = MA_ERROR;
  18693. break; /* Wait failed. */
  18694. }
  18695. }
  18696. /* At this point we should be able to loop back to the start of the loop and try retrieving a data buffer again. */
  18697. } else {
  18698. /* An error occured and we need to abort. */
  18699. 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);
  18700. result = ma_result_from_HRESULT(hr);
  18701. break;
  18702. }
  18703. }
  18704. }
  18705. }
  18706. /*
  18707. If we were unable to process the entire requested frame count, but we still have a mapped buffer,
  18708. there's a good chance either an error occurred or the device was stopped mid-read. In this case
  18709. we'll need to make sure the buffer is released.
  18710. */
  18711. if (totalFramesProcessed < frameCount && pDevice->wasapi.pMappedBufferCapture != NULL) {
  18712. ma_IAudioCaptureClient_ReleaseBuffer((ma_IAudioCaptureClient*)pDevice->wasapi.pCaptureClient, pDevice->wasapi.mappedBufferCaptureCap);
  18713. pDevice->wasapi.pMappedBufferCapture = NULL;
  18714. pDevice->wasapi.mappedBufferCaptureCap = 0;
  18715. pDevice->wasapi.mappedBufferCaptureLen = 0;
  18716. }
  18717. if (pFramesRead != NULL) {
  18718. *pFramesRead = totalFramesProcessed;
  18719. }
  18720. return result;
  18721. }
  18722. static ma_result ma_device_write__wasapi(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  18723. {
  18724. ma_result result = MA_SUCCESS;
  18725. ma_uint32 totalFramesProcessed = 0;
  18726. /* Keep writing to the device until it's stopped or we've consumed all of our input. */
  18727. while (ma_device_get_state(pDevice) == ma_device_state_started && totalFramesProcessed < frameCount) {
  18728. ma_uint32 framesRemaining = frameCount - totalFramesProcessed;
  18729. /*
  18730. We're going to do this in a similar way to capture. We'll first check if the cached data pointer
  18731. is valid, and if so, read from that. Otherwise We will call IAudioRenderClient_GetBuffer() with
  18732. a requested buffer size equal to our actual period size. If it returns AUDCLNT_E_BUFFER_TOO_LARGE
  18733. it means we need to wait for some data to become available.
  18734. */
  18735. if (pDevice->wasapi.pMappedBufferPlayback != NULL) {
  18736. /* We still have some space available in the mapped data buffer. Write to it. */
  18737. ma_uint32 framesToProcessNow = framesRemaining;
  18738. if (framesToProcessNow > (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen)) {
  18739. framesToProcessNow = (pDevice->wasapi.mappedBufferPlaybackCap - pDevice->wasapi.mappedBufferPlaybackLen);
  18740. }
  18741. /* Now just copy the data over to the output buffer. */
  18742. ma_copy_pcm_frames(
  18743. ma_offset_pcm_frames_ptr(pDevice->wasapi.pMappedBufferPlayback, pDevice->wasapi.mappedBufferPlaybackLen, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  18744. ma_offset_pcm_frames_const_ptr(pFrames, totalFramesProcessed, pDevice->playback.internalFormat, pDevice->playback.internalChannels),
  18745. framesToProcessNow,
  18746. pDevice->playback.internalFormat, pDevice->playback.internalChannels
  18747. );
  18748. totalFramesProcessed += framesToProcessNow;
  18749. pDevice->wasapi.mappedBufferPlaybackLen += framesToProcessNow;
  18750. /* If the data buffer has been fully consumed we need to release it. */
  18751. if (pDevice->wasapi.mappedBufferPlaybackLen == pDevice->wasapi.mappedBufferPlaybackCap) {
  18752. ma_IAudioRenderClient_ReleaseBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, pDevice->wasapi.mappedBufferPlaybackCap, 0);
  18753. pDevice->wasapi.pMappedBufferPlayback = NULL;
  18754. pDevice->wasapi.mappedBufferPlaybackCap = 0;
  18755. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  18756. /*
  18757. In exclusive mode we need to wait here. Exclusive mode is weird because GetBuffer() never
  18758. seems to return AUDCLNT_E_BUFFER_TOO_LARGE, which is what we normally use to determine
  18759. whether or not we need to wait for more data.
  18760. */
  18761. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  18762. if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  18763. result = MA_ERROR;
  18764. break; /* Wait failed. Probably timed out. */
  18765. }
  18766. }
  18767. }
  18768. } else {
  18769. /* We don't have a mapped data buffer so we'll need to get one. */
  18770. HRESULT hr;
  18771. ma_uint32 bufferSizeInFrames;
  18772. /* Special rules for exclusive mode. */
  18773. if (pDevice->playback.shareMode == ma_share_mode_exclusive) {
  18774. bufferSizeInFrames = pDevice->wasapi.actualBufferSizeInFramesPlayback;
  18775. } else {
  18776. bufferSizeInFrames = pDevice->wasapi.periodSizeInFramesPlayback;
  18777. }
  18778. hr = ma_IAudioRenderClient_GetBuffer((ma_IAudioRenderClient*)pDevice->wasapi.pRenderClient, bufferSizeInFrames, (BYTE**)&pDevice->wasapi.pMappedBufferPlayback);
  18779. if (hr == S_OK) {
  18780. /* We have data available. */
  18781. pDevice->wasapi.mappedBufferPlaybackCap = bufferSizeInFrames;
  18782. pDevice->wasapi.mappedBufferPlaybackLen = 0;
  18783. } else {
  18784. if (hr == MA_AUDCLNT_E_BUFFER_TOO_LARGE || hr == MA_AUDCLNT_E_BUFFER_ERROR) {
  18785. /* Not enough data available. We need to wait for more. */
  18786. if (WaitForSingleObject(pDevice->wasapi.hEventPlayback, MA_WASAPI_WAIT_TIMEOUT_MILLISECONDS) != WAIT_OBJECT_0) {
  18787. result = MA_ERROR;
  18788. break; /* Wait failed. Probably timed out. */
  18789. }
  18790. } else {
  18791. /* Some error occurred. We'll need to abort. */
  18792. 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);
  18793. result = ma_result_from_HRESULT(hr);
  18794. break;
  18795. }
  18796. }
  18797. }
  18798. }
  18799. if (pFramesWritten != NULL) {
  18800. *pFramesWritten = totalFramesProcessed;
  18801. }
  18802. return result;
  18803. }
  18804. static ma_result ma_device_data_loop_wakeup__wasapi(ma_device* pDevice)
  18805. {
  18806. MA_ASSERT(pDevice != NULL);
  18807. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  18808. SetEvent((HANDLE)pDevice->wasapi.hEventCapture);
  18809. }
  18810. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  18811. SetEvent((HANDLE)pDevice->wasapi.hEventPlayback);
  18812. }
  18813. return MA_SUCCESS;
  18814. }
  18815. static ma_result ma_context_uninit__wasapi(ma_context* pContext)
  18816. {
  18817. MA_ASSERT(pContext != NULL);
  18818. MA_ASSERT(pContext->backend == ma_backend_wasapi);
  18819. if (pContext->wasapi.commandThread != NULL) {
  18820. ma_context_command__wasapi cmd = ma_context_init_command__wasapi(MA_CONTEXT_COMMAND_QUIT__WASAPI);
  18821. ma_context_post_command__wasapi(pContext, &cmd);
  18822. ma_thread_wait(&pContext->wasapi.commandThread);
  18823. if (pContext->wasapi.hAvrt) {
  18824. ma_dlclose(pContext, pContext->wasapi.hAvrt);
  18825. pContext->wasapi.hAvrt = NULL;
  18826. }
  18827. #if defined(MA_WIN32_UWP)
  18828. {
  18829. if (pContext->wasapi.hMMDevapi) {
  18830. ma_dlclose(pContext, pContext->wasapi.hMMDevapi);
  18831. pContext->wasapi.hMMDevapi = NULL;
  18832. }
  18833. }
  18834. #endif
  18835. /* Only after the thread has been terminated can we uninitialize the sync objects for the command thread. */
  18836. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  18837. ma_mutex_uninit(&pContext->wasapi.commandLock);
  18838. }
  18839. return MA_SUCCESS;
  18840. }
  18841. static ma_result ma_context_init__wasapi(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  18842. {
  18843. ma_result result = MA_SUCCESS;
  18844. MA_ASSERT(pContext != NULL);
  18845. (void)pConfig;
  18846. #ifdef MA_WIN32_DESKTOP
  18847. /*
  18848. WASAPI is only supported in Vista SP1 and newer. The reason for SP1 and not the base version of Vista is that event-driven
  18849. exclusive mode does not work until SP1.
  18850. Unfortunately older compilers don't define these functions so we need to dynamically load them in order to avoid a link error.
  18851. */
  18852. {
  18853. ma_OSVERSIONINFOEXW osvi;
  18854. ma_handle kernel32DLL;
  18855. ma_PFNVerifyVersionInfoW _VerifyVersionInfoW;
  18856. ma_PFNVerSetConditionMask _VerSetConditionMask;
  18857. kernel32DLL = ma_dlopen(pContext, "kernel32.dll");
  18858. if (kernel32DLL == NULL) {
  18859. return MA_NO_BACKEND;
  18860. }
  18861. _VerifyVersionInfoW = (ma_PFNVerifyVersionInfoW )ma_dlsym(pContext, kernel32DLL, "VerifyVersionInfoW");
  18862. _VerSetConditionMask = (ma_PFNVerSetConditionMask)ma_dlsym(pContext, kernel32DLL, "VerSetConditionMask");
  18863. if (_VerifyVersionInfoW == NULL || _VerSetConditionMask == NULL) {
  18864. ma_dlclose(pContext, kernel32DLL);
  18865. return MA_NO_BACKEND;
  18866. }
  18867. MA_ZERO_OBJECT(&osvi);
  18868. osvi.dwOSVersionInfoSize = sizeof(osvi);
  18869. osvi.dwMajorVersion = ((MA_WIN32_WINNT_VISTA >> 8) & 0xFF);
  18870. osvi.dwMinorVersion = ((MA_WIN32_WINNT_VISTA >> 0) & 0xFF);
  18871. osvi.wServicePackMajor = 1;
  18872. 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))) {
  18873. result = MA_SUCCESS;
  18874. } else {
  18875. result = MA_NO_BACKEND;
  18876. }
  18877. ma_dlclose(pContext, kernel32DLL);
  18878. }
  18879. #endif
  18880. if (result != MA_SUCCESS) {
  18881. return result;
  18882. }
  18883. MA_ZERO_OBJECT(&pContext->wasapi);
  18884. /*
  18885. Annoyingly, WASAPI does not allow you to release an IAudioClient object from a different thread
  18886. than the one that retrieved it with GetService(). This can result in a deadlock in two
  18887. situations:
  18888. 1) When calling ma_device_uninit() from a different thread to ma_device_init(); and
  18889. 2) When uninitializing and reinitializing the internal IAudioClient object in response to
  18890. automatic stream routing.
  18891. We could define ma_device_uninit() such that it must be called on the same thread as
  18892. ma_device_init(). We could also just not release the IAudioClient when performing automatic
  18893. stream routing to avoid the deadlock. Neither of these are acceptable solutions in my view so
  18894. we're going to have to work around this with a worker thread. This is not ideal, but I can't
  18895. think of a better way to do this.
  18896. More information about this can be found here:
  18897. https://docs.microsoft.com/en-us/windows/win32/api/audioclient/nn-audioclient-iaudiorenderclient
  18898. Note this section:
  18899. When releasing an IAudioRenderClient interface instance, the client must call the interface's
  18900. Release method from the same thread as the call to IAudioClient::GetService that created the
  18901. object.
  18902. */
  18903. {
  18904. result = ma_mutex_init(&pContext->wasapi.commandLock);
  18905. if (result != MA_SUCCESS) {
  18906. return result;
  18907. }
  18908. result = ma_semaphore_init(0, &pContext->wasapi.commandSem);
  18909. if (result != MA_SUCCESS) {
  18910. ma_mutex_uninit(&pContext->wasapi.commandLock);
  18911. return result;
  18912. }
  18913. result = ma_thread_create(&pContext->wasapi.commandThread, ma_thread_priority_normal, 0, ma_context_command_thread__wasapi, pContext, &pContext->allocationCallbacks);
  18914. if (result != MA_SUCCESS) {
  18915. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  18916. ma_mutex_uninit(&pContext->wasapi.commandLock);
  18917. return result;
  18918. }
  18919. #if defined(MA_WIN32_UWP)
  18920. {
  18921. /* Link to mmdevapi so we can get access to ActivateAudioInterfaceAsync(). */
  18922. pContext->wasapi.hMMDevapi = ma_dlopen(pContext, "mmdevapi.dll");
  18923. if (pContext->wasapi.hMMDevapi) {
  18924. pContext->wasapi.ActivateAudioInterfaceAsync = ma_dlsym(pContext, pContext->wasapi.hMMDevapi, "ActivateAudioInterfaceAsync");
  18925. if (pContext->wasapi.ActivateAudioInterfaceAsync == NULL) {
  18926. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  18927. ma_mutex_uninit(&pContext->wasapi.commandLock);
  18928. ma_dlclose(pContext, pContext->wasapi.hMMDevapi);
  18929. return MA_NO_BACKEND; /* ActivateAudioInterfaceAsync() could not be loaded. */
  18930. }
  18931. } else {
  18932. ma_semaphore_uninit(&pContext->wasapi.commandSem);
  18933. ma_mutex_uninit(&pContext->wasapi.commandLock);
  18934. return MA_NO_BACKEND; /* Failed to load mmdevapi.dll which is required for ActivateAudioInterfaceAsync() */
  18935. }
  18936. }
  18937. #endif
  18938. /* Optionally use the Avrt API to specify the audio thread's latency sensitivity requirements */
  18939. pContext->wasapi.hAvrt = ma_dlopen(pContext, "avrt.dll");
  18940. if (pContext->wasapi.hAvrt) {
  18941. pContext->wasapi.AvSetMmThreadCharacteristicsW = ma_dlsym(pContext, pContext->wasapi.hAvrt, "AvSetMmThreadCharacteristicsW");
  18942. pContext->wasapi.AvRevertMmThreadcharacteristics = ma_dlsym(pContext, pContext->wasapi.hAvrt, "AvRevertMmThreadCharacteristics");
  18943. /* If either function could not be found, disable use of avrt entirely. */
  18944. if (!pContext->wasapi.AvSetMmThreadCharacteristicsW || !pContext->wasapi.AvRevertMmThreadcharacteristics) {
  18945. pContext->wasapi.AvSetMmThreadCharacteristicsW = NULL;
  18946. pContext->wasapi.AvRevertMmThreadcharacteristics = NULL;
  18947. ma_dlclose(pContext, pContext->wasapi.hAvrt);
  18948. pContext->wasapi.hAvrt = NULL;
  18949. }
  18950. }
  18951. }
  18952. pCallbacks->onContextInit = ma_context_init__wasapi;
  18953. pCallbacks->onContextUninit = ma_context_uninit__wasapi;
  18954. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__wasapi;
  18955. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__wasapi;
  18956. pCallbacks->onDeviceInit = ma_device_init__wasapi;
  18957. pCallbacks->onDeviceUninit = ma_device_uninit__wasapi;
  18958. pCallbacks->onDeviceStart = ma_device_start__wasapi;
  18959. pCallbacks->onDeviceStop = ma_device_stop__wasapi;
  18960. pCallbacks->onDeviceRead = ma_device_read__wasapi;
  18961. pCallbacks->onDeviceWrite = ma_device_write__wasapi;
  18962. pCallbacks->onDeviceDataLoop = NULL;
  18963. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__wasapi;
  18964. return MA_SUCCESS;
  18965. }
  18966. #endif
  18967. /******************************************************************************
  18968. DirectSound Backend
  18969. ******************************************************************************/
  18970. #ifdef MA_HAS_DSOUND
  18971. /*#include <dsound.h>*/
  18972. /*static const GUID MA_GUID_IID_DirectSoundNotify = {0xb0210783, 0x89cd, 0x11d0, {0xaf, 0x08, 0x00, 0xa0, 0xc9, 0x25, 0xcd, 0x16}};*/
  18973. /* miniaudio only uses priority or exclusive modes. */
  18974. #define MA_DSSCL_NORMAL 1
  18975. #define MA_DSSCL_PRIORITY 2
  18976. #define MA_DSSCL_EXCLUSIVE 3
  18977. #define MA_DSSCL_WRITEPRIMARY 4
  18978. #define MA_DSCAPS_PRIMARYMONO 0x00000001
  18979. #define MA_DSCAPS_PRIMARYSTEREO 0x00000002
  18980. #define MA_DSCAPS_PRIMARY8BIT 0x00000004
  18981. #define MA_DSCAPS_PRIMARY16BIT 0x00000008
  18982. #define MA_DSCAPS_CONTINUOUSRATE 0x00000010
  18983. #define MA_DSCAPS_EMULDRIVER 0x00000020
  18984. #define MA_DSCAPS_CERTIFIED 0x00000040
  18985. #define MA_DSCAPS_SECONDARYMONO 0x00000100
  18986. #define MA_DSCAPS_SECONDARYSTEREO 0x00000200
  18987. #define MA_DSCAPS_SECONDARY8BIT 0x00000400
  18988. #define MA_DSCAPS_SECONDARY16BIT 0x00000800
  18989. #define MA_DSBCAPS_PRIMARYBUFFER 0x00000001
  18990. #define MA_DSBCAPS_STATIC 0x00000002
  18991. #define MA_DSBCAPS_LOCHARDWARE 0x00000004
  18992. #define MA_DSBCAPS_LOCSOFTWARE 0x00000008
  18993. #define MA_DSBCAPS_CTRL3D 0x00000010
  18994. #define MA_DSBCAPS_CTRLFREQUENCY 0x00000020
  18995. #define MA_DSBCAPS_CTRLPAN 0x00000040
  18996. #define MA_DSBCAPS_CTRLVOLUME 0x00000080
  18997. #define MA_DSBCAPS_CTRLPOSITIONNOTIFY 0x00000100
  18998. #define MA_DSBCAPS_CTRLFX 0x00000200
  18999. #define MA_DSBCAPS_STICKYFOCUS 0x00004000
  19000. #define MA_DSBCAPS_GLOBALFOCUS 0x00008000
  19001. #define MA_DSBCAPS_GETCURRENTPOSITION2 0x00010000
  19002. #define MA_DSBCAPS_MUTE3DATMAXDISTANCE 0x00020000
  19003. #define MA_DSBCAPS_LOCDEFER 0x00040000
  19004. #define MA_DSBCAPS_TRUEPLAYPOSITION 0x00080000
  19005. #define MA_DSBPLAY_LOOPING 0x00000001
  19006. #define MA_DSBPLAY_LOCHARDWARE 0x00000002
  19007. #define MA_DSBPLAY_LOCSOFTWARE 0x00000004
  19008. #define MA_DSBPLAY_TERMINATEBY_TIME 0x00000008
  19009. #define MA_DSBPLAY_TERMINATEBY_DISTANCE 0x00000010
  19010. #define MA_DSBPLAY_TERMINATEBY_PRIORITY 0x00000020
  19011. #define MA_DSCBSTART_LOOPING 0x00000001
  19012. typedef struct
  19013. {
  19014. DWORD dwSize;
  19015. DWORD dwFlags;
  19016. DWORD dwBufferBytes;
  19017. DWORD dwReserved;
  19018. WAVEFORMATEX* lpwfxFormat;
  19019. GUID guid3DAlgorithm;
  19020. } MA_DSBUFFERDESC;
  19021. typedef struct
  19022. {
  19023. DWORD dwSize;
  19024. DWORD dwFlags;
  19025. DWORD dwBufferBytes;
  19026. DWORD dwReserved;
  19027. WAVEFORMATEX* lpwfxFormat;
  19028. DWORD dwFXCount;
  19029. void* lpDSCFXDesc; /* <-- miniaudio doesn't use this, so set to void*. */
  19030. } MA_DSCBUFFERDESC;
  19031. typedef struct
  19032. {
  19033. DWORD dwSize;
  19034. DWORD dwFlags;
  19035. DWORD dwMinSecondarySampleRate;
  19036. DWORD dwMaxSecondarySampleRate;
  19037. DWORD dwPrimaryBuffers;
  19038. DWORD dwMaxHwMixingAllBuffers;
  19039. DWORD dwMaxHwMixingStaticBuffers;
  19040. DWORD dwMaxHwMixingStreamingBuffers;
  19041. DWORD dwFreeHwMixingAllBuffers;
  19042. DWORD dwFreeHwMixingStaticBuffers;
  19043. DWORD dwFreeHwMixingStreamingBuffers;
  19044. DWORD dwMaxHw3DAllBuffers;
  19045. DWORD dwMaxHw3DStaticBuffers;
  19046. DWORD dwMaxHw3DStreamingBuffers;
  19047. DWORD dwFreeHw3DAllBuffers;
  19048. DWORD dwFreeHw3DStaticBuffers;
  19049. DWORD dwFreeHw3DStreamingBuffers;
  19050. DWORD dwTotalHwMemBytes;
  19051. DWORD dwFreeHwMemBytes;
  19052. DWORD dwMaxContigFreeHwMemBytes;
  19053. DWORD dwUnlockTransferRateHwBuffers;
  19054. DWORD dwPlayCpuOverheadSwBuffers;
  19055. DWORD dwReserved1;
  19056. DWORD dwReserved2;
  19057. } MA_DSCAPS;
  19058. typedef struct
  19059. {
  19060. DWORD dwSize;
  19061. DWORD dwFlags;
  19062. DWORD dwBufferBytes;
  19063. DWORD dwUnlockTransferRate;
  19064. DWORD dwPlayCpuOverhead;
  19065. } MA_DSBCAPS;
  19066. typedef struct
  19067. {
  19068. DWORD dwSize;
  19069. DWORD dwFlags;
  19070. DWORD dwFormats;
  19071. DWORD dwChannels;
  19072. } MA_DSCCAPS;
  19073. typedef struct
  19074. {
  19075. DWORD dwSize;
  19076. DWORD dwFlags;
  19077. DWORD dwBufferBytes;
  19078. DWORD dwReserved;
  19079. } MA_DSCBCAPS;
  19080. typedef struct
  19081. {
  19082. DWORD dwOffset;
  19083. HANDLE hEventNotify;
  19084. } MA_DSBPOSITIONNOTIFY;
  19085. typedef struct ma_IDirectSound ma_IDirectSound;
  19086. typedef struct ma_IDirectSoundBuffer ma_IDirectSoundBuffer;
  19087. typedef struct ma_IDirectSoundCapture ma_IDirectSoundCapture;
  19088. typedef struct ma_IDirectSoundCaptureBuffer ma_IDirectSoundCaptureBuffer;
  19089. typedef struct ma_IDirectSoundNotify ma_IDirectSoundNotify;
  19090. /*
  19091. COM objects. The way these work is that you have a vtable (a list of function pointers, kind of
  19092. like how C++ works internally), and then you have a structure with a single member, which is a
  19093. pointer to the vtable. The vtable is where the methods of the object are defined. Methods need
  19094. to be in a specific order, and parent classes need to have their methods declared first.
  19095. */
  19096. /* IDirectSound */
  19097. typedef struct
  19098. {
  19099. /* IUnknown */
  19100. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSound* pThis, const IID* const riid, void** ppObject);
  19101. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSound* pThis);
  19102. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSound* pThis);
  19103. /* IDirectSound */
  19104. HRESULT (STDMETHODCALLTYPE * CreateSoundBuffer) (ma_IDirectSound* pThis, const MA_DSBUFFERDESC* pDSBufferDesc, ma_IDirectSoundBuffer** ppDSBuffer, void* pUnkOuter);
  19105. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps);
  19106. HRESULT (STDMETHODCALLTYPE * DuplicateSoundBuffer)(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate);
  19107. HRESULT (STDMETHODCALLTYPE * SetCooperativeLevel) (ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel);
  19108. HRESULT (STDMETHODCALLTYPE * Compact) (ma_IDirectSound* pThis);
  19109. HRESULT (STDMETHODCALLTYPE * GetSpeakerConfig) (ma_IDirectSound* pThis, DWORD* pSpeakerConfig);
  19110. HRESULT (STDMETHODCALLTYPE * SetSpeakerConfig) (ma_IDirectSound* pThis, DWORD dwSpeakerConfig);
  19111. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSound* pThis, const GUID* pGuidDevice);
  19112. } ma_IDirectSoundVtbl;
  19113. struct ma_IDirectSound
  19114. {
  19115. ma_IDirectSoundVtbl* lpVtbl;
  19116. };
  19117. static MA_INLINE HRESULT ma_IDirectSound_QueryInterface(ma_IDirectSound* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19118. static MA_INLINE ULONG ma_IDirectSound_AddRef(ma_IDirectSound* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19119. static MA_INLINE ULONG ma_IDirectSound_Release(ma_IDirectSound* pThis) { return pThis->lpVtbl->Release(pThis); }
  19120. 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); }
  19121. static MA_INLINE HRESULT ma_IDirectSound_GetCaps(ma_IDirectSound* pThis, MA_DSCAPS* pDSCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCaps); }
  19122. static MA_INLINE HRESULT ma_IDirectSound_DuplicateSoundBuffer(ma_IDirectSound* pThis, ma_IDirectSoundBuffer* pDSBufferOriginal, ma_IDirectSoundBuffer** ppDSBufferDuplicate) { return pThis->lpVtbl->DuplicateSoundBuffer(pThis, pDSBufferOriginal, ppDSBufferDuplicate); }
  19123. static MA_INLINE HRESULT ma_IDirectSound_SetCooperativeLevel(ma_IDirectSound* pThis, HWND hwnd, DWORD dwLevel) { return pThis->lpVtbl->SetCooperativeLevel(pThis, hwnd, dwLevel); }
  19124. static MA_INLINE HRESULT ma_IDirectSound_Compact(ma_IDirectSound* pThis) { return pThis->lpVtbl->Compact(pThis); }
  19125. static MA_INLINE HRESULT ma_IDirectSound_GetSpeakerConfig(ma_IDirectSound* pThis, DWORD* pSpeakerConfig) { return pThis->lpVtbl->GetSpeakerConfig(pThis, pSpeakerConfig); }
  19126. static MA_INLINE HRESULT ma_IDirectSound_SetSpeakerConfig(ma_IDirectSound* pThis, DWORD dwSpeakerConfig) { return pThis->lpVtbl->SetSpeakerConfig(pThis, dwSpeakerConfig); }
  19127. static MA_INLINE HRESULT ma_IDirectSound_Initialize(ma_IDirectSound* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  19128. /* IDirectSoundBuffer */
  19129. typedef struct
  19130. {
  19131. /* IUnknown */
  19132. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject);
  19133. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundBuffer* pThis);
  19134. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundBuffer* pThis);
  19135. /* IDirectSoundBuffer */
  19136. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps);
  19137. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor);
  19138. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  19139. HRESULT (STDMETHODCALLTYPE * GetVolume) (ma_IDirectSoundBuffer* pThis, LONG* pVolume);
  19140. HRESULT (STDMETHODCALLTYPE * GetPan) (ma_IDirectSoundBuffer* pThis, LONG* pPan);
  19141. HRESULT (STDMETHODCALLTYPE * GetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD* pFrequency);
  19142. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundBuffer* pThis, DWORD* pStatus);
  19143. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc);
  19144. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  19145. HRESULT (STDMETHODCALLTYPE * Play) (ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags);
  19146. HRESULT (STDMETHODCALLTYPE * SetCurrentPosition)(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition);
  19147. HRESULT (STDMETHODCALLTYPE * SetFormat) (ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat);
  19148. HRESULT (STDMETHODCALLTYPE * SetVolume) (ma_IDirectSoundBuffer* pThis, LONG volume);
  19149. HRESULT (STDMETHODCALLTYPE * SetPan) (ma_IDirectSoundBuffer* pThis, LONG pan);
  19150. HRESULT (STDMETHODCALLTYPE * SetFrequency) (ma_IDirectSoundBuffer* pThis, DWORD dwFrequency);
  19151. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundBuffer* pThis);
  19152. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  19153. HRESULT (STDMETHODCALLTYPE * Restore) (ma_IDirectSoundBuffer* pThis);
  19154. } ma_IDirectSoundBufferVtbl;
  19155. struct ma_IDirectSoundBuffer
  19156. {
  19157. ma_IDirectSoundBufferVtbl* lpVtbl;
  19158. };
  19159. static MA_INLINE HRESULT ma_IDirectSoundBuffer_QueryInterface(ma_IDirectSoundBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19160. static MA_INLINE ULONG ma_IDirectSoundBuffer_AddRef(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19161. static MA_INLINE ULONG ma_IDirectSoundBuffer_Release(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  19162. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCaps(ma_IDirectSoundBuffer* pThis, MA_DSBCAPS* pDSBufferCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSBufferCaps); }
  19163. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD* pCurrentPlayCursor, DWORD* pCurrentWriteCursor) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCurrentPlayCursor, pCurrentWriteCursor); }
  19164. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFormat(ma_IDirectSoundBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
  19165. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetVolume(ma_IDirectSoundBuffer* pThis, LONG* pVolume) { return pThis->lpVtbl->GetVolume(pThis, pVolume); }
  19166. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetPan(ma_IDirectSoundBuffer* pThis, LONG* pPan) { return pThis->lpVtbl->GetPan(pThis, pPan); }
  19167. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetFrequency(ma_IDirectSoundBuffer* pThis, DWORD* pFrequency) { return pThis->lpVtbl->GetFrequency(pThis, pFrequency); }
  19168. static MA_INLINE HRESULT ma_IDirectSoundBuffer_GetStatus(ma_IDirectSoundBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  19169. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Initialize(ma_IDirectSoundBuffer* pThis, ma_IDirectSound* pDirectSound, const MA_DSBUFFERDESC* pDSBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSound, pDSBufferDesc); }
  19170. 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); }
  19171. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Play(ma_IDirectSoundBuffer* pThis, DWORD dwReserved1, DWORD dwPriority, DWORD dwFlags) { return pThis->lpVtbl->Play(pThis, dwReserved1, dwPriority, dwFlags); }
  19172. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetCurrentPosition(ma_IDirectSoundBuffer* pThis, DWORD dwNewPosition) { return pThis->lpVtbl->SetCurrentPosition(pThis, dwNewPosition); }
  19173. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFormat(ma_IDirectSoundBuffer* pThis, const WAVEFORMATEX* pFormat) { return pThis->lpVtbl->SetFormat(pThis, pFormat); }
  19174. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetVolume(ma_IDirectSoundBuffer* pThis, LONG volume) { return pThis->lpVtbl->SetVolume(pThis, volume); }
  19175. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetPan(ma_IDirectSoundBuffer* pThis, LONG pan) { return pThis->lpVtbl->SetPan(pThis, pan); }
  19176. static MA_INLINE HRESULT ma_IDirectSoundBuffer_SetFrequency(ma_IDirectSoundBuffer* pThis, DWORD dwFrequency) { return pThis->lpVtbl->SetFrequency(pThis, dwFrequency); }
  19177. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Stop(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  19178. 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); }
  19179. static MA_INLINE HRESULT ma_IDirectSoundBuffer_Restore(ma_IDirectSoundBuffer* pThis) { return pThis->lpVtbl->Restore(pThis); }
  19180. /* IDirectSoundCapture */
  19181. typedef struct
  19182. {
  19183. /* IUnknown */
  19184. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject);
  19185. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCapture* pThis);
  19186. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCapture* pThis);
  19187. /* IDirectSoundCapture */
  19188. HRESULT (STDMETHODCALLTYPE * CreateCaptureBuffer)(ma_IDirectSoundCapture* pThis, const MA_DSCBUFFERDESC* pDSCBufferDesc, ma_IDirectSoundCaptureBuffer** ppDSCBuffer, void* pUnkOuter);
  19189. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps);
  19190. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice);
  19191. } ma_IDirectSoundCaptureVtbl;
  19192. struct ma_IDirectSoundCapture
  19193. {
  19194. ma_IDirectSoundCaptureVtbl* lpVtbl;
  19195. };
  19196. static MA_INLINE HRESULT ma_IDirectSoundCapture_QueryInterface (ma_IDirectSoundCapture* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19197. static MA_INLINE ULONG ma_IDirectSoundCapture_AddRef (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19198. static MA_INLINE ULONG ma_IDirectSoundCapture_Release (ma_IDirectSoundCapture* pThis) { return pThis->lpVtbl->Release(pThis); }
  19199. 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); }
  19200. static MA_INLINE HRESULT ma_IDirectSoundCapture_GetCaps (ma_IDirectSoundCapture* pThis, MA_DSCCAPS* pDSCCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCCaps); }
  19201. static MA_INLINE HRESULT ma_IDirectSoundCapture_Initialize (ma_IDirectSoundCapture* pThis, const GUID* pGuidDevice) { return pThis->lpVtbl->Initialize(pThis, pGuidDevice); }
  19202. /* IDirectSoundCaptureBuffer */
  19203. typedef struct
  19204. {
  19205. /* IUnknown */
  19206. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject);
  19207. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundCaptureBuffer* pThis);
  19208. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundCaptureBuffer* pThis);
  19209. /* IDirectSoundCaptureBuffer */
  19210. HRESULT (STDMETHODCALLTYPE * GetCaps) (ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps);
  19211. HRESULT (STDMETHODCALLTYPE * GetCurrentPosition)(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition);
  19212. HRESULT (STDMETHODCALLTYPE * GetFormat) (ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten);
  19213. HRESULT (STDMETHODCALLTYPE * GetStatus) (ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus);
  19214. HRESULT (STDMETHODCALLTYPE * Initialize) (ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc);
  19215. HRESULT (STDMETHODCALLTYPE * Lock) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwOffset, DWORD dwBytes, void** ppAudioPtr1, DWORD* pAudioBytes1, void** ppAudioPtr2, DWORD* pAudioBytes2, DWORD dwFlags);
  19216. HRESULT (STDMETHODCALLTYPE * Start) (ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags);
  19217. HRESULT (STDMETHODCALLTYPE * Stop) (ma_IDirectSoundCaptureBuffer* pThis);
  19218. HRESULT (STDMETHODCALLTYPE * Unlock) (ma_IDirectSoundCaptureBuffer* pThis, void* pAudioPtr1, DWORD dwAudioBytes1, void* pAudioPtr2, DWORD dwAudioBytes2);
  19219. } ma_IDirectSoundCaptureBufferVtbl;
  19220. struct ma_IDirectSoundCaptureBuffer
  19221. {
  19222. ma_IDirectSoundCaptureBufferVtbl* lpVtbl;
  19223. };
  19224. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_QueryInterface(ma_IDirectSoundCaptureBuffer* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19225. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_AddRef(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19226. static MA_INLINE ULONG ma_IDirectSoundCaptureBuffer_Release(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Release(pThis); }
  19227. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCaps(ma_IDirectSoundCaptureBuffer* pThis, MA_DSCBCAPS* pDSCBCaps) { return pThis->lpVtbl->GetCaps(pThis, pDSCBCaps); }
  19228. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetCurrentPosition(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pCapturePosition, DWORD* pReadPosition) { return pThis->lpVtbl->GetCurrentPosition(pThis, pCapturePosition, pReadPosition); }
  19229. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetFormat(ma_IDirectSoundCaptureBuffer* pThis, WAVEFORMATEX* pFormat, DWORD dwSizeAllocated, DWORD* pSizeWritten) { return pThis->lpVtbl->GetFormat(pThis, pFormat, dwSizeAllocated, pSizeWritten); }
  19230. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_GetStatus(ma_IDirectSoundCaptureBuffer* pThis, DWORD* pStatus) { return pThis->lpVtbl->GetStatus(pThis, pStatus); }
  19231. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Initialize(ma_IDirectSoundCaptureBuffer* pThis, ma_IDirectSoundCapture* pDirectSoundCapture, const MA_DSCBUFFERDESC* pDSCBufferDesc) { return pThis->lpVtbl->Initialize(pThis, pDirectSoundCapture, pDSCBufferDesc); }
  19232. 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); }
  19233. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Start(ma_IDirectSoundCaptureBuffer* pThis, DWORD dwFlags) { return pThis->lpVtbl->Start(pThis, dwFlags); }
  19234. static MA_INLINE HRESULT ma_IDirectSoundCaptureBuffer_Stop(ma_IDirectSoundCaptureBuffer* pThis) { return pThis->lpVtbl->Stop(pThis); }
  19235. 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); }
  19236. /* IDirectSoundNotify */
  19237. typedef struct
  19238. {
  19239. /* IUnknown */
  19240. HRESULT (STDMETHODCALLTYPE * QueryInterface)(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject);
  19241. ULONG (STDMETHODCALLTYPE * AddRef) (ma_IDirectSoundNotify* pThis);
  19242. ULONG (STDMETHODCALLTYPE * Release) (ma_IDirectSoundNotify* pThis);
  19243. /* IDirectSoundNotify */
  19244. HRESULT (STDMETHODCALLTYPE * SetNotificationPositions)(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies);
  19245. } ma_IDirectSoundNotifyVtbl;
  19246. struct ma_IDirectSoundNotify
  19247. {
  19248. ma_IDirectSoundNotifyVtbl* lpVtbl;
  19249. };
  19250. static MA_INLINE HRESULT ma_IDirectSoundNotify_QueryInterface(ma_IDirectSoundNotify* pThis, const IID* const riid, void** ppObject) { return pThis->lpVtbl->QueryInterface(pThis, riid, ppObject); }
  19251. static MA_INLINE ULONG ma_IDirectSoundNotify_AddRef(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->AddRef(pThis); }
  19252. static MA_INLINE ULONG ma_IDirectSoundNotify_Release(ma_IDirectSoundNotify* pThis) { return pThis->lpVtbl->Release(pThis); }
  19253. static MA_INLINE HRESULT ma_IDirectSoundNotify_SetNotificationPositions(ma_IDirectSoundNotify* pThis, DWORD dwPositionNotifies, const MA_DSBPOSITIONNOTIFY* pPositionNotifies) { return pThis->lpVtbl->SetNotificationPositions(pThis, dwPositionNotifies, pPositionNotifies); }
  19254. typedef BOOL (CALLBACK * ma_DSEnumCallbackAProc) (LPGUID pDeviceGUID, LPCSTR pDeviceDescription, LPCSTR pModule, LPVOID pContext);
  19255. typedef HRESULT (WINAPI * ma_DirectSoundCreateProc) (const GUID* pcGuidDevice, ma_IDirectSound** ppDS8, LPUNKNOWN pUnkOuter);
  19256. typedef HRESULT (WINAPI * ma_DirectSoundEnumerateAProc) (ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext);
  19257. typedef HRESULT (WINAPI * ma_DirectSoundCaptureCreateProc) (const GUID* pcGuidDevice, ma_IDirectSoundCapture** ppDSC8, LPUNKNOWN pUnkOuter);
  19258. typedef HRESULT (WINAPI * ma_DirectSoundCaptureEnumerateAProc)(ma_DSEnumCallbackAProc pDSEnumCallback, LPVOID pContext);
  19259. static ma_uint32 ma_get_best_sample_rate_within_range(ma_uint32 sampleRateMin, ma_uint32 sampleRateMax)
  19260. {
  19261. /* Normalize the range in case we were given something stupid. */
  19262. if (sampleRateMin < (ma_uint32)ma_standard_sample_rate_min) {
  19263. sampleRateMin = (ma_uint32)ma_standard_sample_rate_min;
  19264. }
  19265. if (sampleRateMax > (ma_uint32)ma_standard_sample_rate_max) {
  19266. sampleRateMax = (ma_uint32)ma_standard_sample_rate_max;
  19267. }
  19268. if (sampleRateMin > sampleRateMax) {
  19269. sampleRateMin = sampleRateMax;
  19270. }
  19271. if (sampleRateMin == sampleRateMax) {
  19272. return sampleRateMax;
  19273. } else {
  19274. size_t iStandardRate;
  19275. for (iStandardRate = 0; iStandardRate < ma_countof(g_maStandardSampleRatePriorities); ++iStandardRate) {
  19276. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iStandardRate];
  19277. if (standardRate >= sampleRateMin && standardRate <= sampleRateMax) {
  19278. return standardRate;
  19279. }
  19280. }
  19281. }
  19282. /* Should never get here. */
  19283. MA_ASSERT(MA_FALSE);
  19284. return 0;
  19285. }
  19286. /*
  19287. Retrieves the channel count and channel map for the given speaker configuration. If the speaker configuration is unknown,
  19288. the channel count and channel map will be left unmodified.
  19289. */
  19290. static void ma_get_channels_from_speaker_config__dsound(DWORD speakerConfig, WORD* pChannelsOut, DWORD* pChannelMapOut)
  19291. {
  19292. WORD channels;
  19293. DWORD channelMap;
  19294. channels = 0;
  19295. if (pChannelsOut != NULL) {
  19296. channels = *pChannelsOut;
  19297. }
  19298. channelMap = 0;
  19299. if (pChannelMapOut != NULL) {
  19300. channelMap = *pChannelMapOut;
  19301. }
  19302. /*
  19303. The speaker configuration is a combination of speaker config and speaker geometry. The lower 8 bits is what we care about. The upper
  19304. 16 bits is for the geometry.
  19305. */
  19306. switch ((BYTE)(speakerConfig)) {
  19307. case 1 /*DSSPEAKER_HEADPHONE*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  19308. case 2 /*DSSPEAKER_MONO*/: channels = 1; channelMap = SPEAKER_FRONT_CENTER; break;
  19309. case 3 /*DSSPEAKER_QUAD*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  19310. case 4 /*DSSPEAKER_STEREO*/: channels = 2; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  19311. case 5 /*DSSPEAKER_SURROUND*/: channels = 4; channelMap = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_CENTER; break;
  19312. 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;
  19313. 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;
  19314. 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;
  19315. 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;
  19316. default: break;
  19317. }
  19318. if (pChannelsOut != NULL) {
  19319. *pChannelsOut = channels;
  19320. }
  19321. if (pChannelMapOut != NULL) {
  19322. *pChannelMapOut = channelMap;
  19323. }
  19324. }
  19325. static ma_result ma_context_create_IDirectSound__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSound** ppDirectSound)
  19326. {
  19327. ma_IDirectSound* pDirectSound;
  19328. HWND hWnd;
  19329. HRESULT hr;
  19330. MA_ASSERT(pContext != NULL);
  19331. MA_ASSERT(ppDirectSound != NULL);
  19332. *ppDirectSound = NULL;
  19333. pDirectSound = NULL;
  19334. if (FAILED(((ma_DirectSoundCreateProc)pContext->dsound.DirectSoundCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSound, NULL))) {
  19335. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCreate() failed for playback device.");
  19336. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  19337. }
  19338. /* The cooperative level must be set before doing anything else. */
  19339. hWnd = ((MA_PFN_GetForegroundWindow)pContext->win32.GetForegroundWindow)();
  19340. if (hWnd == NULL) {
  19341. hWnd = ((MA_PFN_GetDesktopWindow)pContext->win32.GetDesktopWindow)();
  19342. }
  19343. hr = ma_IDirectSound_SetCooperativeLevel(pDirectSound, hWnd, (shareMode == ma_share_mode_exclusive) ? MA_DSSCL_EXCLUSIVE : MA_DSSCL_PRIORITY);
  19344. if (FAILED(hr)) {
  19345. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_SetCooperateiveLevel() failed for playback device.");
  19346. return ma_result_from_HRESULT(hr);
  19347. }
  19348. *ppDirectSound = pDirectSound;
  19349. return MA_SUCCESS;
  19350. }
  19351. static ma_result ma_context_create_IDirectSoundCapture__dsound(ma_context* pContext, ma_share_mode shareMode, const ma_device_id* pDeviceID, ma_IDirectSoundCapture** ppDirectSoundCapture)
  19352. {
  19353. ma_IDirectSoundCapture* pDirectSoundCapture;
  19354. HRESULT hr;
  19355. MA_ASSERT(pContext != NULL);
  19356. MA_ASSERT(ppDirectSoundCapture != NULL);
  19357. /* DirectSound does not support exclusive mode for capture. */
  19358. if (shareMode == ma_share_mode_exclusive) {
  19359. return MA_SHARE_MODE_NOT_SUPPORTED;
  19360. }
  19361. *ppDirectSoundCapture = NULL;
  19362. pDirectSoundCapture = NULL;
  19363. hr = ((ma_DirectSoundCaptureCreateProc)pContext->dsound.DirectSoundCaptureCreate)((pDeviceID == NULL) ? NULL : (const GUID*)pDeviceID->dsound, &pDirectSoundCapture, NULL);
  19364. if (FAILED(hr)) {
  19365. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] DirectSoundCaptureCreate() failed for capture device.");
  19366. return ma_result_from_HRESULT(hr);
  19367. }
  19368. *ppDirectSoundCapture = pDirectSoundCapture;
  19369. return MA_SUCCESS;
  19370. }
  19371. static ma_result ma_context_get_format_info_for_IDirectSoundCapture__dsound(ma_context* pContext, ma_IDirectSoundCapture* pDirectSoundCapture, WORD* pChannels, WORD* pBitsPerSample, DWORD* pSampleRate)
  19372. {
  19373. HRESULT hr;
  19374. MA_DSCCAPS caps;
  19375. WORD bitsPerSample;
  19376. DWORD sampleRate;
  19377. MA_ASSERT(pContext != NULL);
  19378. MA_ASSERT(pDirectSoundCapture != NULL);
  19379. if (pChannels) {
  19380. *pChannels = 0;
  19381. }
  19382. if (pBitsPerSample) {
  19383. *pBitsPerSample = 0;
  19384. }
  19385. if (pSampleRate) {
  19386. *pSampleRate = 0;
  19387. }
  19388. MA_ZERO_OBJECT(&caps);
  19389. caps.dwSize = sizeof(caps);
  19390. hr = ma_IDirectSoundCapture_GetCaps(pDirectSoundCapture, &caps);
  19391. if (FAILED(hr)) {
  19392. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_GetCaps() failed for capture device.");
  19393. return ma_result_from_HRESULT(hr);
  19394. }
  19395. if (pChannels) {
  19396. *pChannels = (WORD)caps.dwChannels;
  19397. }
  19398. /* 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. */
  19399. bitsPerSample = 16;
  19400. sampleRate = 48000;
  19401. if (caps.dwChannels == 1) {
  19402. if ((caps.dwFormats & WAVE_FORMAT_48M16) != 0) {
  19403. sampleRate = 48000;
  19404. } else if ((caps.dwFormats & WAVE_FORMAT_44M16) != 0) {
  19405. sampleRate = 44100;
  19406. } else if ((caps.dwFormats & WAVE_FORMAT_2M16) != 0) {
  19407. sampleRate = 22050;
  19408. } else if ((caps.dwFormats & WAVE_FORMAT_1M16) != 0) {
  19409. sampleRate = 11025;
  19410. } else if ((caps.dwFormats & WAVE_FORMAT_96M16) != 0) {
  19411. sampleRate = 96000;
  19412. } else {
  19413. bitsPerSample = 8;
  19414. if ((caps.dwFormats & WAVE_FORMAT_48M08) != 0) {
  19415. sampleRate = 48000;
  19416. } else if ((caps.dwFormats & WAVE_FORMAT_44M08) != 0) {
  19417. sampleRate = 44100;
  19418. } else if ((caps.dwFormats & WAVE_FORMAT_2M08) != 0) {
  19419. sampleRate = 22050;
  19420. } else if ((caps.dwFormats & WAVE_FORMAT_1M08) != 0) {
  19421. sampleRate = 11025;
  19422. } else if ((caps.dwFormats & WAVE_FORMAT_96M08) != 0) {
  19423. sampleRate = 96000;
  19424. } else {
  19425. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  19426. }
  19427. }
  19428. } else if (caps.dwChannels == 2) {
  19429. if ((caps.dwFormats & WAVE_FORMAT_48S16) != 0) {
  19430. sampleRate = 48000;
  19431. } else if ((caps.dwFormats & WAVE_FORMAT_44S16) != 0) {
  19432. sampleRate = 44100;
  19433. } else if ((caps.dwFormats & WAVE_FORMAT_2S16) != 0) {
  19434. sampleRate = 22050;
  19435. } else if ((caps.dwFormats & WAVE_FORMAT_1S16) != 0) {
  19436. sampleRate = 11025;
  19437. } else if ((caps.dwFormats & WAVE_FORMAT_96S16) != 0) {
  19438. sampleRate = 96000;
  19439. } else {
  19440. bitsPerSample = 8;
  19441. if ((caps.dwFormats & WAVE_FORMAT_48S08) != 0) {
  19442. sampleRate = 48000;
  19443. } else if ((caps.dwFormats & WAVE_FORMAT_44S08) != 0) {
  19444. sampleRate = 44100;
  19445. } else if ((caps.dwFormats & WAVE_FORMAT_2S08) != 0) {
  19446. sampleRate = 22050;
  19447. } else if ((caps.dwFormats & WAVE_FORMAT_1S08) != 0) {
  19448. sampleRate = 11025;
  19449. } else if ((caps.dwFormats & WAVE_FORMAT_96S08) != 0) {
  19450. sampleRate = 96000;
  19451. } else {
  19452. bitsPerSample = 16; /* Didn't find it. Just fall back to 16-bit. */
  19453. }
  19454. }
  19455. }
  19456. if (pBitsPerSample) {
  19457. *pBitsPerSample = bitsPerSample;
  19458. }
  19459. if (pSampleRate) {
  19460. *pSampleRate = sampleRate;
  19461. }
  19462. return MA_SUCCESS;
  19463. }
  19464. typedef struct
  19465. {
  19466. ma_context* pContext;
  19467. ma_device_type deviceType;
  19468. ma_enum_devices_callback_proc callback;
  19469. void* pUserData;
  19470. ma_bool32 terminated;
  19471. } ma_context_enumerate_devices_callback_data__dsound;
  19472. static BOOL CALLBACK ma_context_enumerate_devices_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext)
  19473. {
  19474. ma_context_enumerate_devices_callback_data__dsound* pData = (ma_context_enumerate_devices_callback_data__dsound*)lpContext;
  19475. ma_device_info deviceInfo;
  19476. (void)lpcstrModule;
  19477. MA_ZERO_OBJECT(&deviceInfo);
  19478. /* ID. */
  19479. if (lpGuid != NULL) {
  19480. MA_COPY_MEMORY(deviceInfo.id.dsound, lpGuid, 16);
  19481. } else {
  19482. MA_ZERO_MEMORY(deviceInfo.id.dsound, 16);
  19483. deviceInfo.isDefault = MA_TRUE;
  19484. }
  19485. /* Name / Description */
  19486. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), lpcstrDescription, (size_t)-1);
  19487. /* Call the callback function, but make sure we stop enumerating if the callee requested so. */
  19488. MA_ASSERT(pData != NULL);
  19489. pData->terminated = !pData->callback(pData->pContext, pData->deviceType, &deviceInfo, pData->pUserData);
  19490. if (pData->terminated) {
  19491. return FALSE; /* Stop enumeration. */
  19492. } else {
  19493. return TRUE; /* Continue enumeration. */
  19494. }
  19495. }
  19496. static ma_result ma_context_enumerate_devices__dsound(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  19497. {
  19498. ma_context_enumerate_devices_callback_data__dsound data;
  19499. MA_ASSERT(pContext != NULL);
  19500. MA_ASSERT(callback != NULL);
  19501. data.pContext = pContext;
  19502. data.callback = callback;
  19503. data.pUserData = pUserData;
  19504. data.terminated = MA_FALSE;
  19505. /* Playback. */
  19506. if (!data.terminated) {
  19507. data.deviceType = ma_device_type_playback;
  19508. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  19509. }
  19510. /* Capture. */
  19511. if (!data.terminated) {
  19512. data.deviceType = ma_device_type_capture;
  19513. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_enumerate_devices_callback__dsound, &data);
  19514. }
  19515. return MA_SUCCESS;
  19516. }
  19517. typedef struct
  19518. {
  19519. const ma_device_id* pDeviceID;
  19520. ma_device_info* pDeviceInfo;
  19521. ma_bool32 found;
  19522. } ma_context_get_device_info_callback_data__dsound;
  19523. static BOOL CALLBACK ma_context_get_device_info_callback__dsound(LPGUID lpGuid, LPCSTR lpcstrDescription, LPCSTR lpcstrModule, LPVOID lpContext)
  19524. {
  19525. ma_context_get_device_info_callback_data__dsound* pData = (ma_context_get_device_info_callback_data__dsound*)lpContext;
  19526. MA_ASSERT(pData != NULL);
  19527. if ((pData->pDeviceID == NULL || ma_is_guid_null(pData->pDeviceID->dsound)) && (lpGuid == NULL || ma_is_guid_null(lpGuid))) {
  19528. /* Default device. */
  19529. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  19530. pData->pDeviceInfo->isDefault = MA_TRUE;
  19531. pData->found = MA_TRUE;
  19532. return FALSE; /* Stop enumeration. */
  19533. } else {
  19534. /* Not the default device. */
  19535. if (lpGuid != NULL && pData->pDeviceID != NULL) {
  19536. if (memcmp(pData->pDeviceID->dsound, lpGuid, sizeof(pData->pDeviceID->dsound)) == 0) {
  19537. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), lpcstrDescription, (size_t)-1);
  19538. pData->found = MA_TRUE;
  19539. return FALSE; /* Stop enumeration. */
  19540. }
  19541. }
  19542. }
  19543. (void)lpcstrModule;
  19544. return TRUE;
  19545. }
  19546. 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)
  19547. {
  19548. ma_result result;
  19549. HRESULT hr;
  19550. if (pDeviceID != NULL) {
  19551. ma_context_get_device_info_callback_data__dsound data;
  19552. /* ID. */
  19553. MA_COPY_MEMORY(pDeviceInfo->id.dsound, pDeviceID->dsound, 16);
  19554. /* Name / Description. This is retrieved by enumerating over each device until we find that one that matches the input ID. */
  19555. data.pDeviceID = pDeviceID;
  19556. data.pDeviceInfo = pDeviceInfo;
  19557. data.found = MA_FALSE;
  19558. if (deviceType == ma_device_type_playback) {
  19559. ((ma_DirectSoundEnumerateAProc)pContext->dsound.DirectSoundEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  19560. } else {
  19561. ((ma_DirectSoundCaptureEnumerateAProc)pContext->dsound.DirectSoundCaptureEnumerateA)(ma_context_get_device_info_callback__dsound, &data);
  19562. }
  19563. if (!data.found) {
  19564. return MA_NO_DEVICE;
  19565. }
  19566. } else {
  19567. /* 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. */
  19568. /* ID */
  19569. MA_ZERO_MEMORY(pDeviceInfo->id.dsound, 16);
  19570. /* Name / Description */
  19571. if (deviceType == ma_device_type_playback) {
  19572. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  19573. } else {
  19574. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  19575. }
  19576. pDeviceInfo->isDefault = MA_TRUE;
  19577. }
  19578. /* Retrieving detailed information is slightly different depending on the device type. */
  19579. if (deviceType == ma_device_type_playback) {
  19580. /* Playback. */
  19581. ma_IDirectSound* pDirectSound;
  19582. MA_DSCAPS caps;
  19583. WORD channels;
  19584. result = ma_context_create_IDirectSound__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSound);
  19585. if (result != MA_SUCCESS) {
  19586. return result;
  19587. }
  19588. MA_ZERO_OBJECT(&caps);
  19589. caps.dwSize = sizeof(caps);
  19590. hr = ma_IDirectSound_GetCaps(pDirectSound, &caps);
  19591. if (FAILED(hr)) {
  19592. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  19593. return ma_result_from_HRESULT(hr);
  19594. }
  19595. /* Channels. Only a single channel count is reported for DirectSound. */
  19596. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  19597. /* It supports at least stereo, but could support more. */
  19598. DWORD speakerConfig;
  19599. channels = 2;
  19600. /* Look at the speaker configuration to get a better idea on the channel count. */
  19601. hr = ma_IDirectSound_GetSpeakerConfig(pDirectSound, &speakerConfig);
  19602. if (SUCCEEDED(hr)) {
  19603. ma_get_channels_from_speaker_config__dsound(speakerConfig, &channels, NULL);
  19604. }
  19605. } else {
  19606. /* It does not support stereo, which means we are stuck with mono. */
  19607. channels = 1;
  19608. }
  19609. /*
  19610. In DirectSound, our native formats are centered around sample rates. All formats are supported, and we're only reporting a single channel
  19611. count. However, DirectSound can report a range of supported sample rates. We're only going to include standard rates known by miniaudio
  19612. in order to keep the size of this within reason.
  19613. */
  19614. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  19615. /* Multiple sample rates are supported. We'll report in order of our preferred sample rates. */
  19616. size_t iStandardSampleRate;
  19617. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  19618. ma_uint32 sampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  19619. if (sampleRate >= caps.dwMinSecondarySampleRate && sampleRate <= caps.dwMaxSecondarySampleRate) {
  19620. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  19621. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  19622. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  19623. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  19624. pDeviceInfo->nativeDataFormatCount += 1;
  19625. }
  19626. }
  19627. } else {
  19628. /* Only a single sample rate is supported. */
  19629. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = ma_format_unknown;
  19630. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  19631. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = caps.dwMaxSecondarySampleRate;
  19632. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  19633. pDeviceInfo->nativeDataFormatCount += 1;
  19634. }
  19635. ma_IDirectSound_Release(pDirectSound);
  19636. } else {
  19637. /*
  19638. Capture. This is a little different to playback due to the say the supported formats are reported. Technically capture
  19639. devices can support a number of different formats, but for simplicity and consistency with ma_device_init() I'm just
  19640. reporting the best format.
  19641. */
  19642. ma_IDirectSoundCapture* pDirectSoundCapture;
  19643. WORD channels;
  19644. WORD bitsPerSample;
  19645. DWORD sampleRate;
  19646. result = ma_context_create_IDirectSoundCapture__dsound(pContext, ma_share_mode_shared, pDeviceID, &pDirectSoundCapture);
  19647. if (result != MA_SUCCESS) {
  19648. return result;
  19649. }
  19650. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pContext, pDirectSoundCapture, &channels, &bitsPerSample, &sampleRate);
  19651. if (result != MA_SUCCESS) {
  19652. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  19653. return result;
  19654. }
  19655. ma_IDirectSoundCapture_Release(pDirectSoundCapture);
  19656. /* The format is always an integer format and is based on the bits per sample. */
  19657. if (bitsPerSample == 8) {
  19658. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  19659. } else if (bitsPerSample == 16) {
  19660. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  19661. } else if (bitsPerSample == 24) {
  19662. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  19663. } else if (bitsPerSample == 32) {
  19664. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  19665. } else {
  19666. return MA_FORMAT_NOT_SUPPORTED;
  19667. }
  19668. pDeviceInfo->nativeDataFormats[0].channels = channels;
  19669. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  19670. pDeviceInfo->nativeDataFormats[0].flags = 0;
  19671. pDeviceInfo->nativeDataFormatCount = 1;
  19672. }
  19673. return MA_SUCCESS;
  19674. }
  19675. static ma_result ma_device_uninit__dsound(ma_device* pDevice)
  19676. {
  19677. MA_ASSERT(pDevice != NULL);
  19678. if (pDevice->dsound.pCaptureBuffer != NULL) {
  19679. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  19680. }
  19681. if (pDevice->dsound.pCapture != NULL) {
  19682. ma_IDirectSoundCapture_Release((ma_IDirectSoundCapture*)pDevice->dsound.pCapture);
  19683. }
  19684. if (pDevice->dsound.pPlaybackBuffer != NULL) {
  19685. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  19686. }
  19687. if (pDevice->dsound.pPlaybackPrimaryBuffer != NULL) {
  19688. ma_IDirectSoundBuffer_Release((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer);
  19689. }
  19690. if (pDevice->dsound.pPlayback != NULL) {
  19691. ma_IDirectSound_Release((ma_IDirectSound*)pDevice->dsound.pPlayback);
  19692. }
  19693. return MA_SUCCESS;
  19694. }
  19695. static ma_result ma_config_to_WAVEFORMATEXTENSIBLE(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, const ma_channel* pChannelMap, WAVEFORMATEXTENSIBLE* pWF)
  19696. {
  19697. GUID subformat;
  19698. if (format == ma_format_unknown) {
  19699. format = MA_DEFAULT_FORMAT;
  19700. }
  19701. if (channels == 0) {
  19702. channels = MA_DEFAULT_CHANNELS;
  19703. }
  19704. if (sampleRate == 0) {
  19705. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  19706. }
  19707. switch (format)
  19708. {
  19709. case ma_format_u8:
  19710. case ma_format_s16:
  19711. case ma_format_s24:
  19712. /*case ma_format_s24_32:*/
  19713. case ma_format_s32:
  19714. {
  19715. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  19716. } break;
  19717. case ma_format_f32:
  19718. {
  19719. subformat = MA_GUID_KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  19720. } break;
  19721. default:
  19722. return MA_FORMAT_NOT_SUPPORTED;
  19723. }
  19724. MA_ZERO_OBJECT(pWF);
  19725. pWF->Format.cbSize = sizeof(*pWF);
  19726. pWF->Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  19727. pWF->Format.nChannels = (WORD)channels;
  19728. pWF->Format.nSamplesPerSec = (DWORD)sampleRate;
  19729. pWF->Format.wBitsPerSample = (WORD)(ma_get_bytes_per_sample(format)*8);
  19730. pWF->Format.nBlockAlign = (WORD)(pWF->Format.nChannels * pWF->Format.wBitsPerSample / 8);
  19731. pWF->Format.nAvgBytesPerSec = pWF->Format.nBlockAlign * pWF->Format.nSamplesPerSec;
  19732. pWF->Samples.wValidBitsPerSample = pWF->Format.wBitsPerSample;
  19733. pWF->dwChannelMask = ma_channel_map_to_channel_mask__win32(pChannelMap, channels);
  19734. pWF->SubFormat = subformat;
  19735. return MA_SUCCESS;
  19736. }
  19737. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__dsound(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  19738. {
  19739. /*
  19740. DirectSound has a minimum period size of 20ms. In practice, this doesn't seem to be enough for
  19741. reliable glitch-free processing so going to use 30ms instead.
  19742. */
  19743. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(30, nativeSampleRate);
  19744. ma_uint32 periodSizeInFrames;
  19745. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  19746. if (periodSizeInFrames < minPeriodSizeInFrames) {
  19747. periodSizeInFrames = minPeriodSizeInFrames;
  19748. }
  19749. return periodSizeInFrames;
  19750. }
  19751. static ma_result ma_device_init__dsound(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  19752. {
  19753. ma_result result;
  19754. HRESULT hr;
  19755. MA_ASSERT(pDevice != NULL);
  19756. MA_ZERO_OBJECT(&pDevice->dsound);
  19757. if (pConfig->deviceType == ma_device_type_loopback) {
  19758. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  19759. }
  19760. /*
  19761. Unfortunately DirectSound uses different APIs and data structures for playback and catpure devices. We need to initialize
  19762. 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
  19763. full-duplex mode.
  19764. */
  19765. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  19766. WAVEFORMATEXTENSIBLE wf;
  19767. MA_DSCBUFFERDESC descDS;
  19768. ma_uint32 periodSizeInFrames;
  19769. ma_uint32 periodCount;
  19770. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  19771. WAVEFORMATEXTENSIBLE* pActualFormat;
  19772. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &wf);
  19773. if (result != MA_SUCCESS) {
  19774. return result;
  19775. }
  19776. result = ma_context_create_IDirectSoundCapture__dsound(pDevice->pContext, pDescriptorCapture->shareMode, pDescriptorCapture->pDeviceID, (ma_IDirectSoundCapture**)&pDevice->dsound.pCapture);
  19777. if (result != MA_SUCCESS) {
  19778. ma_device_uninit__dsound(pDevice);
  19779. return result;
  19780. }
  19781. result = ma_context_get_format_info_for_IDirectSoundCapture__dsound(pDevice->pContext, (ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &wf.Format.nChannels, &wf.Format.wBitsPerSample, &wf.Format.nSamplesPerSec);
  19782. if (result != MA_SUCCESS) {
  19783. ma_device_uninit__dsound(pDevice);
  19784. return result;
  19785. }
  19786. wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
  19787. wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
  19788. wf.Samples.wValidBitsPerSample = wf.Format.wBitsPerSample;
  19789. wf.SubFormat = MA_GUID_KSDATAFORMAT_SUBTYPE_PCM;
  19790. /* The size of the buffer must be a clean multiple of the period count. */
  19791. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorCapture, wf.Format.nSamplesPerSec, pConfig->performanceProfile);
  19792. periodCount = (pDescriptorCapture->periodCount > 0) ? pDescriptorCapture->periodCount : MA_DEFAULT_PERIODS;
  19793. MA_ZERO_OBJECT(&descDS);
  19794. descDS.dwSize = sizeof(descDS);
  19795. descDS.dwFlags = 0;
  19796. descDS.dwBufferBytes = periodSizeInFrames * periodCount * wf.Format.nBlockAlign;
  19797. descDS.lpwfxFormat = (WAVEFORMATEX*)&wf;
  19798. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  19799. if (FAILED(hr)) {
  19800. ma_device_uninit__dsound(pDevice);
  19801. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  19802. return ma_result_from_HRESULT(hr);
  19803. }
  19804. /* Get the _actual_ properties of the buffer. */
  19805. pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata;
  19806. hr = ma_IDirectSoundCaptureBuffer_GetFormat((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  19807. if (FAILED(hr)) {
  19808. ma_device_uninit__dsound(pDevice);
  19809. 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.");
  19810. return ma_result_from_HRESULT(hr);
  19811. }
  19812. /* We can now start setting the output data formats. */
  19813. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
  19814. pDescriptorCapture->channels = pActualFormat->Format.nChannels;
  19815. pDescriptorCapture->sampleRate = pActualFormat->Format.nSamplesPerSec;
  19816. /* Get the native channel map based on the channel mask. */
  19817. if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  19818. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  19819. } else {
  19820. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorCapture->channels, pDescriptorCapture->channelMap);
  19821. }
  19822. /*
  19823. 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
  19824. 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.
  19825. */
  19826. if (periodSizeInFrames != (descDS.dwBufferBytes / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / periodCount)) {
  19827. descDS.dwBufferBytes = periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * periodCount;
  19828. ma_IDirectSoundCaptureBuffer_Release((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  19829. hr = ma_IDirectSoundCapture_CreateCaptureBuffer((ma_IDirectSoundCapture*)pDevice->dsound.pCapture, &descDS, (ma_IDirectSoundCaptureBuffer**)&pDevice->dsound.pCaptureBuffer, NULL);
  19830. if (FAILED(hr)) {
  19831. ma_device_uninit__dsound(pDevice);
  19832. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Second attempt at IDirectSoundCapture_CreateCaptureBuffer() failed for capture device.");
  19833. return ma_result_from_HRESULT(hr);
  19834. }
  19835. }
  19836. /* DirectSound should give us a buffer exactly the size we asked for. */
  19837. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  19838. pDescriptorCapture->periodCount = periodCount;
  19839. }
  19840. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  19841. WAVEFORMATEXTENSIBLE wf;
  19842. MA_DSBUFFERDESC descDSPrimary;
  19843. MA_DSCAPS caps;
  19844. char rawdata[1024]; /* <-- Ugly hack to avoid a malloc() due to a crappy DirectSound API. */
  19845. WAVEFORMATEXTENSIBLE* pActualFormat;
  19846. ma_uint32 periodSizeInFrames;
  19847. ma_uint32 periodCount;
  19848. MA_DSBUFFERDESC descDS;
  19849. result = ma_config_to_WAVEFORMATEXTENSIBLE(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &wf);
  19850. if (result != MA_SUCCESS) {
  19851. return result;
  19852. }
  19853. result = ma_context_create_IDirectSound__dsound(pDevice->pContext, pDescriptorPlayback->shareMode, pDescriptorPlayback->pDeviceID, (ma_IDirectSound**)&pDevice->dsound.pPlayback);
  19854. if (result != MA_SUCCESS) {
  19855. ma_device_uninit__dsound(pDevice);
  19856. return result;
  19857. }
  19858. MA_ZERO_OBJECT(&descDSPrimary);
  19859. descDSPrimary.dwSize = sizeof(MA_DSBUFFERDESC);
  19860. descDSPrimary.dwFlags = MA_DSBCAPS_PRIMARYBUFFER | MA_DSBCAPS_CTRLVOLUME;
  19861. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDSPrimary, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackPrimaryBuffer, NULL);
  19862. if (FAILED(hr)) {
  19863. ma_device_uninit__dsound(pDevice);
  19864. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's primary buffer.");
  19865. return ma_result_from_HRESULT(hr);
  19866. }
  19867. /* We may want to make some adjustments to the format if we are using defaults. */
  19868. MA_ZERO_OBJECT(&caps);
  19869. caps.dwSize = sizeof(caps);
  19870. hr = ma_IDirectSound_GetCaps((ma_IDirectSound*)pDevice->dsound.pPlayback, &caps);
  19871. if (FAILED(hr)) {
  19872. ma_device_uninit__dsound(pDevice);
  19873. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_GetCaps() failed for playback device.");
  19874. return ma_result_from_HRESULT(hr);
  19875. }
  19876. if (pDescriptorPlayback->channels == 0) {
  19877. if ((caps.dwFlags & MA_DSCAPS_PRIMARYSTEREO) != 0) {
  19878. DWORD speakerConfig;
  19879. /* It supports at least stereo, but could support more. */
  19880. wf.Format.nChannels = 2;
  19881. /* Look at the speaker configuration to get a better idea on the channel count. */
  19882. if (SUCCEEDED(ma_IDirectSound_GetSpeakerConfig((ma_IDirectSound*)pDevice->dsound.pPlayback, &speakerConfig))) {
  19883. ma_get_channels_from_speaker_config__dsound(speakerConfig, &wf.Format.nChannels, &wf.dwChannelMask);
  19884. }
  19885. } else {
  19886. /* It does not support stereo, which means we are stuck with mono. */
  19887. wf.Format.nChannels = 1;
  19888. }
  19889. }
  19890. if (pDescriptorPlayback->sampleRate == 0) {
  19891. /* We base the sample rate on the values returned by GetCaps(). */
  19892. if ((caps.dwFlags & MA_DSCAPS_CONTINUOUSRATE) != 0) {
  19893. wf.Format.nSamplesPerSec = ma_get_best_sample_rate_within_range(caps.dwMinSecondarySampleRate, caps.dwMaxSecondarySampleRate);
  19894. } else {
  19895. wf.Format.nSamplesPerSec = caps.dwMaxSecondarySampleRate;
  19896. }
  19897. }
  19898. wf.Format.nBlockAlign = (WORD)(wf.Format.nChannels * wf.Format.wBitsPerSample / 8);
  19899. wf.Format.nAvgBytesPerSec = wf.Format.nBlockAlign * wf.Format.nSamplesPerSec;
  19900. /*
  19901. From MSDN:
  19902. The method succeeds even if the hardware does not support the requested format; DirectSound sets the buffer to the closest
  19903. supported format. To determine whether this has happened, an application can call the GetFormat method for the primary buffer
  19904. and compare the result with the format that was requested with the SetFormat method.
  19905. */
  19906. hr = ma_IDirectSoundBuffer_SetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)&wf);
  19907. if (FAILED(hr)) {
  19908. ma_device_uninit__dsound(pDevice);
  19909. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] Failed to set format of playback device's primary buffer.");
  19910. return ma_result_from_HRESULT(hr);
  19911. }
  19912. /* Get the _actual_ properties of the buffer. */
  19913. pActualFormat = (WAVEFORMATEXTENSIBLE*)rawdata;
  19914. hr = ma_IDirectSoundBuffer_GetFormat((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackPrimaryBuffer, (WAVEFORMATEX*)pActualFormat, sizeof(rawdata), NULL);
  19915. if (FAILED(hr)) {
  19916. ma_device_uninit__dsound(pDevice);
  19917. 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.");
  19918. return ma_result_from_HRESULT(hr);
  19919. }
  19920. /* We now have enough information to start setting some output properties. */
  19921. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX((WAVEFORMATEX*)pActualFormat);
  19922. pDescriptorPlayback->channels = pActualFormat->Format.nChannels;
  19923. pDescriptorPlayback->sampleRate = pActualFormat->Format.nSamplesPerSec;
  19924. /* Get the internal channel map based on the channel mask. */
  19925. if (pActualFormat->Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE) {
  19926. ma_channel_mask_to_channel_map__win32(pActualFormat->dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  19927. } else {
  19928. ma_channel_mask_to_channel_map__win32(wf.dwChannelMask, pDescriptorPlayback->channels, pDescriptorPlayback->channelMap);
  19929. }
  19930. /* The size of the buffer must be a clean multiple of the period count. */
  19931. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__dsound(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  19932. periodCount = (pDescriptorPlayback->periodCount > 0) ? pDescriptorPlayback->periodCount : MA_DEFAULT_PERIODS;
  19933. /*
  19934. Meaning of dwFlags (from MSDN):
  19935. DSBCAPS_CTRLPOSITIONNOTIFY
  19936. The buffer has position notification capability.
  19937. DSBCAPS_GLOBALFOCUS
  19938. With this flag set, an application using DirectSound can continue to play its buffers if the user switches focus to
  19939. another application, even if the new application uses DirectSound.
  19940. DSBCAPS_GETCURRENTPOSITION2
  19941. In the first version of DirectSound, the play cursor was significantly ahead of the actual playing sound on emulated
  19942. sound cards; it was directly behind the write cursor. Now, if the DSBCAPS_GETCURRENTPOSITION2 flag is specified, the
  19943. application can get a more accurate play cursor.
  19944. */
  19945. MA_ZERO_OBJECT(&descDS);
  19946. descDS.dwSize = sizeof(descDS);
  19947. descDS.dwFlags = MA_DSBCAPS_CTRLPOSITIONNOTIFY | MA_DSBCAPS_GLOBALFOCUS | MA_DSBCAPS_GETCURRENTPOSITION2;
  19948. descDS.dwBufferBytes = periodSizeInFrames * periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels);
  19949. descDS.lpwfxFormat = (WAVEFORMATEX*)&wf;
  19950. hr = ma_IDirectSound_CreateSoundBuffer((ma_IDirectSound*)pDevice->dsound.pPlayback, &descDS, (ma_IDirectSoundBuffer**)&pDevice->dsound.pPlaybackBuffer, NULL);
  19951. if (FAILED(hr)) {
  19952. ma_device_uninit__dsound(pDevice);
  19953. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSound_CreateSoundBuffer() failed for playback device's secondary buffer.");
  19954. return ma_result_from_HRESULT(hr);
  19955. }
  19956. /* DirectSound should give us a buffer exactly the size we asked for. */
  19957. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  19958. pDescriptorPlayback->periodCount = periodCount;
  19959. }
  19960. return MA_SUCCESS;
  19961. }
  19962. static ma_result ma_device_data_loop__dsound(ma_device* pDevice)
  19963. {
  19964. ma_result result = MA_SUCCESS;
  19965. ma_uint32 bpfDeviceCapture = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  19966. ma_uint32 bpfDevicePlayback = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  19967. HRESULT hr;
  19968. DWORD lockOffsetInBytesCapture;
  19969. DWORD lockSizeInBytesCapture;
  19970. DWORD mappedSizeInBytesCapture;
  19971. DWORD mappedDeviceFramesProcessedCapture;
  19972. void* pMappedDeviceBufferCapture;
  19973. DWORD lockOffsetInBytesPlayback;
  19974. DWORD lockSizeInBytesPlayback;
  19975. DWORD mappedSizeInBytesPlayback;
  19976. void* pMappedDeviceBufferPlayback;
  19977. DWORD prevReadCursorInBytesCapture = 0;
  19978. DWORD prevPlayCursorInBytesPlayback = 0;
  19979. ma_bool32 physicalPlayCursorLoopFlagPlayback = 0;
  19980. DWORD virtualWriteCursorInBytesPlayback = 0;
  19981. ma_bool32 virtualWriteCursorLoopFlagPlayback = 0;
  19982. ma_bool32 isPlaybackDeviceStarted = MA_FALSE;
  19983. ma_uint32 framesWrittenToPlaybackDevice = 0; /* For knowing whether or not the playback device needs to be started. */
  19984. ma_uint32 waitTimeInMilliseconds = 1;
  19985. MA_ASSERT(pDevice != NULL);
  19986. /* The first thing to do is start the capture device. The playback device is only started after the first period is written. */
  19987. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  19988. hr = ma_IDirectSoundCaptureBuffer_Start((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, MA_DSCBSTART_LOOPING);
  19989. if (FAILED(hr)) {
  19990. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Start() failed.");
  19991. return ma_result_from_HRESULT(hr);
  19992. }
  19993. }
  19994. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  19995. switch (pDevice->type)
  19996. {
  19997. case ma_device_type_duplex:
  19998. {
  19999. DWORD physicalCaptureCursorInBytes;
  20000. DWORD physicalReadCursorInBytes;
  20001. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  20002. if (FAILED(hr)) {
  20003. return ma_result_from_HRESULT(hr);
  20004. }
  20005. /* If nothing is available we just sleep for a bit and return from this iteration. */
  20006. if (physicalReadCursorInBytes == prevReadCursorInBytesCapture) {
  20007. ma_sleep(waitTimeInMilliseconds);
  20008. continue; /* Nothing is available in the capture buffer. */
  20009. }
  20010. /*
  20011. The current position has moved. We need to map all of the captured samples and write them to the playback device, making sure
  20012. we don't return until every frame has been copied over.
  20013. */
  20014. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  20015. /* The capture position has not looped. This is the simple case. */
  20016. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20017. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  20018. } else {
  20019. /*
  20020. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  20021. do it again from the start.
  20022. */
  20023. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  20024. /* Lock up to the end of the buffer. */
  20025. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20026. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  20027. } else {
  20028. /* Lock starting from the start of the buffer. */
  20029. lockOffsetInBytesCapture = 0;
  20030. lockSizeInBytesCapture = physicalReadCursorInBytes;
  20031. }
  20032. }
  20033. if (lockSizeInBytesCapture == 0) {
  20034. ma_sleep(waitTimeInMilliseconds);
  20035. continue; /* Nothing is available in the capture buffer. */
  20036. }
  20037. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  20038. if (FAILED(hr)) {
  20039. 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.");
  20040. return ma_result_from_HRESULT(hr);
  20041. }
  20042. /* 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. */
  20043. mappedDeviceFramesProcessedCapture = 0;
  20044. for (;;) { /* Keep writing to the playback device. */
  20045. ma_uint8 inputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20046. ma_uint32 inputFramesInClientFormatCap = sizeof(inputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  20047. ma_uint8 outputFramesInClientFormat[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  20048. ma_uint32 outputFramesInClientFormatCap = sizeof(outputFramesInClientFormat) / ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  20049. ma_uint32 outputFramesInClientFormatCount;
  20050. ma_uint32 outputFramesInClientFormatConsumed = 0;
  20051. ma_uint64 clientCapturedFramesToProcess = ma_min(inputFramesInClientFormatCap, outputFramesInClientFormatCap);
  20052. ma_uint64 deviceCapturedFramesToProcess = (mappedSizeInBytesCapture / bpfDeviceCapture) - mappedDeviceFramesProcessedCapture;
  20053. void* pRunningMappedDeviceBufferCapture = ma_offset_ptr(pMappedDeviceBufferCapture, mappedDeviceFramesProcessedCapture * bpfDeviceCapture);
  20054. result = ma_data_converter_process_pcm_frames(&pDevice->capture.converter, pRunningMappedDeviceBufferCapture, &deviceCapturedFramesToProcess, inputFramesInClientFormat, &clientCapturedFramesToProcess);
  20055. if (result != MA_SUCCESS) {
  20056. break;
  20057. }
  20058. outputFramesInClientFormatCount = (ma_uint32)clientCapturedFramesToProcess;
  20059. mappedDeviceFramesProcessedCapture += (ma_uint32)deviceCapturedFramesToProcess;
  20060. ma_device__handle_data_callback(pDevice, outputFramesInClientFormat, inputFramesInClientFormat, (ma_uint32)clientCapturedFramesToProcess);
  20061. /* 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. */
  20062. for (;;) {
  20063. ma_uint32 framesWrittenThisIteration;
  20064. DWORD physicalPlayCursorInBytes;
  20065. DWORD physicalWriteCursorInBytes;
  20066. DWORD availableBytesPlayback;
  20067. DWORD silentPaddingInBytes = 0; /* <-- Must be initialized to 0. */
  20068. /* We need the physical play and write cursors. */
  20069. if (FAILED(ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes))) {
  20070. break;
  20071. }
  20072. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  20073. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  20074. }
  20075. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  20076. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  20077. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20078. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  20079. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  20080. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20081. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  20082. } else {
  20083. /* This is an error. */
  20084. 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);
  20085. availableBytesPlayback = 0;
  20086. }
  20087. } else {
  20088. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  20089. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  20090. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20091. } else {
  20092. /* This is an error. */
  20093. 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);
  20094. availableBytesPlayback = 0;
  20095. }
  20096. }
  20097. /* If there's no room available for writing we need to wait for more. */
  20098. if (availableBytesPlayback == 0) {
  20099. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  20100. if (!isPlaybackDeviceStarted) {
  20101. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20102. if (FAILED(hr)) {
  20103. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20104. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20105. return ma_result_from_HRESULT(hr);
  20106. }
  20107. isPlaybackDeviceStarted = MA_TRUE;
  20108. } else {
  20109. ma_sleep(waitTimeInMilliseconds);
  20110. continue;
  20111. }
  20112. }
  20113. /* 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. */
  20114. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  20115. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20116. /* Same loop iteration. Go up to the end of the buffer. */
  20117. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20118. } else {
  20119. /* Different loop iterations. Go up to the physical play cursor. */
  20120. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20121. }
  20122. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  20123. if (FAILED(hr)) {
  20124. 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.");
  20125. result = ma_result_from_HRESULT(hr);
  20126. break;
  20127. }
  20128. /*
  20129. 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
  20130. endless glitching due to it constantly running out of data.
  20131. */
  20132. if (isPlaybackDeviceStarted) {
  20133. DWORD bytesQueuedForPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - availableBytesPlayback;
  20134. if (bytesQueuedForPlayback < (pDevice->playback.internalPeriodSizeInFrames*bpfDevicePlayback)) {
  20135. silentPaddingInBytes = (pDevice->playback.internalPeriodSizeInFrames*2*bpfDevicePlayback) - bytesQueuedForPlayback;
  20136. if (silentPaddingInBytes > lockSizeInBytesPlayback) {
  20137. silentPaddingInBytes = lockSizeInBytesPlayback;
  20138. }
  20139. 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);
  20140. }
  20141. }
  20142. /* At this point we have a buffer for output. */
  20143. if (silentPaddingInBytes > 0) {
  20144. MA_ZERO_MEMORY(pMappedDeviceBufferPlayback, silentPaddingInBytes);
  20145. framesWrittenThisIteration = silentPaddingInBytes/bpfDevicePlayback;
  20146. } else {
  20147. ma_uint64 convertedFrameCountIn = (outputFramesInClientFormatCount - outputFramesInClientFormatConsumed);
  20148. ma_uint64 convertedFrameCountOut = mappedSizeInBytesPlayback/bpfDevicePlayback;
  20149. void* pConvertedFramesIn = ma_offset_ptr(outputFramesInClientFormat, outputFramesInClientFormatConsumed * bpfDevicePlayback);
  20150. void* pConvertedFramesOut = pMappedDeviceBufferPlayback;
  20151. result = ma_data_converter_process_pcm_frames(&pDevice->playback.converter, pConvertedFramesIn, &convertedFrameCountIn, pConvertedFramesOut, &convertedFrameCountOut);
  20152. if (result != MA_SUCCESS) {
  20153. break;
  20154. }
  20155. outputFramesInClientFormatConsumed += (ma_uint32)convertedFrameCountOut;
  20156. framesWrittenThisIteration = (ma_uint32)convertedFrameCountOut;
  20157. }
  20158. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, framesWrittenThisIteration*bpfDevicePlayback, NULL, 0);
  20159. if (FAILED(hr)) {
  20160. 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.");
  20161. result = ma_result_from_HRESULT(hr);
  20162. break;
  20163. }
  20164. virtualWriteCursorInBytesPlayback += framesWrittenThisIteration*bpfDevicePlayback;
  20165. if ((virtualWriteCursorInBytesPlayback/bpfDevicePlayback) == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods) {
  20166. virtualWriteCursorInBytesPlayback = 0;
  20167. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  20168. }
  20169. /*
  20170. 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
  20171. a bit of a buffer to prevent the playback buffer from getting starved.
  20172. */
  20173. framesWrittenToPlaybackDevice += framesWrittenThisIteration;
  20174. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= (pDevice->playback.internalPeriodSizeInFrames*2)) {
  20175. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20176. if (FAILED(hr)) {
  20177. ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20178. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20179. return ma_result_from_HRESULT(hr);
  20180. }
  20181. isPlaybackDeviceStarted = MA_TRUE;
  20182. }
  20183. if (framesWrittenThisIteration < mappedSizeInBytesPlayback/bpfDevicePlayback) {
  20184. break; /* We're finished with the output data.*/
  20185. }
  20186. }
  20187. if (clientCapturedFramesToProcess == 0) {
  20188. break; /* We just consumed every input sample. */
  20189. }
  20190. }
  20191. /* At this point we're done with the mapped portion of the capture buffer. */
  20192. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  20193. if (FAILED(hr)) {
  20194. 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.");
  20195. return ma_result_from_HRESULT(hr);
  20196. }
  20197. prevReadCursorInBytesCapture = (lockOffsetInBytesCapture + mappedSizeInBytesCapture);
  20198. } break;
  20199. case ma_device_type_capture:
  20200. {
  20201. DWORD physicalCaptureCursorInBytes;
  20202. DWORD physicalReadCursorInBytes;
  20203. hr = ma_IDirectSoundCaptureBuffer_GetCurrentPosition((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, &physicalCaptureCursorInBytes, &physicalReadCursorInBytes);
  20204. if (FAILED(hr)) {
  20205. return MA_ERROR;
  20206. }
  20207. /* If the previous capture position is the same as the current position we need to wait a bit longer. */
  20208. if (prevReadCursorInBytesCapture == physicalReadCursorInBytes) {
  20209. ma_sleep(waitTimeInMilliseconds);
  20210. continue;
  20211. }
  20212. /* Getting here means we have capture data available. */
  20213. if (prevReadCursorInBytesCapture < physicalReadCursorInBytes) {
  20214. /* The capture position has not looped. This is the simple case. */
  20215. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20216. lockSizeInBytesCapture = (physicalReadCursorInBytes - prevReadCursorInBytesCapture);
  20217. } else {
  20218. /*
  20219. The capture position has looped. This is the more complex case. Map to the end of the buffer. If this does not return anything,
  20220. do it again from the start.
  20221. */
  20222. if (prevReadCursorInBytesCapture < pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) {
  20223. /* Lock up to the end of the buffer. */
  20224. lockOffsetInBytesCapture = prevReadCursorInBytesCapture;
  20225. lockSizeInBytesCapture = (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture) - prevReadCursorInBytesCapture;
  20226. } else {
  20227. /* Lock starting from the start of the buffer. */
  20228. lockOffsetInBytesCapture = 0;
  20229. lockSizeInBytesCapture = physicalReadCursorInBytes;
  20230. }
  20231. }
  20232. if (lockSizeInBytesCapture < pDevice->capture.internalPeriodSizeInFrames) {
  20233. ma_sleep(waitTimeInMilliseconds);
  20234. continue; /* Nothing is available in the capture buffer. */
  20235. }
  20236. hr = ma_IDirectSoundCaptureBuffer_Lock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, lockOffsetInBytesCapture, lockSizeInBytesCapture, &pMappedDeviceBufferCapture, &mappedSizeInBytesCapture, NULL, NULL, 0);
  20237. if (FAILED(hr)) {
  20238. 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.");
  20239. result = ma_result_from_HRESULT(hr);
  20240. }
  20241. if (lockSizeInBytesCapture != mappedSizeInBytesCapture) {
  20242. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[DirectSound] (Capture) lockSizeInBytesCapture=%ld != mappedSizeInBytesCapture=%ld\n", lockSizeInBytesCapture, mappedSizeInBytesCapture);
  20243. }
  20244. ma_device__send_frames_to_client(pDevice, mappedSizeInBytesCapture/bpfDeviceCapture, pMappedDeviceBufferCapture);
  20245. hr = ma_IDirectSoundCaptureBuffer_Unlock((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer, pMappedDeviceBufferCapture, mappedSizeInBytesCapture, NULL, 0);
  20246. if (FAILED(hr)) {
  20247. 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.");
  20248. return ma_result_from_HRESULT(hr);
  20249. }
  20250. prevReadCursorInBytesCapture = lockOffsetInBytesCapture + mappedSizeInBytesCapture;
  20251. if (prevReadCursorInBytesCapture == (pDevice->capture.internalPeriodSizeInFrames*pDevice->capture.internalPeriods*bpfDeviceCapture)) {
  20252. prevReadCursorInBytesCapture = 0;
  20253. }
  20254. } break;
  20255. case ma_device_type_playback:
  20256. {
  20257. DWORD availableBytesPlayback;
  20258. DWORD physicalPlayCursorInBytes;
  20259. DWORD physicalWriteCursorInBytes;
  20260. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  20261. if (FAILED(hr)) {
  20262. break;
  20263. }
  20264. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  20265. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  20266. }
  20267. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  20268. /* If there's any bytes available for writing we can do that now. The space between the virtual cursor position and play cursor. */
  20269. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20270. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  20271. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  20272. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20273. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  20274. } else {
  20275. /* This is an error. */
  20276. 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);
  20277. availableBytesPlayback = 0;
  20278. }
  20279. } else {
  20280. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  20281. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  20282. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20283. } else {
  20284. /* This is an error. */
  20285. 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);
  20286. availableBytesPlayback = 0;
  20287. }
  20288. }
  20289. /* If there's no room available for writing we need to wait for more. */
  20290. if (availableBytesPlayback < pDevice->playback.internalPeriodSizeInFrames) {
  20291. /* If we haven't started the device yet, this will never get beyond 0. In this case we need to get the device started. */
  20292. if (availableBytesPlayback == 0 && !isPlaybackDeviceStarted) {
  20293. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20294. if (FAILED(hr)) {
  20295. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20296. return ma_result_from_HRESULT(hr);
  20297. }
  20298. isPlaybackDeviceStarted = MA_TRUE;
  20299. } else {
  20300. ma_sleep(waitTimeInMilliseconds);
  20301. continue;
  20302. }
  20303. }
  20304. /* 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. */
  20305. lockOffsetInBytesPlayback = virtualWriteCursorInBytesPlayback;
  20306. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20307. /* Same loop iteration. Go up to the end of the buffer. */
  20308. lockSizeInBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20309. } else {
  20310. /* Different loop iterations. Go up to the physical play cursor. */
  20311. lockSizeInBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20312. }
  20313. hr = ma_IDirectSoundBuffer_Lock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, lockOffsetInBytesPlayback, lockSizeInBytesPlayback, &pMappedDeviceBufferPlayback, &mappedSizeInBytesPlayback, NULL, NULL, 0);
  20314. if (FAILED(hr)) {
  20315. 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.");
  20316. result = ma_result_from_HRESULT(hr);
  20317. break;
  20318. }
  20319. /* At this point we have a buffer for output. */
  20320. ma_device__read_frames_from_client(pDevice, (mappedSizeInBytesPlayback/bpfDevicePlayback), pMappedDeviceBufferPlayback);
  20321. hr = ma_IDirectSoundBuffer_Unlock((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, pMappedDeviceBufferPlayback, mappedSizeInBytesPlayback, NULL, 0);
  20322. if (FAILED(hr)) {
  20323. 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.");
  20324. result = ma_result_from_HRESULT(hr);
  20325. break;
  20326. }
  20327. virtualWriteCursorInBytesPlayback += mappedSizeInBytesPlayback;
  20328. if (virtualWriteCursorInBytesPlayback == pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) {
  20329. virtualWriteCursorInBytesPlayback = 0;
  20330. virtualWriteCursorLoopFlagPlayback = !virtualWriteCursorLoopFlagPlayback;
  20331. }
  20332. /*
  20333. 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
  20334. a bit of a buffer to prevent the playback buffer from getting starved.
  20335. */
  20336. framesWrittenToPlaybackDevice += mappedSizeInBytesPlayback/bpfDevicePlayback;
  20337. if (!isPlaybackDeviceStarted && framesWrittenToPlaybackDevice >= pDevice->playback.internalPeriodSizeInFrames) {
  20338. hr = ma_IDirectSoundBuffer_Play((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0, 0, MA_DSBPLAY_LOOPING);
  20339. if (FAILED(hr)) {
  20340. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Play() failed.");
  20341. return ma_result_from_HRESULT(hr);
  20342. }
  20343. isPlaybackDeviceStarted = MA_TRUE;
  20344. }
  20345. } break;
  20346. default: return MA_INVALID_ARGS; /* Invalid device type. */
  20347. }
  20348. if (result != MA_SUCCESS) {
  20349. return result;
  20350. }
  20351. }
  20352. /* Getting here means the device is being stopped. */
  20353. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  20354. hr = ma_IDirectSoundCaptureBuffer_Stop((ma_IDirectSoundCaptureBuffer*)pDevice->dsound.pCaptureBuffer);
  20355. if (FAILED(hr)) {
  20356. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundCaptureBuffer_Stop() failed.");
  20357. return ma_result_from_HRESULT(hr);
  20358. }
  20359. }
  20360. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  20361. /* 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. */
  20362. if (isPlaybackDeviceStarted) {
  20363. for (;;) {
  20364. DWORD availableBytesPlayback = 0;
  20365. DWORD physicalPlayCursorInBytes;
  20366. DWORD physicalWriteCursorInBytes;
  20367. hr = ma_IDirectSoundBuffer_GetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, &physicalPlayCursorInBytes, &physicalWriteCursorInBytes);
  20368. if (FAILED(hr)) {
  20369. break;
  20370. }
  20371. if (physicalPlayCursorInBytes < prevPlayCursorInBytesPlayback) {
  20372. physicalPlayCursorLoopFlagPlayback = !physicalPlayCursorLoopFlagPlayback;
  20373. }
  20374. prevPlayCursorInBytesPlayback = physicalPlayCursorInBytes;
  20375. if (physicalPlayCursorLoopFlagPlayback == virtualWriteCursorLoopFlagPlayback) {
  20376. /* Same loop iteration. The available bytes wraps all the way around from the virtual write cursor to the physical play cursor. */
  20377. if (physicalPlayCursorInBytes <= virtualWriteCursorInBytesPlayback) {
  20378. availableBytesPlayback = (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback) - virtualWriteCursorInBytesPlayback;
  20379. availableBytesPlayback += physicalPlayCursorInBytes; /* Wrap around. */
  20380. } else {
  20381. break;
  20382. }
  20383. } else {
  20384. /* Different loop iterations. The available bytes only goes from the virtual write cursor to the physical play cursor. */
  20385. if (physicalPlayCursorInBytes >= virtualWriteCursorInBytesPlayback) {
  20386. availableBytesPlayback = physicalPlayCursorInBytes - virtualWriteCursorInBytesPlayback;
  20387. } else {
  20388. break;
  20389. }
  20390. }
  20391. if (availableBytesPlayback >= (pDevice->playback.internalPeriodSizeInFrames*pDevice->playback.internalPeriods*bpfDevicePlayback)) {
  20392. break;
  20393. }
  20394. ma_sleep(waitTimeInMilliseconds);
  20395. }
  20396. }
  20397. hr = ma_IDirectSoundBuffer_Stop((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer);
  20398. if (FAILED(hr)) {
  20399. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[DirectSound] IDirectSoundBuffer_Stop() failed.");
  20400. return ma_result_from_HRESULT(hr);
  20401. }
  20402. ma_IDirectSoundBuffer_SetCurrentPosition((ma_IDirectSoundBuffer*)pDevice->dsound.pPlaybackBuffer, 0);
  20403. }
  20404. return MA_SUCCESS;
  20405. }
  20406. static ma_result ma_context_uninit__dsound(ma_context* pContext)
  20407. {
  20408. MA_ASSERT(pContext != NULL);
  20409. MA_ASSERT(pContext->backend == ma_backend_dsound);
  20410. ma_dlclose(pContext, pContext->dsound.hDSoundDLL);
  20411. return MA_SUCCESS;
  20412. }
  20413. static ma_result ma_context_init__dsound(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  20414. {
  20415. MA_ASSERT(pContext != NULL);
  20416. (void)pConfig;
  20417. pContext->dsound.hDSoundDLL = ma_dlopen(pContext, "dsound.dll");
  20418. if (pContext->dsound.hDSoundDLL == NULL) {
  20419. return MA_API_NOT_FOUND;
  20420. }
  20421. pContext->dsound.DirectSoundCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCreate");
  20422. pContext->dsound.DirectSoundEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundEnumerateA");
  20423. pContext->dsound.DirectSoundCaptureCreate = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureCreate");
  20424. pContext->dsound.DirectSoundCaptureEnumerateA = ma_dlsym(pContext, pContext->dsound.hDSoundDLL, "DirectSoundCaptureEnumerateA");
  20425. pCallbacks->onContextInit = ma_context_init__dsound;
  20426. pCallbacks->onContextUninit = ma_context_uninit__dsound;
  20427. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__dsound;
  20428. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__dsound;
  20429. pCallbacks->onDeviceInit = ma_device_init__dsound;
  20430. pCallbacks->onDeviceUninit = ma_device_uninit__dsound;
  20431. pCallbacks->onDeviceStart = NULL; /* Not used. Started in onDeviceDataLoop. */
  20432. pCallbacks->onDeviceStop = NULL; /* Not used. Stopped in onDeviceDataLoop. */
  20433. pCallbacks->onDeviceRead = NULL; /* Not used. Data is read directly in onDeviceDataLoop. */
  20434. pCallbacks->onDeviceWrite = NULL; /* Not used. Data is written directly in onDeviceDataLoop. */
  20435. pCallbacks->onDeviceDataLoop = ma_device_data_loop__dsound;
  20436. return MA_SUCCESS;
  20437. }
  20438. #endif
  20439. /******************************************************************************
  20440. WinMM Backend
  20441. ******************************************************************************/
  20442. #ifdef MA_HAS_WINMM
  20443. /*
  20444. Some older compilers don't have WAVEOUTCAPS2A and WAVEINCAPS2A, so we'll need to write this ourselves. These structures
  20445. are exactly the same as the older ones but they have a few GUIDs for manufacturer/product/name identification. I'm keeping
  20446. the names the same as the Win32 library for consistency, but namespaced to avoid naming conflicts with the Win32 version.
  20447. */
  20448. typedef struct
  20449. {
  20450. WORD wMid;
  20451. WORD wPid;
  20452. MMVERSION vDriverVersion;
  20453. CHAR szPname[MAXPNAMELEN];
  20454. DWORD dwFormats;
  20455. WORD wChannels;
  20456. WORD wReserved1;
  20457. DWORD dwSupport;
  20458. GUID ManufacturerGuid;
  20459. GUID ProductGuid;
  20460. GUID NameGuid;
  20461. } MA_WAVEOUTCAPS2A;
  20462. typedef struct
  20463. {
  20464. WORD wMid;
  20465. WORD wPid;
  20466. MMVERSION vDriverVersion;
  20467. CHAR szPname[MAXPNAMELEN];
  20468. DWORD dwFormats;
  20469. WORD wChannels;
  20470. WORD wReserved1;
  20471. GUID ManufacturerGuid;
  20472. GUID ProductGuid;
  20473. GUID NameGuid;
  20474. } MA_WAVEINCAPS2A;
  20475. typedef UINT (WINAPI * MA_PFN_waveOutGetNumDevs)(void);
  20476. typedef MMRESULT (WINAPI * MA_PFN_waveOutGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEOUTCAPSA pwoc, UINT cbwoc);
  20477. typedef MMRESULT (WINAPI * MA_PFN_waveOutOpen)(LPHWAVEOUT phwo, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  20478. typedef MMRESULT (WINAPI * MA_PFN_waveOutClose)(HWAVEOUT hwo);
  20479. typedef MMRESULT (WINAPI * MA_PFN_waveOutPrepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
  20480. typedef MMRESULT (WINAPI * MA_PFN_waveOutUnprepareHeader)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
  20481. typedef MMRESULT (WINAPI * MA_PFN_waveOutWrite)(HWAVEOUT hwo, LPWAVEHDR pwh, UINT cbwh);
  20482. typedef MMRESULT (WINAPI * MA_PFN_waveOutReset)(HWAVEOUT hwo);
  20483. typedef UINT (WINAPI * MA_PFN_waveInGetNumDevs)(void);
  20484. typedef MMRESULT (WINAPI * MA_PFN_waveInGetDevCapsA)(ma_uintptr uDeviceID, LPWAVEINCAPSA pwic, UINT cbwic);
  20485. typedef MMRESULT (WINAPI * MA_PFN_waveInOpen)(LPHWAVEIN phwi, UINT uDeviceID, LPCWAVEFORMATEX pwfx, DWORD_PTR dwCallback, DWORD_PTR dwInstance, DWORD fdwOpen);
  20486. typedef MMRESULT (WINAPI * MA_PFN_waveInClose)(HWAVEIN hwi);
  20487. typedef MMRESULT (WINAPI * MA_PFN_waveInPrepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
  20488. typedef MMRESULT (WINAPI * MA_PFN_waveInUnprepareHeader)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
  20489. typedef MMRESULT (WINAPI * MA_PFN_waveInAddBuffer)(HWAVEIN hwi, LPWAVEHDR pwh, UINT cbwh);
  20490. typedef MMRESULT (WINAPI * MA_PFN_waveInStart)(HWAVEIN hwi);
  20491. typedef MMRESULT (WINAPI * MA_PFN_waveInReset)(HWAVEIN hwi);
  20492. static ma_result ma_result_from_MMRESULT(MMRESULT resultMM)
  20493. {
  20494. switch (resultMM) {
  20495. case MMSYSERR_NOERROR: return MA_SUCCESS;
  20496. case MMSYSERR_BADDEVICEID: return MA_INVALID_ARGS;
  20497. case MMSYSERR_INVALHANDLE: return MA_INVALID_ARGS;
  20498. case MMSYSERR_NOMEM: return MA_OUT_OF_MEMORY;
  20499. case MMSYSERR_INVALFLAG: return MA_INVALID_ARGS;
  20500. case MMSYSERR_INVALPARAM: return MA_INVALID_ARGS;
  20501. case MMSYSERR_HANDLEBUSY: return MA_BUSY;
  20502. case MMSYSERR_ERROR: return MA_ERROR;
  20503. default: return MA_ERROR;
  20504. }
  20505. }
  20506. static char* ma_find_last_character(char* str, char ch)
  20507. {
  20508. char* last;
  20509. if (str == NULL) {
  20510. return NULL;
  20511. }
  20512. last = NULL;
  20513. while (*str != '\0') {
  20514. if (*str == ch) {
  20515. last = str;
  20516. }
  20517. str += 1;
  20518. }
  20519. return last;
  20520. }
  20521. static ma_uint32 ma_get_period_size_in_bytes(ma_uint32 periodSizeInFrames, ma_format format, ma_uint32 channels)
  20522. {
  20523. return periodSizeInFrames * ma_get_bytes_per_frame(format, channels);
  20524. }
  20525. /*
  20526. Our own "WAVECAPS" structure that contains generic information shared between WAVEOUTCAPS2 and WAVEINCAPS2 so
  20527. we can do things generically and typesafely. Names are being kept the same for consistency.
  20528. */
  20529. typedef struct
  20530. {
  20531. CHAR szPname[MAXPNAMELEN];
  20532. DWORD dwFormats;
  20533. WORD wChannels;
  20534. GUID NameGuid;
  20535. } MA_WAVECAPSA;
  20536. static ma_result ma_get_best_info_from_formats_flags__winmm(DWORD dwFormats, WORD channels, WORD* pBitsPerSample, DWORD* pSampleRate)
  20537. {
  20538. WORD bitsPerSample = 0;
  20539. DWORD sampleRate = 0;
  20540. if (pBitsPerSample) {
  20541. *pBitsPerSample = 0;
  20542. }
  20543. if (pSampleRate) {
  20544. *pSampleRate = 0;
  20545. }
  20546. if (channels == 1) {
  20547. bitsPerSample = 16;
  20548. if ((dwFormats & WAVE_FORMAT_48M16) != 0) {
  20549. sampleRate = 48000;
  20550. } else if ((dwFormats & WAVE_FORMAT_44M16) != 0) {
  20551. sampleRate = 44100;
  20552. } else if ((dwFormats & WAVE_FORMAT_2M16) != 0) {
  20553. sampleRate = 22050;
  20554. } else if ((dwFormats & WAVE_FORMAT_1M16) != 0) {
  20555. sampleRate = 11025;
  20556. } else if ((dwFormats & WAVE_FORMAT_96M16) != 0) {
  20557. sampleRate = 96000;
  20558. } else {
  20559. bitsPerSample = 8;
  20560. if ((dwFormats & WAVE_FORMAT_48M08) != 0) {
  20561. sampleRate = 48000;
  20562. } else if ((dwFormats & WAVE_FORMAT_44M08) != 0) {
  20563. sampleRate = 44100;
  20564. } else if ((dwFormats & WAVE_FORMAT_2M08) != 0) {
  20565. sampleRate = 22050;
  20566. } else if ((dwFormats & WAVE_FORMAT_1M08) != 0) {
  20567. sampleRate = 11025;
  20568. } else if ((dwFormats & WAVE_FORMAT_96M08) != 0) {
  20569. sampleRate = 96000;
  20570. } else {
  20571. return MA_FORMAT_NOT_SUPPORTED;
  20572. }
  20573. }
  20574. } else {
  20575. bitsPerSample = 16;
  20576. if ((dwFormats & WAVE_FORMAT_48S16) != 0) {
  20577. sampleRate = 48000;
  20578. } else if ((dwFormats & WAVE_FORMAT_44S16) != 0) {
  20579. sampleRate = 44100;
  20580. } else if ((dwFormats & WAVE_FORMAT_2S16) != 0) {
  20581. sampleRate = 22050;
  20582. } else if ((dwFormats & WAVE_FORMAT_1S16) != 0) {
  20583. sampleRate = 11025;
  20584. } else if ((dwFormats & WAVE_FORMAT_96S16) != 0) {
  20585. sampleRate = 96000;
  20586. } else {
  20587. bitsPerSample = 8;
  20588. if ((dwFormats & WAVE_FORMAT_48S08) != 0) {
  20589. sampleRate = 48000;
  20590. } else if ((dwFormats & WAVE_FORMAT_44S08) != 0) {
  20591. sampleRate = 44100;
  20592. } else if ((dwFormats & WAVE_FORMAT_2S08) != 0) {
  20593. sampleRate = 22050;
  20594. } else if ((dwFormats & WAVE_FORMAT_1S08) != 0) {
  20595. sampleRate = 11025;
  20596. } else if ((dwFormats & WAVE_FORMAT_96S08) != 0) {
  20597. sampleRate = 96000;
  20598. } else {
  20599. return MA_FORMAT_NOT_SUPPORTED;
  20600. }
  20601. }
  20602. }
  20603. if (pBitsPerSample) {
  20604. *pBitsPerSample = bitsPerSample;
  20605. }
  20606. if (pSampleRate) {
  20607. *pSampleRate = sampleRate;
  20608. }
  20609. return MA_SUCCESS;
  20610. }
  20611. static ma_result ma_formats_flags_to_WAVEFORMATEX__winmm(DWORD dwFormats, WORD channels, WAVEFORMATEX* pWF)
  20612. {
  20613. ma_result result;
  20614. MA_ASSERT(pWF != NULL);
  20615. MA_ZERO_OBJECT(pWF);
  20616. pWF->cbSize = sizeof(*pWF);
  20617. pWF->wFormatTag = WAVE_FORMAT_PCM;
  20618. pWF->nChannels = (WORD)channels;
  20619. if (pWF->nChannels > 2) {
  20620. pWF->nChannels = 2;
  20621. }
  20622. result = ma_get_best_info_from_formats_flags__winmm(dwFormats, channels, &pWF->wBitsPerSample, &pWF->nSamplesPerSec);
  20623. if (result != MA_SUCCESS) {
  20624. return result;
  20625. }
  20626. pWF->nBlockAlign = (WORD)(pWF->nChannels * pWF->wBitsPerSample / 8);
  20627. pWF->nAvgBytesPerSec = pWF->nBlockAlign * pWF->nSamplesPerSec;
  20628. return MA_SUCCESS;
  20629. }
  20630. static ma_result ma_context_get_device_info_from_WAVECAPS(ma_context* pContext, MA_WAVECAPSA* pCaps, ma_device_info* pDeviceInfo)
  20631. {
  20632. WORD bitsPerSample;
  20633. DWORD sampleRate;
  20634. ma_result result;
  20635. MA_ASSERT(pContext != NULL);
  20636. MA_ASSERT(pCaps != NULL);
  20637. MA_ASSERT(pDeviceInfo != NULL);
  20638. /*
  20639. Name / Description
  20640. Unfortunately the name specified in WAVE(OUT/IN)CAPS2 is limited to 31 characters. This results in an unprofessional looking
  20641. situation where the names of the devices are truncated. To help work around this, we need to look at the name GUID and try
  20642. 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.
  20643. */
  20644. /* Set the default to begin with. */
  20645. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), pCaps->szPname, (size_t)-1);
  20646. /*
  20647. Now try the registry. There's a few things to consider here:
  20648. - The name GUID can be null, in which we case we just need to stick to the original 31 characters.
  20649. - If the name GUID is not present in the registry we'll also need to stick to the original 31 characters.
  20650. - I like consistency, so I want the returned device names to be consistent with those returned by WASAPI and DirectSound. The
  20651. problem, however is that WASAPI and DirectSound use "<component> (<name>)" format (such as "Speakers (High Definition Audio)"),
  20652. but WinMM does not specificy the component name. From my admittedly limited testing, I've notice the component name seems to
  20653. 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
  20654. name, and then concatenate the name from the registry.
  20655. */
  20656. if (!ma_is_guid_null(&pCaps->NameGuid)) {
  20657. wchar_t guidStrW[256];
  20658. if (((MA_PFN_StringFromGUID2)pContext->win32.StringFromGUID2)(&pCaps->NameGuid, guidStrW, ma_countof(guidStrW)) > 0) {
  20659. char guidStr[256];
  20660. char keyStr[1024];
  20661. HKEY hKey;
  20662. WideCharToMultiByte(CP_UTF8, 0, guidStrW, -1, guidStr, sizeof(guidStr), 0, FALSE);
  20663. ma_strcpy_s(keyStr, sizeof(keyStr), "SYSTEM\\CurrentControlSet\\Control\\MediaCategories\\");
  20664. ma_strcat_s(keyStr, sizeof(keyStr), guidStr);
  20665. if (((MA_PFN_RegOpenKeyExA)pContext->win32.RegOpenKeyExA)(HKEY_LOCAL_MACHINE, keyStr, 0, KEY_READ, &hKey) == ERROR_SUCCESS) {
  20666. BYTE nameFromReg[512];
  20667. DWORD nameFromRegSize = sizeof(nameFromReg);
  20668. LONG resultWin32 = ((MA_PFN_RegQueryValueExA)pContext->win32.RegQueryValueExA)(hKey, "Name", 0, NULL, (LPBYTE)nameFromReg, (LPDWORD)&nameFromRegSize);
  20669. ((MA_PFN_RegCloseKey)pContext->win32.RegCloseKey)(hKey);
  20670. if (resultWin32 == ERROR_SUCCESS) {
  20671. /* We have the value from the registry, so now we need to construct the name string. */
  20672. char name[1024];
  20673. if (ma_strcpy_s(name, sizeof(name), pDeviceInfo->name) == 0) {
  20674. char* nameBeg = ma_find_last_character(name, '(');
  20675. if (nameBeg != NULL) {
  20676. size_t leadingLen = (nameBeg - name);
  20677. ma_strncpy_s(nameBeg + 1, sizeof(name) - leadingLen, (const char*)nameFromReg, (size_t)-1);
  20678. /* The closing ")", if it can fit. */
  20679. if (leadingLen + nameFromRegSize < sizeof(name)-1) {
  20680. ma_strcat_s(name, sizeof(name), ")");
  20681. }
  20682. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), name, (size_t)-1);
  20683. }
  20684. }
  20685. }
  20686. }
  20687. }
  20688. }
  20689. result = ma_get_best_info_from_formats_flags__winmm(pCaps->dwFormats, pCaps->wChannels, &bitsPerSample, &sampleRate);
  20690. if (result != MA_SUCCESS) {
  20691. return result;
  20692. }
  20693. if (bitsPerSample == 8) {
  20694. pDeviceInfo->nativeDataFormats[0].format = ma_format_u8;
  20695. } else if (bitsPerSample == 16) {
  20696. pDeviceInfo->nativeDataFormats[0].format = ma_format_s16;
  20697. } else if (bitsPerSample == 24) {
  20698. pDeviceInfo->nativeDataFormats[0].format = ma_format_s24;
  20699. } else if (bitsPerSample == 32) {
  20700. pDeviceInfo->nativeDataFormats[0].format = ma_format_s32;
  20701. } else {
  20702. return MA_FORMAT_NOT_SUPPORTED;
  20703. }
  20704. pDeviceInfo->nativeDataFormats[0].channels = pCaps->wChannels;
  20705. pDeviceInfo->nativeDataFormats[0].sampleRate = sampleRate;
  20706. pDeviceInfo->nativeDataFormats[0].flags = 0;
  20707. pDeviceInfo->nativeDataFormatCount = 1;
  20708. return MA_SUCCESS;
  20709. }
  20710. static ma_result ma_context_get_device_info_from_WAVEOUTCAPS2(ma_context* pContext, MA_WAVEOUTCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  20711. {
  20712. MA_WAVECAPSA caps;
  20713. MA_ASSERT(pContext != NULL);
  20714. MA_ASSERT(pCaps != NULL);
  20715. MA_ASSERT(pDeviceInfo != NULL);
  20716. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  20717. caps.dwFormats = pCaps->dwFormats;
  20718. caps.wChannels = pCaps->wChannels;
  20719. caps.NameGuid = pCaps->NameGuid;
  20720. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  20721. }
  20722. static ma_result ma_context_get_device_info_from_WAVEINCAPS2(ma_context* pContext, MA_WAVEINCAPS2A* pCaps, ma_device_info* pDeviceInfo)
  20723. {
  20724. MA_WAVECAPSA caps;
  20725. MA_ASSERT(pContext != NULL);
  20726. MA_ASSERT(pCaps != NULL);
  20727. MA_ASSERT(pDeviceInfo != NULL);
  20728. MA_COPY_MEMORY(caps.szPname, pCaps->szPname, sizeof(caps.szPname));
  20729. caps.dwFormats = pCaps->dwFormats;
  20730. caps.wChannels = pCaps->wChannels;
  20731. caps.NameGuid = pCaps->NameGuid;
  20732. return ma_context_get_device_info_from_WAVECAPS(pContext, &caps, pDeviceInfo);
  20733. }
  20734. static ma_result ma_context_enumerate_devices__winmm(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  20735. {
  20736. UINT playbackDeviceCount;
  20737. UINT captureDeviceCount;
  20738. UINT iPlaybackDevice;
  20739. UINT iCaptureDevice;
  20740. MA_ASSERT(pContext != NULL);
  20741. MA_ASSERT(callback != NULL);
  20742. /* Playback. */
  20743. playbackDeviceCount = ((MA_PFN_waveOutGetNumDevs)pContext->winmm.waveOutGetNumDevs)();
  20744. for (iPlaybackDevice = 0; iPlaybackDevice < playbackDeviceCount; ++iPlaybackDevice) {
  20745. MMRESULT result;
  20746. MA_WAVEOUTCAPS2A caps;
  20747. MA_ZERO_OBJECT(&caps);
  20748. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(iPlaybackDevice, (WAVEOUTCAPSA*)&caps, sizeof(caps));
  20749. if (result == MMSYSERR_NOERROR) {
  20750. ma_device_info deviceInfo;
  20751. MA_ZERO_OBJECT(&deviceInfo);
  20752. deviceInfo.id.winmm = iPlaybackDevice;
  20753. /* The first enumerated device is the default device. */
  20754. if (iPlaybackDevice == 0) {
  20755. deviceInfo.isDefault = MA_TRUE;
  20756. }
  20757. if (ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  20758. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  20759. if (cbResult == MA_FALSE) {
  20760. return MA_SUCCESS; /* Enumeration was stopped. */
  20761. }
  20762. }
  20763. }
  20764. }
  20765. /* Capture. */
  20766. captureDeviceCount = ((MA_PFN_waveInGetNumDevs)pContext->winmm.waveInGetNumDevs)();
  20767. for (iCaptureDevice = 0; iCaptureDevice < captureDeviceCount; ++iCaptureDevice) {
  20768. MMRESULT result;
  20769. MA_WAVEINCAPS2A caps;
  20770. MA_ZERO_OBJECT(&caps);
  20771. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(iCaptureDevice, (WAVEINCAPSA*)&caps, sizeof(caps));
  20772. if (result == MMSYSERR_NOERROR) {
  20773. ma_device_info deviceInfo;
  20774. MA_ZERO_OBJECT(&deviceInfo);
  20775. deviceInfo.id.winmm = iCaptureDevice;
  20776. /* The first enumerated device is the default device. */
  20777. if (iCaptureDevice == 0) {
  20778. deviceInfo.isDefault = MA_TRUE;
  20779. }
  20780. if (ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, &deviceInfo) == MA_SUCCESS) {
  20781. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  20782. if (cbResult == MA_FALSE) {
  20783. return MA_SUCCESS; /* Enumeration was stopped. */
  20784. }
  20785. }
  20786. }
  20787. }
  20788. return MA_SUCCESS;
  20789. }
  20790. 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)
  20791. {
  20792. UINT winMMDeviceID;
  20793. MA_ASSERT(pContext != NULL);
  20794. winMMDeviceID = 0;
  20795. if (pDeviceID != NULL) {
  20796. winMMDeviceID = (UINT)pDeviceID->winmm;
  20797. }
  20798. pDeviceInfo->id.winmm = winMMDeviceID;
  20799. /* The first ID is the default device. */
  20800. if (winMMDeviceID == 0) {
  20801. pDeviceInfo->isDefault = MA_TRUE;
  20802. }
  20803. if (deviceType == ma_device_type_playback) {
  20804. MMRESULT result;
  20805. MA_WAVEOUTCAPS2A caps;
  20806. MA_ZERO_OBJECT(&caps);
  20807. result = ((MA_PFN_waveOutGetDevCapsA)pContext->winmm.waveOutGetDevCapsA)(winMMDeviceID, (WAVEOUTCAPSA*)&caps, sizeof(caps));
  20808. if (result == MMSYSERR_NOERROR) {
  20809. return ma_context_get_device_info_from_WAVEOUTCAPS2(pContext, &caps, pDeviceInfo);
  20810. }
  20811. } else {
  20812. MMRESULT result;
  20813. MA_WAVEINCAPS2A caps;
  20814. MA_ZERO_OBJECT(&caps);
  20815. result = ((MA_PFN_waveInGetDevCapsA)pContext->winmm.waveInGetDevCapsA)(winMMDeviceID, (WAVEINCAPSA*)&caps, sizeof(caps));
  20816. if (result == MMSYSERR_NOERROR) {
  20817. return ma_context_get_device_info_from_WAVEINCAPS2(pContext, &caps, pDeviceInfo);
  20818. }
  20819. }
  20820. return MA_NO_DEVICE;
  20821. }
  20822. static ma_result ma_device_uninit__winmm(ma_device* pDevice)
  20823. {
  20824. MA_ASSERT(pDevice != NULL);
  20825. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  20826. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture);
  20827. CloseHandle((HANDLE)pDevice->winmm.hEventCapture);
  20828. }
  20829. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  20830. ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
  20831. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
  20832. CloseHandle((HANDLE)pDevice->winmm.hEventPlayback);
  20833. }
  20834. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  20835. MA_ZERO_OBJECT(&pDevice->winmm); /* Safety. */
  20836. return MA_SUCCESS;
  20837. }
  20838. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__winmm(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  20839. {
  20840. /* WinMM has a minimum period size of 40ms. */
  20841. ma_uint32 minPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(40, nativeSampleRate);
  20842. ma_uint32 periodSizeInFrames;
  20843. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, nativeSampleRate, performanceProfile);
  20844. if (periodSizeInFrames < minPeriodSizeInFrames) {
  20845. periodSizeInFrames = minPeriodSizeInFrames;
  20846. }
  20847. return periodSizeInFrames;
  20848. }
  20849. static ma_result ma_device_init__winmm(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  20850. {
  20851. const char* errorMsg = "";
  20852. ma_result errorCode = MA_ERROR;
  20853. ma_result result = MA_SUCCESS;
  20854. ma_uint32 heapSize;
  20855. UINT winMMDeviceIDPlayback = 0;
  20856. UINT winMMDeviceIDCapture = 0;
  20857. MA_ASSERT(pDevice != NULL);
  20858. MA_ZERO_OBJECT(&pDevice->winmm);
  20859. if (pConfig->deviceType == ma_device_type_loopback) {
  20860. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  20861. }
  20862. /* No exlusive mode with WinMM. */
  20863. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  20864. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  20865. return MA_SHARE_MODE_NOT_SUPPORTED;
  20866. }
  20867. if (pDescriptorPlayback->pDeviceID != NULL) {
  20868. winMMDeviceIDPlayback = (UINT)pDescriptorPlayback->pDeviceID->winmm;
  20869. }
  20870. if (pDescriptorCapture->pDeviceID != NULL) {
  20871. winMMDeviceIDCapture = (UINT)pDescriptorCapture->pDeviceID->winmm;
  20872. }
  20873. /* The capture device needs to be initialized first. */
  20874. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  20875. WAVEINCAPSA caps;
  20876. WAVEFORMATEX wf;
  20877. MMRESULT resultMM;
  20878. /* We use an event to know when a new fragment needs to be enqueued. */
  20879. pDevice->winmm.hEventCapture = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
  20880. if (pDevice->winmm.hEventCapture == NULL) {
  20881. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the capture device.", errorCode = ma_result_from_GetLastError(GetLastError());
  20882. goto on_error;
  20883. }
  20884. /* The format should be based on the device's actual format. */
  20885. if (((MA_PFN_waveInGetDevCapsA)pDevice->pContext->winmm.waveInGetDevCapsA)(winMMDeviceIDCapture, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
  20886. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  20887. goto on_error;
  20888. }
  20889. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  20890. if (result != MA_SUCCESS) {
  20891. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  20892. goto on_error;
  20893. }
  20894. resultMM = ((MA_PFN_waveInOpen)pDevice->pContext->winmm.waveInOpen)((LPHWAVEIN)&pDevice->winmm.hDeviceCapture, winMMDeviceIDCapture, &wf, (DWORD_PTR)pDevice->winmm.hEventCapture, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC);
  20895. if (resultMM != MMSYSERR_NOERROR) {
  20896. errorMsg = "[WinMM] Failed to open capture device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  20897. goto on_error;
  20898. }
  20899. pDescriptorCapture->format = ma_format_from_WAVEFORMATEX(&wf);
  20900. pDescriptorCapture->channels = wf.nChannels;
  20901. pDescriptorCapture->sampleRate = wf.nSamplesPerSec;
  20902. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  20903. pDescriptorCapture->periodCount = pDescriptorCapture->periodCount;
  20904. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  20905. }
  20906. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  20907. WAVEOUTCAPSA caps;
  20908. WAVEFORMATEX wf;
  20909. MMRESULT resultMM;
  20910. /* We use an event to know when a new fragment needs to be enqueued. */
  20911. pDevice->winmm.hEventPlayback = (ma_handle)CreateEventW(NULL, TRUE, TRUE, NULL);
  20912. if (pDevice->winmm.hEventPlayback == NULL) {
  20913. errorMsg = "[WinMM] Failed to create event for fragment enqueing for the playback device.", errorCode = ma_result_from_GetLastError(GetLastError());
  20914. goto on_error;
  20915. }
  20916. /* The format should be based on the device's actual format. */
  20917. if (((MA_PFN_waveOutGetDevCapsA)pDevice->pContext->winmm.waveOutGetDevCapsA)(winMMDeviceIDPlayback, &caps, sizeof(caps)) != MMSYSERR_NOERROR) {
  20918. errorMsg = "[WinMM] Failed to retrieve internal device caps.", errorCode = MA_FORMAT_NOT_SUPPORTED;
  20919. goto on_error;
  20920. }
  20921. result = ma_formats_flags_to_WAVEFORMATEX__winmm(caps.dwFormats, caps.wChannels, &wf);
  20922. if (result != MA_SUCCESS) {
  20923. errorMsg = "[WinMM] Could not find appropriate format for internal device.", errorCode = result;
  20924. goto on_error;
  20925. }
  20926. resultMM = ((MA_PFN_waveOutOpen)pDevice->pContext->winmm.waveOutOpen)((LPHWAVEOUT)&pDevice->winmm.hDevicePlayback, winMMDeviceIDPlayback, &wf, (DWORD_PTR)pDevice->winmm.hEventPlayback, (DWORD_PTR)pDevice, CALLBACK_EVENT | WAVE_ALLOWSYNC);
  20927. if (resultMM != MMSYSERR_NOERROR) {
  20928. errorMsg = "[WinMM] Failed to open playback device.", errorCode = MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  20929. goto on_error;
  20930. }
  20931. pDescriptorPlayback->format = ma_format_from_WAVEFORMATEX(&wf);
  20932. pDescriptorPlayback->channels = wf.nChannels;
  20933. pDescriptorPlayback->sampleRate = wf.nSamplesPerSec;
  20934. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  20935. pDescriptorPlayback->periodCount = pDescriptorPlayback->periodCount;
  20936. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__winmm(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  20937. }
  20938. /*
  20939. The heap allocated data is allocated like so:
  20940. [Capture WAVEHDRs][Playback WAVEHDRs][Capture Intermediary Buffer][Playback Intermediary Buffer]
  20941. */
  20942. heapSize = 0;
  20943. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  20944. heapSize += sizeof(WAVEHDR)*pDescriptorCapture->periodCount + (pDescriptorCapture->periodSizeInFrames * pDescriptorCapture->periodCount * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
  20945. }
  20946. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  20947. heapSize += sizeof(WAVEHDR)*pDescriptorPlayback->periodCount + (pDescriptorPlayback->periodSizeInFrames * pDescriptorPlayback->periodCount * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels));
  20948. }
  20949. pDevice->winmm._pHeapData = (ma_uint8*)ma_calloc(heapSize, &pDevice->pContext->allocationCallbacks);
  20950. if (pDevice->winmm._pHeapData == NULL) {
  20951. errorMsg = "[WinMM] Failed to allocate memory for the intermediary buffer.", errorCode = MA_OUT_OF_MEMORY;
  20952. goto on_error;
  20953. }
  20954. MA_ZERO_MEMORY(pDevice->winmm._pHeapData, heapSize);
  20955. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  20956. ma_uint32 iPeriod;
  20957. if (pConfig->deviceType == ma_device_type_capture) {
  20958. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  20959. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount));
  20960. } else {
  20961. pDevice->winmm.pWAVEHDRCapture = pDevice->winmm._pHeapData;
  20962. pDevice->winmm.pIntermediaryBufferCapture = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount));
  20963. }
  20964. /* Prepare headers. */
  20965. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  20966. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->format, pDescriptorCapture->channels);
  20967. ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferCapture + (periodSizeInBytes*iPeriod));
  20968. ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwBufferLength = periodSizeInBytes;
  20969. ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwFlags = 0L;
  20970. ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwLoops = 0L;
  20971. ((MA_PFN_waveInPrepareHeader)pDevice->pContext->winmm.waveInPrepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
  20972. /*
  20973. The user data of the 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
  20974. it's unlocked and available for writing. A value of 1 means it's locked.
  20975. */
  20976. ((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod].dwUser = 0;
  20977. }
  20978. }
  20979. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  20980. ma_uint32 iPeriod;
  20981. if (pConfig->deviceType == ma_device_type_playback) {
  20982. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData;
  20983. pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*pDescriptorPlayback->periodCount);
  20984. } else {
  20985. pDevice->winmm.pWAVEHDRPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount));
  20986. pDevice->winmm.pIntermediaryBufferPlayback = pDevice->winmm._pHeapData + (sizeof(WAVEHDR)*(pDescriptorCapture->periodCount + pDescriptorPlayback->periodCount)) + (pDescriptorCapture->periodSizeInFrames*pDescriptorCapture->periodCount*ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels));
  20987. }
  20988. /* Prepare headers. */
  20989. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  20990. ma_uint32 periodSizeInBytes = ma_get_period_size_in_bytes(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->format, pDescriptorPlayback->channels);
  20991. ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].lpData = (LPSTR)(pDevice->winmm.pIntermediaryBufferPlayback + (periodSizeInBytes*iPeriod));
  20992. ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwBufferLength = periodSizeInBytes;
  20993. ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwFlags = 0L;
  20994. ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwLoops = 0L;
  20995. ((MA_PFN_waveOutPrepareHeader)pDevice->pContext->winmm.waveOutPrepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR));
  20996. /*
  20997. The user data of the 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
  20998. it's unlocked and available for writing. A value of 1 means it's locked.
  20999. */
  21000. ((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod].dwUser = 0;
  21001. }
  21002. }
  21003. return MA_SUCCESS;
  21004. on_error:
  21005. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21006. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21007. ma_uint32 iPeriod;
  21008. for (iPeriod = 0; iPeriod < pDescriptorCapture->periodCount; ++iPeriod) {
  21009. ((MA_PFN_waveInUnprepareHeader)pDevice->pContext->winmm.waveInUnprepareHeader)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((WAVEHDR*)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
  21010. }
  21011. }
  21012. ((MA_PFN_waveInClose)pDevice->pContext->winmm.waveInClose)((HWAVEIN)pDevice->winmm.hDeviceCapture);
  21013. }
  21014. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21015. if (pDevice->winmm.pWAVEHDRCapture != NULL) {
  21016. ma_uint32 iPeriod;
  21017. for (iPeriod = 0; iPeriod < pDescriptorPlayback->periodCount; ++iPeriod) {
  21018. ((MA_PFN_waveOutUnprepareHeader)pDevice->pContext->winmm.waveOutUnprepareHeader)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &((WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback)[iPeriod], sizeof(WAVEHDR));
  21019. }
  21020. }
  21021. ((MA_PFN_waveOutClose)pDevice->pContext->winmm.waveOutClose)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21022. }
  21023. ma_free(pDevice->winmm._pHeapData, &pDevice->pContext->allocationCallbacks);
  21024. if (errorMsg != NULL && errorMsg[0] != '\0') {
  21025. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "%s", errorMsg);
  21026. }
  21027. return errorCode;
  21028. }
  21029. static ma_result ma_device_start__winmm(ma_device* pDevice)
  21030. {
  21031. MA_ASSERT(pDevice != NULL);
  21032. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21033. MMRESULT resultMM;
  21034. WAVEHDR* pWAVEHDR;
  21035. ma_uint32 iPeriod;
  21036. pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  21037. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  21038. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  21039. /* 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. */
  21040. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  21041. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[iPeriod], sizeof(WAVEHDR));
  21042. if (resultMM != MMSYSERR_NOERROR) {
  21043. 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.");
  21044. return ma_result_from_MMRESULT(resultMM);
  21045. }
  21046. /* Make sure all of the buffers start out locked. We don't want to access them until the backend tells us we can. */
  21047. pWAVEHDR[iPeriod].dwUser = 1; /* 1 = locked. */
  21048. }
  21049. /* Capture devices need to be explicitly started, unlike playback devices. */
  21050. resultMM = ((MA_PFN_waveInStart)pDevice->pContext->winmm.waveInStart)((HWAVEIN)pDevice->winmm.hDeviceCapture);
  21051. if (resultMM != MMSYSERR_NOERROR) {
  21052. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] Failed to start backend device.");
  21053. return ma_result_from_MMRESULT(resultMM);
  21054. }
  21055. }
  21056. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21057. /* Don't need to do anything for playback. It'll be started automatically in ma_device_start__winmm(). */
  21058. }
  21059. return MA_SUCCESS;
  21060. }
  21061. static ma_result ma_device_stop__winmm(ma_device* pDevice)
  21062. {
  21063. MMRESULT resultMM;
  21064. MA_ASSERT(pDevice != NULL);
  21065. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  21066. if (pDevice->winmm.hDeviceCapture == NULL) {
  21067. return MA_INVALID_ARGS;
  21068. }
  21069. resultMM = ((MA_PFN_waveInReset)pDevice->pContext->winmm.waveInReset)((HWAVEIN)pDevice->winmm.hDeviceCapture);
  21070. if (resultMM != MMSYSERR_NOERROR) {
  21071. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset capture device.");
  21072. }
  21073. }
  21074. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  21075. ma_uint32 iPeriod;
  21076. WAVEHDR* pWAVEHDR;
  21077. if (pDevice->winmm.hDevicePlayback == NULL) {
  21078. return MA_INVALID_ARGS;
  21079. }
  21080. /* 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. */
  21081. pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  21082. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; iPeriod += 1) {
  21083. if (pWAVEHDR[iPeriod].dwUser == 1) { /* 1 = locked. */
  21084. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  21085. break; /* An error occurred so just abandon ship and stop the device without draining. */
  21086. }
  21087. pWAVEHDR[iPeriod].dwUser = 0;
  21088. }
  21089. }
  21090. resultMM = ((MA_PFN_waveOutReset)pDevice->pContext->winmm.waveOutReset)((HWAVEOUT)pDevice->winmm.hDevicePlayback);
  21091. if (resultMM != MMSYSERR_NOERROR) {
  21092. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_WARNING, "[WinMM] WARNING: Failed to reset playback device.");
  21093. }
  21094. }
  21095. return MA_SUCCESS;
  21096. }
  21097. static ma_result ma_device_write__winmm(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  21098. {
  21099. ma_result result = MA_SUCCESS;
  21100. MMRESULT resultMM;
  21101. ma_uint32 totalFramesWritten;
  21102. WAVEHDR* pWAVEHDR;
  21103. MA_ASSERT(pDevice != NULL);
  21104. MA_ASSERT(pPCMFrames != NULL);
  21105. if (pFramesWritten != NULL) {
  21106. *pFramesWritten = 0;
  21107. }
  21108. pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRPlayback;
  21109. /* Keep processing as much data as possible. */
  21110. totalFramesWritten = 0;
  21111. while (totalFramesWritten < frameCount) {
  21112. /* If the current header has some space available we need to write part of it. */
  21113. if (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser == 0) { /* 0 = unlocked. */
  21114. /*
  21115. 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
  21116. write it out and move on to the next iteration.
  21117. */
  21118. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  21119. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedPlayback;
  21120. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesWritten));
  21121. const void* pSrc = ma_offset_ptr(pPCMFrames, totalFramesWritten*bpf);
  21122. void* pDst = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].lpData, pDevice->winmm.headerFramesConsumedPlayback*bpf);
  21123. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  21124. pDevice->winmm.headerFramesConsumedPlayback += framesToCopy;
  21125. totalFramesWritten += framesToCopy;
  21126. /* If we've consumed the buffer entirely we need to write it out to the device. */
  21127. if (pDevice->winmm.headerFramesConsumedPlayback == (pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwBufferLength/bpf)) {
  21128. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 1; /* 1 = locked. */
  21129. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  21130. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  21131. ResetEvent((HANDLE)pDevice->winmm.hEventPlayback);
  21132. /* The device will be started here. */
  21133. resultMM = ((MA_PFN_waveOutWrite)pDevice->pContext->winmm.waveOutWrite)((HWAVEOUT)pDevice->winmm.hDevicePlayback, &pWAVEHDR[pDevice->winmm.iNextHeaderPlayback], sizeof(WAVEHDR));
  21134. if (resultMM != MMSYSERR_NOERROR) {
  21135. result = ma_result_from_MMRESULT(resultMM);
  21136. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveOutWrite() failed.");
  21137. break;
  21138. }
  21139. /* Make sure we move to the next header. */
  21140. pDevice->winmm.iNextHeaderPlayback = (pDevice->winmm.iNextHeaderPlayback + 1) % pDevice->playback.internalPeriods;
  21141. pDevice->winmm.headerFramesConsumedPlayback = 0;
  21142. }
  21143. /* If at this point we have consumed the entire input buffer we can return. */
  21144. MA_ASSERT(totalFramesWritten <= frameCount);
  21145. if (totalFramesWritten == frameCount) {
  21146. break;
  21147. }
  21148. /* Getting here means there's more to process. */
  21149. continue;
  21150. }
  21151. /* Getting here means there isn't enough room in the buffer and we need to wait for one to become available. */
  21152. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventPlayback, INFINITE) != WAIT_OBJECT_0) {
  21153. result = MA_ERROR;
  21154. break;
  21155. }
  21156. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  21157. if ((pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwFlags & WHDR_DONE) != 0) {
  21158. pWAVEHDR[pDevice->winmm.iNextHeaderPlayback].dwUser = 0; /* 0 = unlocked (make it available for writing). */
  21159. pDevice->winmm.headerFramesConsumedPlayback = 0;
  21160. }
  21161. /* If the device has been stopped we need to break. */
  21162. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  21163. break;
  21164. }
  21165. }
  21166. if (pFramesWritten != NULL) {
  21167. *pFramesWritten = totalFramesWritten;
  21168. }
  21169. return result;
  21170. }
  21171. static ma_result ma_device_read__winmm(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  21172. {
  21173. ma_result result = MA_SUCCESS;
  21174. MMRESULT resultMM;
  21175. ma_uint32 totalFramesRead;
  21176. WAVEHDR* pWAVEHDR;
  21177. MA_ASSERT(pDevice != NULL);
  21178. MA_ASSERT(pPCMFrames != NULL);
  21179. if (pFramesRead != NULL) {
  21180. *pFramesRead = 0;
  21181. }
  21182. pWAVEHDR = (WAVEHDR*)pDevice->winmm.pWAVEHDRCapture;
  21183. /* Keep processing as much data as possible. */
  21184. totalFramesRead = 0;
  21185. while (totalFramesRead < frameCount) {
  21186. /* If the current header has some space available we need to write part of it. */
  21187. if (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser == 0) { /* 0 = unlocked. */
  21188. /* The buffer is available for reading. If we fully consume it we need to add it back to the buffer. */
  21189. ma_uint32 bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  21190. ma_uint32 framesRemainingInHeader = (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf) - pDevice->winmm.headerFramesConsumedCapture;
  21191. ma_uint32 framesToCopy = ma_min(framesRemainingInHeader, (frameCount - totalFramesRead));
  21192. const void* pSrc = ma_offset_ptr(pWAVEHDR[pDevice->winmm.iNextHeaderCapture].lpData, pDevice->winmm.headerFramesConsumedCapture*bpf);
  21193. void* pDst = ma_offset_ptr(pPCMFrames, totalFramesRead*bpf);
  21194. MA_COPY_MEMORY(pDst, pSrc, framesToCopy*bpf);
  21195. pDevice->winmm.headerFramesConsumedCapture += framesToCopy;
  21196. totalFramesRead += framesToCopy;
  21197. /* If we've consumed the buffer entirely we need to add it back to the device. */
  21198. if (pDevice->winmm.headerFramesConsumedCapture == (pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwBufferLength/bpf)) {
  21199. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 1; /* 1 = locked. */
  21200. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags &= ~WHDR_DONE; /* <-- Need to make sure the WHDR_DONE flag is unset. */
  21201. /* Make sure the event is reset to a non-signaled state to ensure we don't prematurely return from WaitForSingleObject(). */
  21202. ResetEvent((HANDLE)pDevice->winmm.hEventCapture);
  21203. /* The device will be started here. */
  21204. resultMM = ((MA_PFN_waveInAddBuffer)pDevice->pContext->winmm.waveInAddBuffer)((HWAVEIN)pDevice->winmm.hDeviceCapture, &((LPWAVEHDR)pDevice->winmm.pWAVEHDRCapture)[pDevice->winmm.iNextHeaderCapture], sizeof(WAVEHDR));
  21205. if (resultMM != MMSYSERR_NOERROR) {
  21206. result = ma_result_from_MMRESULT(resultMM);
  21207. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[WinMM] waveInAddBuffer() failed.");
  21208. break;
  21209. }
  21210. /* Make sure we move to the next header. */
  21211. pDevice->winmm.iNextHeaderCapture = (pDevice->winmm.iNextHeaderCapture + 1) % pDevice->capture.internalPeriods;
  21212. pDevice->winmm.headerFramesConsumedCapture = 0;
  21213. }
  21214. /* If at this point we have filled the entire input buffer we can return. */
  21215. MA_ASSERT(totalFramesRead <= frameCount);
  21216. if (totalFramesRead == frameCount) {
  21217. break;
  21218. }
  21219. /* Getting here means there's more to process. */
  21220. continue;
  21221. }
  21222. /* Getting here means there isn't enough any data left to send to the client which means we need to wait for more. */
  21223. if (WaitForSingleObject((HANDLE)pDevice->winmm.hEventCapture, INFINITE) != WAIT_OBJECT_0) {
  21224. result = MA_ERROR;
  21225. break;
  21226. }
  21227. /* Something happened. If the next buffer has been marked as done we need to reset a bit of state. */
  21228. if ((pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwFlags & WHDR_DONE) != 0) {
  21229. pWAVEHDR[pDevice->winmm.iNextHeaderCapture].dwUser = 0; /* 0 = unlocked (make it available for reading). */
  21230. pDevice->winmm.headerFramesConsumedCapture = 0;
  21231. }
  21232. /* If the device has been stopped we need to break. */
  21233. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  21234. break;
  21235. }
  21236. }
  21237. if (pFramesRead != NULL) {
  21238. *pFramesRead = totalFramesRead;
  21239. }
  21240. return result;
  21241. }
  21242. static ma_result ma_context_uninit__winmm(ma_context* pContext)
  21243. {
  21244. MA_ASSERT(pContext != NULL);
  21245. MA_ASSERT(pContext->backend == ma_backend_winmm);
  21246. ma_dlclose(pContext, pContext->winmm.hWinMM);
  21247. return MA_SUCCESS;
  21248. }
  21249. static ma_result ma_context_init__winmm(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  21250. {
  21251. MA_ASSERT(pContext != NULL);
  21252. (void)pConfig;
  21253. pContext->winmm.hWinMM = ma_dlopen(pContext, "winmm.dll");
  21254. if (pContext->winmm.hWinMM == NULL) {
  21255. return MA_NO_BACKEND;
  21256. }
  21257. pContext->winmm.waveOutGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetNumDevs");
  21258. pContext->winmm.waveOutGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutGetDevCapsA");
  21259. pContext->winmm.waveOutOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutOpen");
  21260. pContext->winmm.waveOutClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutClose");
  21261. pContext->winmm.waveOutPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutPrepareHeader");
  21262. pContext->winmm.waveOutUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutUnprepareHeader");
  21263. pContext->winmm.waveOutWrite = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutWrite");
  21264. pContext->winmm.waveOutReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveOutReset");
  21265. pContext->winmm.waveInGetNumDevs = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetNumDevs");
  21266. pContext->winmm.waveInGetDevCapsA = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInGetDevCapsA");
  21267. pContext->winmm.waveInOpen = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInOpen");
  21268. pContext->winmm.waveInClose = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInClose");
  21269. pContext->winmm.waveInPrepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInPrepareHeader");
  21270. pContext->winmm.waveInUnprepareHeader = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInUnprepareHeader");
  21271. pContext->winmm.waveInAddBuffer = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInAddBuffer");
  21272. pContext->winmm.waveInStart = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInStart");
  21273. pContext->winmm.waveInReset = ma_dlsym(pContext, pContext->winmm.hWinMM, "waveInReset");
  21274. pCallbacks->onContextInit = ma_context_init__winmm;
  21275. pCallbacks->onContextUninit = ma_context_uninit__winmm;
  21276. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__winmm;
  21277. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__winmm;
  21278. pCallbacks->onDeviceInit = ma_device_init__winmm;
  21279. pCallbacks->onDeviceUninit = ma_device_uninit__winmm;
  21280. pCallbacks->onDeviceStart = ma_device_start__winmm;
  21281. pCallbacks->onDeviceStop = ma_device_stop__winmm;
  21282. pCallbacks->onDeviceRead = ma_device_read__winmm;
  21283. pCallbacks->onDeviceWrite = ma_device_write__winmm;
  21284. pCallbacks->onDeviceDataLoop = NULL; /* This is a blocking read-write API, so this can be NULL since miniaudio will manage the audio thread for us. */
  21285. return MA_SUCCESS;
  21286. }
  21287. #endif
  21288. /******************************************************************************
  21289. ALSA Backend
  21290. ******************************************************************************/
  21291. #ifdef MA_HAS_ALSA
  21292. #include <poll.h> /* poll(), struct pollfd */
  21293. #include <sys/eventfd.h> /* eventfd() */
  21294. #ifdef MA_NO_RUNTIME_LINKING
  21295. /* asoundlib.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  21296. #if !defined(__cplusplus)
  21297. #if defined(__STRICT_ANSI__)
  21298. #if !defined(inline)
  21299. #define inline __inline__ __attribute__((always_inline))
  21300. #define MA_INLINE_DEFINED
  21301. #endif
  21302. #endif
  21303. #endif
  21304. #include <alsa/asoundlib.h>
  21305. #if defined(MA_INLINE_DEFINED)
  21306. #undef inline
  21307. #undef MA_INLINE_DEFINED
  21308. #endif
  21309. typedef snd_pcm_uframes_t ma_snd_pcm_uframes_t;
  21310. typedef snd_pcm_sframes_t ma_snd_pcm_sframes_t;
  21311. typedef snd_pcm_stream_t ma_snd_pcm_stream_t;
  21312. typedef snd_pcm_format_t ma_snd_pcm_format_t;
  21313. typedef snd_pcm_access_t ma_snd_pcm_access_t;
  21314. typedef snd_pcm_t ma_snd_pcm_t;
  21315. typedef snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  21316. typedef snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  21317. typedef snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  21318. typedef snd_pcm_info_t ma_snd_pcm_info_t;
  21319. typedef snd_pcm_channel_area_t ma_snd_pcm_channel_area_t;
  21320. typedef snd_pcm_chmap_t ma_snd_pcm_chmap_t;
  21321. typedef snd_pcm_state_t ma_snd_pcm_state_t;
  21322. /* snd_pcm_stream_t */
  21323. #define MA_SND_PCM_STREAM_PLAYBACK SND_PCM_STREAM_PLAYBACK
  21324. #define MA_SND_PCM_STREAM_CAPTURE SND_PCM_STREAM_CAPTURE
  21325. /* snd_pcm_format_t */
  21326. #define MA_SND_PCM_FORMAT_UNKNOWN SND_PCM_FORMAT_UNKNOWN
  21327. #define MA_SND_PCM_FORMAT_U8 SND_PCM_FORMAT_U8
  21328. #define MA_SND_PCM_FORMAT_S16_LE SND_PCM_FORMAT_S16_LE
  21329. #define MA_SND_PCM_FORMAT_S16_BE SND_PCM_FORMAT_S16_BE
  21330. #define MA_SND_PCM_FORMAT_S24_LE SND_PCM_FORMAT_S24_LE
  21331. #define MA_SND_PCM_FORMAT_S24_BE SND_PCM_FORMAT_S24_BE
  21332. #define MA_SND_PCM_FORMAT_S32_LE SND_PCM_FORMAT_S32_LE
  21333. #define MA_SND_PCM_FORMAT_S32_BE SND_PCM_FORMAT_S32_BE
  21334. #define MA_SND_PCM_FORMAT_FLOAT_LE SND_PCM_FORMAT_FLOAT_LE
  21335. #define MA_SND_PCM_FORMAT_FLOAT_BE SND_PCM_FORMAT_FLOAT_BE
  21336. #define MA_SND_PCM_FORMAT_FLOAT64_LE SND_PCM_FORMAT_FLOAT64_LE
  21337. #define MA_SND_PCM_FORMAT_FLOAT64_BE SND_PCM_FORMAT_FLOAT64_BE
  21338. #define MA_SND_PCM_FORMAT_MU_LAW SND_PCM_FORMAT_MU_LAW
  21339. #define MA_SND_PCM_FORMAT_A_LAW SND_PCM_FORMAT_A_LAW
  21340. #define MA_SND_PCM_FORMAT_S24_3LE SND_PCM_FORMAT_S24_3LE
  21341. #define MA_SND_PCM_FORMAT_S24_3BE SND_PCM_FORMAT_S24_3BE
  21342. /* ma_snd_pcm_access_t */
  21343. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED SND_PCM_ACCESS_MMAP_INTERLEAVED
  21344. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED SND_PCM_ACCESS_MMAP_NONINTERLEAVED
  21345. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX SND_PCM_ACCESS_MMAP_COMPLEX
  21346. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED SND_PCM_ACCESS_RW_INTERLEAVED
  21347. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED SND_PCM_ACCESS_RW_NONINTERLEAVED
  21348. /* Channel positions. */
  21349. #define MA_SND_CHMAP_UNKNOWN SND_CHMAP_UNKNOWN
  21350. #define MA_SND_CHMAP_NA SND_CHMAP_NA
  21351. #define MA_SND_CHMAP_MONO SND_CHMAP_MONO
  21352. #define MA_SND_CHMAP_FL SND_CHMAP_FL
  21353. #define MA_SND_CHMAP_FR SND_CHMAP_FR
  21354. #define MA_SND_CHMAP_RL SND_CHMAP_RL
  21355. #define MA_SND_CHMAP_RR SND_CHMAP_RR
  21356. #define MA_SND_CHMAP_FC SND_CHMAP_FC
  21357. #define MA_SND_CHMAP_LFE SND_CHMAP_LFE
  21358. #define MA_SND_CHMAP_SL SND_CHMAP_SL
  21359. #define MA_SND_CHMAP_SR SND_CHMAP_SR
  21360. #define MA_SND_CHMAP_RC SND_CHMAP_RC
  21361. #define MA_SND_CHMAP_FLC SND_CHMAP_FLC
  21362. #define MA_SND_CHMAP_FRC SND_CHMAP_FRC
  21363. #define MA_SND_CHMAP_RLC SND_CHMAP_RLC
  21364. #define MA_SND_CHMAP_RRC SND_CHMAP_RRC
  21365. #define MA_SND_CHMAP_FLW SND_CHMAP_FLW
  21366. #define MA_SND_CHMAP_FRW SND_CHMAP_FRW
  21367. #define MA_SND_CHMAP_FLH SND_CHMAP_FLH
  21368. #define MA_SND_CHMAP_FCH SND_CHMAP_FCH
  21369. #define MA_SND_CHMAP_FRH SND_CHMAP_FRH
  21370. #define MA_SND_CHMAP_TC SND_CHMAP_TC
  21371. #define MA_SND_CHMAP_TFL SND_CHMAP_TFL
  21372. #define MA_SND_CHMAP_TFR SND_CHMAP_TFR
  21373. #define MA_SND_CHMAP_TFC SND_CHMAP_TFC
  21374. #define MA_SND_CHMAP_TRL SND_CHMAP_TRL
  21375. #define MA_SND_CHMAP_TRR SND_CHMAP_TRR
  21376. #define MA_SND_CHMAP_TRC SND_CHMAP_TRC
  21377. #define MA_SND_CHMAP_TFLC SND_CHMAP_TFLC
  21378. #define MA_SND_CHMAP_TFRC SND_CHMAP_TFRC
  21379. #define MA_SND_CHMAP_TSL SND_CHMAP_TSL
  21380. #define MA_SND_CHMAP_TSR SND_CHMAP_TSR
  21381. #define MA_SND_CHMAP_LLFE SND_CHMAP_LLFE
  21382. #define MA_SND_CHMAP_RLFE SND_CHMAP_RLFE
  21383. #define MA_SND_CHMAP_BC SND_CHMAP_BC
  21384. #define MA_SND_CHMAP_BLC SND_CHMAP_BLC
  21385. #define MA_SND_CHMAP_BRC SND_CHMAP_BRC
  21386. /* Open mode flags. */
  21387. #define MA_SND_PCM_NO_AUTO_RESAMPLE SND_PCM_NO_AUTO_RESAMPLE
  21388. #define MA_SND_PCM_NO_AUTO_CHANNELS SND_PCM_NO_AUTO_CHANNELS
  21389. #define MA_SND_PCM_NO_AUTO_FORMAT SND_PCM_NO_AUTO_FORMAT
  21390. #else
  21391. #include <errno.h> /* For EPIPE, etc. */
  21392. typedef unsigned long ma_snd_pcm_uframes_t;
  21393. typedef long ma_snd_pcm_sframes_t;
  21394. typedef int ma_snd_pcm_stream_t;
  21395. typedef int ma_snd_pcm_format_t;
  21396. typedef int ma_snd_pcm_access_t;
  21397. typedef int ma_snd_pcm_state_t;
  21398. typedef struct ma_snd_pcm_t ma_snd_pcm_t;
  21399. typedef struct ma_snd_pcm_hw_params_t ma_snd_pcm_hw_params_t;
  21400. typedef struct ma_snd_pcm_sw_params_t ma_snd_pcm_sw_params_t;
  21401. typedef struct ma_snd_pcm_format_mask_t ma_snd_pcm_format_mask_t;
  21402. typedef struct ma_snd_pcm_info_t ma_snd_pcm_info_t;
  21403. typedef struct
  21404. {
  21405. void* addr;
  21406. unsigned int first;
  21407. unsigned int step;
  21408. } ma_snd_pcm_channel_area_t;
  21409. typedef struct
  21410. {
  21411. unsigned int channels;
  21412. unsigned int pos[1];
  21413. } ma_snd_pcm_chmap_t;
  21414. /* snd_pcm_state_t */
  21415. #define MA_SND_PCM_STATE_OPEN 0
  21416. #define MA_SND_PCM_STATE_SETUP 1
  21417. #define MA_SND_PCM_STATE_PREPARED 2
  21418. #define MA_SND_PCM_STATE_RUNNING 3
  21419. #define MA_SND_PCM_STATE_XRUN 4
  21420. #define MA_SND_PCM_STATE_DRAINING 5
  21421. #define MA_SND_PCM_STATE_PAUSED 6
  21422. #define MA_SND_PCM_STATE_SUSPENDED 7
  21423. #define MA_SND_PCM_STATE_DISCONNECTED 8
  21424. /* snd_pcm_stream_t */
  21425. #define MA_SND_PCM_STREAM_PLAYBACK 0
  21426. #define MA_SND_PCM_STREAM_CAPTURE 1
  21427. /* snd_pcm_format_t */
  21428. #define MA_SND_PCM_FORMAT_UNKNOWN -1
  21429. #define MA_SND_PCM_FORMAT_U8 1
  21430. #define MA_SND_PCM_FORMAT_S16_LE 2
  21431. #define MA_SND_PCM_FORMAT_S16_BE 3
  21432. #define MA_SND_PCM_FORMAT_S24_LE 6
  21433. #define MA_SND_PCM_FORMAT_S24_BE 7
  21434. #define MA_SND_PCM_FORMAT_S32_LE 10
  21435. #define MA_SND_PCM_FORMAT_S32_BE 11
  21436. #define MA_SND_PCM_FORMAT_FLOAT_LE 14
  21437. #define MA_SND_PCM_FORMAT_FLOAT_BE 15
  21438. #define MA_SND_PCM_FORMAT_FLOAT64_LE 16
  21439. #define MA_SND_PCM_FORMAT_FLOAT64_BE 17
  21440. #define MA_SND_PCM_FORMAT_MU_LAW 20
  21441. #define MA_SND_PCM_FORMAT_A_LAW 21
  21442. #define MA_SND_PCM_FORMAT_S24_3LE 32
  21443. #define MA_SND_PCM_FORMAT_S24_3BE 33
  21444. /* snd_pcm_access_t */
  21445. #define MA_SND_PCM_ACCESS_MMAP_INTERLEAVED 0
  21446. #define MA_SND_PCM_ACCESS_MMAP_NONINTERLEAVED 1
  21447. #define MA_SND_PCM_ACCESS_MMAP_COMPLEX 2
  21448. #define MA_SND_PCM_ACCESS_RW_INTERLEAVED 3
  21449. #define MA_SND_PCM_ACCESS_RW_NONINTERLEAVED 4
  21450. /* Channel positions. */
  21451. #define MA_SND_CHMAP_UNKNOWN 0
  21452. #define MA_SND_CHMAP_NA 1
  21453. #define MA_SND_CHMAP_MONO 2
  21454. #define MA_SND_CHMAP_FL 3
  21455. #define MA_SND_CHMAP_FR 4
  21456. #define MA_SND_CHMAP_RL 5
  21457. #define MA_SND_CHMAP_RR 6
  21458. #define MA_SND_CHMAP_FC 7
  21459. #define MA_SND_CHMAP_LFE 8
  21460. #define MA_SND_CHMAP_SL 9
  21461. #define MA_SND_CHMAP_SR 10
  21462. #define MA_SND_CHMAP_RC 11
  21463. #define MA_SND_CHMAP_FLC 12
  21464. #define MA_SND_CHMAP_FRC 13
  21465. #define MA_SND_CHMAP_RLC 14
  21466. #define MA_SND_CHMAP_RRC 15
  21467. #define MA_SND_CHMAP_FLW 16
  21468. #define MA_SND_CHMAP_FRW 17
  21469. #define MA_SND_CHMAP_FLH 18
  21470. #define MA_SND_CHMAP_FCH 19
  21471. #define MA_SND_CHMAP_FRH 20
  21472. #define MA_SND_CHMAP_TC 21
  21473. #define MA_SND_CHMAP_TFL 22
  21474. #define MA_SND_CHMAP_TFR 23
  21475. #define MA_SND_CHMAP_TFC 24
  21476. #define MA_SND_CHMAP_TRL 25
  21477. #define MA_SND_CHMAP_TRR 26
  21478. #define MA_SND_CHMAP_TRC 27
  21479. #define MA_SND_CHMAP_TFLC 28
  21480. #define MA_SND_CHMAP_TFRC 29
  21481. #define MA_SND_CHMAP_TSL 30
  21482. #define MA_SND_CHMAP_TSR 31
  21483. #define MA_SND_CHMAP_LLFE 32
  21484. #define MA_SND_CHMAP_RLFE 33
  21485. #define MA_SND_CHMAP_BC 34
  21486. #define MA_SND_CHMAP_BLC 35
  21487. #define MA_SND_CHMAP_BRC 36
  21488. /* Open mode flags. */
  21489. #define MA_SND_PCM_NO_AUTO_RESAMPLE 0x00010000
  21490. #define MA_SND_PCM_NO_AUTO_CHANNELS 0x00020000
  21491. #define MA_SND_PCM_NO_AUTO_FORMAT 0x00040000
  21492. #endif
  21493. typedef int (* ma_snd_pcm_open_proc) (ma_snd_pcm_t **pcm, const char *name, ma_snd_pcm_stream_t stream, int mode);
  21494. typedef int (* ma_snd_pcm_close_proc) (ma_snd_pcm_t *pcm);
  21495. typedef size_t (* ma_snd_pcm_hw_params_sizeof_proc) (void);
  21496. typedef int (* ma_snd_pcm_hw_params_any_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  21497. 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);
  21498. 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);
  21499. 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);
  21500. 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);
  21501. 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);
  21502. 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);
  21503. 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);
  21504. 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);
  21505. 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);
  21506. 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);
  21507. 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);
  21508. 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);
  21509. typedef int (* ma_snd_pcm_hw_params_get_format_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_format_t *format);
  21510. typedef int (* ma_snd_pcm_hw_params_get_channels_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  21511. typedef int (* ma_snd_pcm_hw_params_get_channels_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  21512. typedef int (* ma_snd_pcm_hw_params_get_channels_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val);
  21513. typedef int (* ma_snd_pcm_hw_params_get_rate_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  21514. typedef int (* ma_snd_pcm_hw_params_get_rate_min_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  21515. typedef int (* ma_snd_pcm_hw_params_get_rate_max_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *rate, int *dir);
  21516. 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);
  21517. typedef int (* ma_snd_pcm_hw_params_get_periods_proc) (const ma_snd_pcm_hw_params_t *params, unsigned int *val, int *dir);
  21518. typedef int (* ma_snd_pcm_hw_params_get_access_proc) (const ma_snd_pcm_hw_params_t *params, ma_snd_pcm_access_t *_access);
  21519. 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);
  21520. 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);
  21521. 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);
  21522. typedef int (* ma_snd_pcm_hw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_hw_params_t *params);
  21523. typedef size_t (* ma_snd_pcm_sw_params_sizeof_proc) (void);
  21524. typedef int (* ma_snd_pcm_sw_params_current_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  21525. typedef int (* ma_snd_pcm_sw_params_get_boundary_proc) (const ma_snd_pcm_sw_params_t *params, ma_snd_pcm_uframes_t* val);
  21526. 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);
  21527. 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);
  21528. 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);
  21529. typedef int (* ma_snd_pcm_sw_params_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_sw_params_t *params);
  21530. typedef size_t (* ma_snd_pcm_format_mask_sizeof_proc) (void);
  21531. typedef int (* ma_snd_pcm_format_mask_test_proc) (const ma_snd_pcm_format_mask_t *mask, ma_snd_pcm_format_t val);
  21532. typedef ma_snd_pcm_chmap_t * (* ma_snd_pcm_get_chmap_proc) (ma_snd_pcm_t *pcm);
  21533. typedef ma_snd_pcm_state_t (* ma_snd_pcm_state_proc) (ma_snd_pcm_t *pcm);
  21534. typedef int (* ma_snd_pcm_prepare_proc) (ma_snd_pcm_t *pcm);
  21535. typedef int (* ma_snd_pcm_start_proc) (ma_snd_pcm_t *pcm);
  21536. typedef int (* ma_snd_pcm_drop_proc) (ma_snd_pcm_t *pcm);
  21537. typedef int (* ma_snd_pcm_drain_proc) (ma_snd_pcm_t *pcm);
  21538. typedef int (* ma_snd_pcm_reset_proc) (ma_snd_pcm_t *pcm);
  21539. typedef int (* ma_snd_device_name_hint_proc) (int card, const char *iface, void ***hints);
  21540. typedef char * (* ma_snd_device_name_get_hint_proc) (const void *hint, const char *id);
  21541. typedef int (* ma_snd_card_get_index_proc) (const char *name);
  21542. typedef int (* ma_snd_device_name_free_hint_proc) (void **hints);
  21543. 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);
  21544. 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);
  21545. typedef int (* ma_snd_pcm_recover_proc) (ma_snd_pcm_t *pcm, int err, int silent);
  21546. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_readi_proc) (ma_snd_pcm_t *pcm, void *buffer, ma_snd_pcm_uframes_t size);
  21547. 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);
  21548. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_proc) (ma_snd_pcm_t *pcm);
  21549. typedef ma_snd_pcm_sframes_t (* ma_snd_pcm_avail_update_proc) (ma_snd_pcm_t *pcm);
  21550. typedef int (* ma_snd_pcm_wait_proc) (ma_snd_pcm_t *pcm, int timeout);
  21551. typedef int (* ma_snd_pcm_nonblock_proc) (ma_snd_pcm_t *pcm, int nonblock);
  21552. typedef int (* ma_snd_pcm_info_proc) (ma_snd_pcm_t *pcm, ma_snd_pcm_info_t* info);
  21553. typedef size_t (* ma_snd_pcm_info_sizeof_proc) (void);
  21554. typedef const char* (* ma_snd_pcm_info_get_name_proc) (const ma_snd_pcm_info_t* info);
  21555. typedef int (* ma_snd_pcm_poll_descriptors_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int space);
  21556. typedef int (* ma_snd_pcm_poll_descriptors_count_proc) (ma_snd_pcm_t *pcm);
  21557. typedef int (* ma_snd_pcm_poll_descriptors_revents_proc) (ma_snd_pcm_t *pcm, struct pollfd *pfds, unsigned int nfds, unsigned short *revents);
  21558. typedef int (* ma_snd_config_update_free_global_proc) (void);
  21559. /* This array specifies each of the common devices that can be used for both playback and capture. */
  21560. static const char* g_maCommonDeviceNamesALSA[] = {
  21561. "default",
  21562. "null",
  21563. "pulse",
  21564. "jack"
  21565. };
  21566. /* This array allows us to blacklist specific playback devices. */
  21567. static const char* g_maBlacklistedPlaybackDeviceNamesALSA[] = {
  21568. ""
  21569. };
  21570. /* This array allows us to blacklist specific capture devices. */
  21571. static const char* g_maBlacklistedCaptureDeviceNamesALSA[] = {
  21572. ""
  21573. };
  21574. static ma_snd_pcm_format_t ma_convert_ma_format_to_alsa_format(ma_format format)
  21575. {
  21576. ma_snd_pcm_format_t ALSAFormats[] = {
  21577. MA_SND_PCM_FORMAT_UNKNOWN, /* ma_format_unknown */
  21578. MA_SND_PCM_FORMAT_U8, /* ma_format_u8 */
  21579. MA_SND_PCM_FORMAT_S16_LE, /* ma_format_s16 */
  21580. MA_SND_PCM_FORMAT_S24_3LE, /* ma_format_s24 */
  21581. MA_SND_PCM_FORMAT_S32_LE, /* ma_format_s32 */
  21582. MA_SND_PCM_FORMAT_FLOAT_LE /* ma_format_f32 */
  21583. };
  21584. if (ma_is_big_endian()) {
  21585. ALSAFormats[0] = MA_SND_PCM_FORMAT_UNKNOWN;
  21586. ALSAFormats[1] = MA_SND_PCM_FORMAT_U8;
  21587. ALSAFormats[2] = MA_SND_PCM_FORMAT_S16_BE;
  21588. ALSAFormats[3] = MA_SND_PCM_FORMAT_S24_3BE;
  21589. ALSAFormats[4] = MA_SND_PCM_FORMAT_S32_BE;
  21590. ALSAFormats[5] = MA_SND_PCM_FORMAT_FLOAT_BE;
  21591. }
  21592. return ALSAFormats[format];
  21593. }
  21594. static ma_format ma_format_from_alsa(ma_snd_pcm_format_t formatALSA)
  21595. {
  21596. if (ma_is_little_endian()) {
  21597. switch (formatALSA) {
  21598. case MA_SND_PCM_FORMAT_S16_LE: return ma_format_s16;
  21599. case MA_SND_PCM_FORMAT_S24_3LE: return ma_format_s24;
  21600. case MA_SND_PCM_FORMAT_S32_LE: return ma_format_s32;
  21601. case MA_SND_PCM_FORMAT_FLOAT_LE: return ma_format_f32;
  21602. default: break;
  21603. }
  21604. } else {
  21605. switch (formatALSA) {
  21606. case MA_SND_PCM_FORMAT_S16_BE: return ma_format_s16;
  21607. case MA_SND_PCM_FORMAT_S24_3BE: return ma_format_s24;
  21608. case MA_SND_PCM_FORMAT_S32_BE: return ma_format_s32;
  21609. case MA_SND_PCM_FORMAT_FLOAT_BE: return ma_format_f32;
  21610. default: break;
  21611. }
  21612. }
  21613. /* Endian agnostic. */
  21614. switch (formatALSA) {
  21615. case MA_SND_PCM_FORMAT_U8: return ma_format_u8;
  21616. default: return ma_format_unknown;
  21617. }
  21618. }
  21619. static ma_channel ma_convert_alsa_channel_position_to_ma_channel(unsigned int alsaChannelPos)
  21620. {
  21621. switch (alsaChannelPos)
  21622. {
  21623. case MA_SND_CHMAP_MONO: return MA_CHANNEL_MONO;
  21624. case MA_SND_CHMAP_FL: return MA_CHANNEL_FRONT_LEFT;
  21625. case MA_SND_CHMAP_FR: return MA_CHANNEL_FRONT_RIGHT;
  21626. case MA_SND_CHMAP_RL: return MA_CHANNEL_BACK_LEFT;
  21627. case MA_SND_CHMAP_RR: return MA_CHANNEL_BACK_RIGHT;
  21628. case MA_SND_CHMAP_FC: return MA_CHANNEL_FRONT_CENTER;
  21629. case MA_SND_CHMAP_LFE: return MA_CHANNEL_LFE;
  21630. case MA_SND_CHMAP_SL: return MA_CHANNEL_SIDE_LEFT;
  21631. case MA_SND_CHMAP_SR: return MA_CHANNEL_SIDE_RIGHT;
  21632. case MA_SND_CHMAP_RC: return MA_CHANNEL_BACK_CENTER;
  21633. case MA_SND_CHMAP_FLC: return MA_CHANNEL_FRONT_LEFT_CENTER;
  21634. case MA_SND_CHMAP_FRC: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  21635. case MA_SND_CHMAP_RLC: return 0;
  21636. case MA_SND_CHMAP_RRC: return 0;
  21637. case MA_SND_CHMAP_FLW: return 0;
  21638. case MA_SND_CHMAP_FRW: return 0;
  21639. case MA_SND_CHMAP_FLH: return 0;
  21640. case MA_SND_CHMAP_FCH: return 0;
  21641. case MA_SND_CHMAP_FRH: return 0;
  21642. case MA_SND_CHMAP_TC: return MA_CHANNEL_TOP_CENTER;
  21643. case MA_SND_CHMAP_TFL: return MA_CHANNEL_TOP_FRONT_LEFT;
  21644. case MA_SND_CHMAP_TFR: return MA_CHANNEL_TOP_FRONT_RIGHT;
  21645. case MA_SND_CHMAP_TFC: return MA_CHANNEL_TOP_FRONT_CENTER;
  21646. case MA_SND_CHMAP_TRL: return MA_CHANNEL_TOP_BACK_LEFT;
  21647. case MA_SND_CHMAP_TRR: return MA_CHANNEL_TOP_BACK_RIGHT;
  21648. case MA_SND_CHMAP_TRC: return MA_CHANNEL_TOP_BACK_CENTER;
  21649. default: break;
  21650. }
  21651. return 0;
  21652. }
  21653. static ma_bool32 ma_is_common_device_name__alsa(const char* name)
  21654. {
  21655. size_t iName;
  21656. for (iName = 0; iName < ma_countof(g_maCommonDeviceNamesALSA); ++iName) {
  21657. if (ma_strcmp(name, g_maCommonDeviceNamesALSA[iName]) == 0) {
  21658. return MA_TRUE;
  21659. }
  21660. }
  21661. return MA_FALSE;
  21662. }
  21663. static ma_bool32 ma_is_playback_device_blacklisted__alsa(const char* name)
  21664. {
  21665. size_t iName;
  21666. for (iName = 0; iName < ma_countof(g_maBlacklistedPlaybackDeviceNamesALSA); ++iName) {
  21667. if (ma_strcmp(name, g_maBlacklistedPlaybackDeviceNamesALSA[iName]) == 0) {
  21668. return MA_TRUE;
  21669. }
  21670. }
  21671. return MA_FALSE;
  21672. }
  21673. static ma_bool32 ma_is_capture_device_blacklisted__alsa(const char* name)
  21674. {
  21675. size_t iName;
  21676. for (iName = 0; iName < ma_countof(g_maBlacklistedCaptureDeviceNamesALSA); ++iName) {
  21677. if (ma_strcmp(name, g_maBlacklistedCaptureDeviceNamesALSA[iName]) == 0) {
  21678. return MA_TRUE;
  21679. }
  21680. }
  21681. return MA_FALSE;
  21682. }
  21683. static ma_bool32 ma_is_device_blacklisted__alsa(ma_device_type deviceType, const char* name)
  21684. {
  21685. if (deviceType == ma_device_type_playback) {
  21686. return ma_is_playback_device_blacklisted__alsa(name);
  21687. } else {
  21688. return ma_is_capture_device_blacklisted__alsa(name);
  21689. }
  21690. }
  21691. static const char* ma_find_char(const char* str, char c, int* index)
  21692. {
  21693. int i = 0;
  21694. for (;;) {
  21695. if (str[i] == '\0') {
  21696. if (index) *index = -1;
  21697. return NULL;
  21698. }
  21699. if (str[i] == c) {
  21700. if (index) *index = i;
  21701. return str + i;
  21702. }
  21703. i += 1;
  21704. }
  21705. /* Should never get here, but treat it as though the character was not found to make me feel better inside. */
  21706. if (index) *index = -1;
  21707. return NULL;
  21708. }
  21709. static ma_bool32 ma_is_device_name_in_hw_format__alsa(const char* hwid)
  21710. {
  21711. /* This function is just checking whether or not hwid is in "hw:%d,%d" format. */
  21712. int commaPos;
  21713. const char* dev;
  21714. int i;
  21715. if (hwid == NULL) {
  21716. return MA_FALSE;
  21717. }
  21718. if (hwid[0] != 'h' || hwid[1] != 'w' || hwid[2] != ':') {
  21719. return MA_FALSE;
  21720. }
  21721. hwid += 3;
  21722. dev = ma_find_char(hwid, ',', &commaPos);
  21723. if (dev == NULL) {
  21724. return MA_FALSE;
  21725. } else {
  21726. dev += 1; /* Skip past the ",". */
  21727. }
  21728. /* Check if the part between the ":" and the "," contains only numbers. If not, return false. */
  21729. for (i = 0; i < commaPos; ++i) {
  21730. if (hwid[i] < '0' || hwid[i] > '9') {
  21731. return MA_FALSE;
  21732. }
  21733. }
  21734. /* Check if everything after the "," is numeric. If not, return false. */
  21735. i = 0;
  21736. while (dev[i] != '\0') {
  21737. if (dev[i] < '0' || dev[i] > '9') {
  21738. return MA_FALSE;
  21739. }
  21740. i += 1;
  21741. }
  21742. return MA_TRUE;
  21743. }
  21744. 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. */
  21745. {
  21746. /* src should look something like this: "hw:CARD=I82801AAICH,DEV=0" */
  21747. int colonPos;
  21748. int commaPos;
  21749. char card[256];
  21750. const char* dev;
  21751. int cardIndex;
  21752. if (dst == NULL) {
  21753. return -1;
  21754. }
  21755. if (dstSize < 7) {
  21756. return -1; /* Absolute minimum size of the output buffer is 7 bytes. */
  21757. }
  21758. *dst = '\0'; /* Safety. */
  21759. if (src == NULL) {
  21760. return -1;
  21761. }
  21762. /* If the input name is already in "hw:%d,%d" format, just return that verbatim. */
  21763. if (ma_is_device_name_in_hw_format__alsa(src)) {
  21764. return ma_strcpy_s(dst, dstSize, src);
  21765. }
  21766. src = ma_find_char(src, ':', &colonPos);
  21767. if (src == NULL) {
  21768. return -1; /* Couldn't find a colon */
  21769. }
  21770. dev = ma_find_char(src, ',', &commaPos);
  21771. if (dev == NULL) {
  21772. dev = "0";
  21773. ma_strncpy_s(card, sizeof(card), src+6, (size_t)-1); /* +6 = ":CARD=" */
  21774. } else {
  21775. dev = dev + 5; /* +5 = ",DEV=" */
  21776. ma_strncpy_s(card, sizeof(card), src+6, commaPos-6); /* +6 = ":CARD=" */
  21777. }
  21778. cardIndex = ((ma_snd_card_get_index_proc)pContext->alsa.snd_card_get_index)(card);
  21779. if (cardIndex < 0) {
  21780. return -2; /* Failed to retrieve the card index. */
  21781. }
  21782. /* Construction. */
  21783. dst[0] = 'h'; dst[1] = 'w'; dst[2] = ':';
  21784. if (ma_itoa_s(cardIndex, dst+3, dstSize-3, 10) != 0) {
  21785. return -3;
  21786. }
  21787. if (ma_strcat_s(dst, dstSize, ",") != 0) {
  21788. return -3;
  21789. }
  21790. if (ma_strcat_s(dst, dstSize, dev) != 0) {
  21791. return -3;
  21792. }
  21793. return 0;
  21794. }
  21795. static ma_bool32 ma_does_id_exist_in_list__alsa(ma_device_id* pUniqueIDs, ma_uint32 count, const char* pHWID)
  21796. {
  21797. ma_uint32 i;
  21798. MA_ASSERT(pHWID != NULL);
  21799. for (i = 0; i < count; ++i) {
  21800. if (ma_strcmp(pUniqueIDs[i].alsa, pHWID) == 0) {
  21801. return MA_TRUE;
  21802. }
  21803. }
  21804. return MA_FALSE;
  21805. }
  21806. 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)
  21807. {
  21808. ma_snd_pcm_t* pPCM;
  21809. ma_snd_pcm_stream_t stream;
  21810. MA_ASSERT(pContext != NULL);
  21811. MA_ASSERT(ppPCM != NULL);
  21812. *ppPCM = NULL;
  21813. pPCM = NULL;
  21814. stream = (deviceType == ma_device_type_playback) ? MA_SND_PCM_STREAM_PLAYBACK : MA_SND_PCM_STREAM_CAPTURE;
  21815. if (pDeviceID == NULL) {
  21816. ma_bool32 isDeviceOpen;
  21817. size_t i;
  21818. /*
  21819. We're opening the default device. I don't know if trying anything other than "default" is necessary, but it makes
  21820. me feel better to try as hard as we can get to get _something_ working.
  21821. */
  21822. const char* defaultDeviceNames[] = {
  21823. "default",
  21824. NULL,
  21825. NULL,
  21826. NULL,
  21827. NULL,
  21828. NULL,
  21829. NULL
  21830. };
  21831. if (shareMode == ma_share_mode_exclusive) {
  21832. defaultDeviceNames[1] = "hw";
  21833. defaultDeviceNames[2] = "hw:0";
  21834. defaultDeviceNames[3] = "hw:0,0";
  21835. } else {
  21836. if (deviceType == ma_device_type_playback) {
  21837. defaultDeviceNames[1] = "dmix";
  21838. defaultDeviceNames[2] = "dmix:0";
  21839. defaultDeviceNames[3] = "dmix:0,0";
  21840. } else {
  21841. defaultDeviceNames[1] = "dsnoop";
  21842. defaultDeviceNames[2] = "dsnoop:0";
  21843. defaultDeviceNames[3] = "dsnoop:0,0";
  21844. }
  21845. defaultDeviceNames[4] = "hw";
  21846. defaultDeviceNames[5] = "hw:0";
  21847. defaultDeviceNames[6] = "hw:0,0";
  21848. }
  21849. isDeviceOpen = MA_FALSE;
  21850. for (i = 0; i < ma_countof(defaultDeviceNames); ++i) {
  21851. if (defaultDeviceNames[i] != NULL && defaultDeviceNames[i][0] != '\0') {
  21852. if (((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, defaultDeviceNames[i], stream, openMode) == 0) {
  21853. isDeviceOpen = MA_TRUE;
  21854. break;
  21855. }
  21856. }
  21857. }
  21858. if (!isDeviceOpen) {
  21859. 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.");
  21860. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  21861. }
  21862. } else {
  21863. /*
  21864. We're trying to open a specific device. There's a few things to consider here:
  21865. 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
  21866. an ID of this format is specified, it indicates to miniaudio that it can try different combinations of plugins ("hw", "dmix", etc.) until it
  21867. 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").
  21868. */
  21869. /* May end up needing to make small adjustments to the ID, so make a copy. */
  21870. ma_device_id deviceID = *pDeviceID;
  21871. int resultALSA = -ENODEV;
  21872. if (deviceID.alsa[0] != ':') {
  21873. /* The ID is not in ":0,0" format. Use the ID exactly as-is. */
  21874. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, deviceID.alsa, stream, openMode);
  21875. } else {
  21876. char hwid[256];
  21877. /* The ID is in ":0,0" format. Try different plugins depending on the shared mode. */
  21878. if (deviceID.alsa[1] == '\0') {
  21879. deviceID.alsa[0] = '\0'; /* An ID of ":" should be converted to "". */
  21880. }
  21881. if (shareMode == ma_share_mode_shared) {
  21882. if (deviceType == ma_device_type_playback) {
  21883. ma_strcpy_s(hwid, sizeof(hwid), "dmix");
  21884. } else {
  21885. ma_strcpy_s(hwid, sizeof(hwid), "dsnoop");
  21886. }
  21887. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  21888. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  21889. }
  21890. }
  21891. /* 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. */
  21892. if (resultALSA != 0) {
  21893. ma_strcpy_s(hwid, sizeof(hwid), "hw");
  21894. if (ma_strcat_s(hwid, sizeof(hwid), deviceID.alsa) == 0) {
  21895. resultALSA = ((ma_snd_pcm_open_proc)pContext->alsa.snd_pcm_open)(&pPCM, hwid, stream, openMode);
  21896. }
  21897. }
  21898. }
  21899. if (resultALSA < 0) {
  21900. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_open() failed.");
  21901. return ma_result_from_errno(-resultALSA);
  21902. }
  21903. }
  21904. *ppPCM = pPCM;
  21905. return MA_SUCCESS;
  21906. }
  21907. static ma_result ma_context_enumerate_devices__alsa(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  21908. {
  21909. int resultALSA;
  21910. ma_bool32 cbResult = MA_TRUE;
  21911. char** ppDeviceHints;
  21912. ma_device_id* pUniqueIDs = NULL;
  21913. ma_uint32 uniqueIDCount = 0;
  21914. char** ppNextDeviceHint;
  21915. MA_ASSERT(pContext != NULL);
  21916. MA_ASSERT(callback != NULL);
  21917. ma_mutex_lock(&pContext->alsa.internalDeviceEnumLock);
  21918. resultALSA = ((ma_snd_device_name_hint_proc)pContext->alsa.snd_device_name_hint)(-1, "pcm", (void***)&ppDeviceHints);
  21919. if (resultALSA < 0) {
  21920. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  21921. return ma_result_from_errno(-resultALSA);
  21922. }
  21923. ppNextDeviceHint = ppDeviceHints;
  21924. while (*ppNextDeviceHint != NULL) {
  21925. char* NAME = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "NAME");
  21926. char* DESC = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "DESC");
  21927. char* IOID = ((ma_snd_device_name_get_hint_proc)pContext->alsa.snd_device_name_get_hint)(*ppNextDeviceHint, "IOID");
  21928. ma_device_type deviceType = ma_device_type_playback;
  21929. ma_bool32 stopEnumeration = MA_FALSE;
  21930. char hwid[sizeof(pUniqueIDs->alsa)];
  21931. ma_device_info deviceInfo;
  21932. if ((IOID == NULL || ma_strcmp(IOID, "Output") == 0)) {
  21933. deviceType = ma_device_type_playback;
  21934. }
  21935. if ((IOID != NULL && ma_strcmp(IOID, "Input" ) == 0)) {
  21936. deviceType = ma_device_type_capture;
  21937. }
  21938. if (NAME != NULL) {
  21939. if (pContext->alsa.useVerboseDeviceEnumeration) {
  21940. /* Verbose mode. Use the name exactly as-is. */
  21941. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  21942. } else {
  21943. /* Simplified mode. Use ":%d,%d" format. */
  21944. if (ma_convert_device_name_to_hw_format__alsa(pContext, hwid, sizeof(hwid), NAME) == 0) {
  21945. /*
  21946. At this point, hwid looks like "hw:0,0". In simplified enumeration mode, we actually want to strip off the
  21947. plugin name so it looks like ":0,0". The reason for this is that this special format is detected at device
  21948. initialization time and is used as an indicator to try and use the most appropriate plugin depending on the
  21949. device type and sharing mode.
  21950. */
  21951. char* dst = hwid;
  21952. char* src = hwid+2;
  21953. while ((*dst++ = *src++));
  21954. } else {
  21955. /* Conversion to "hw:%d,%d" failed. Just use the name as-is. */
  21956. ma_strncpy_s(hwid, sizeof(hwid), NAME, (size_t)-1);
  21957. }
  21958. if (ma_does_id_exist_in_list__alsa(pUniqueIDs, uniqueIDCount, hwid)) {
  21959. goto next_device; /* The device has already been enumerated. Move on to the next one. */
  21960. } else {
  21961. /* The device has not yet been enumerated. Make sure it's added to our list so that it's not enumerated again. */
  21962. size_t newCapacity = sizeof(*pUniqueIDs) * (uniqueIDCount + 1);
  21963. ma_device_id* pNewUniqueIDs = (ma_device_id*)ma_realloc(pUniqueIDs, newCapacity, &pContext->allocationCallbacks);
  21964. if (pNewUniqueIDs == NULL) {
  21965. goto next_device; /* Failed to allocate memory. */
  21966. }
  21967. pUniqueIDs = pNewUniqueIDs;
  21968. MA_COPY_MEMORY(pUniqueIDs[uniqueIDCount].alsa, hwid, sizeof(hwid));
  21969. uniqueIDCount += 1;
  21970. }
  21971. }
  21972. } else {
  21973. MA_ZERO_MEMORY(hwid, sizeof(hwid));
  21974. }
  21975. MA_ZERO_OBJECT(&deviceInfo);
  21976. ma_strncpy_s(deviceInfo.id.alsa, sizeof(deviceInfo.id.alsa), hwid, (size_t)-1);
  21977. /*
  21978. 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
  21979. just use the name of "default" as the indicator.
  21980. */
  21981. if (ma_strcmp(deviceInfo.id.alsa, "default") == 0) {
  21982. deviceInfo.isDefault = MA_TRUE;
  21983. }
  21984. /*
  21985. DESC is the friendly name. We treat this slightly differently depending on whether or not we are using verbose
  21986. device enumeration. In verbose mode we want to take the entire description so that the end-user can distinguish
  21987. between the subdevices of each card/dev pair. In simplified mode, however, we only want the first part of the
  21988. description.
  21989. The value in DESC seems to be split into two lines, with the first line being the name of the device and the
  21990. second line being a description of the device. I don't like having the description be across two lines because
  21991. it makes formatting ugly and annoying. I'm therefore deciding to put it all on a single line with the second line
  21992. being put into parentheses. In simplified mode I'm just stripping the second line entirely.
  21993. */
  21994. if (DESC != NULL) {
  21995. int lfPos;
  21996. const char* line2 = ma_find_char(DESC, '\n', &lfPos);
  21997. if (line2 != NULL) {
  21998. line2 += 1; /* Skip past the new-line character. */
  21999. if (pContext->alsa.useVerboseDeviceEnumeration) {
  22000. /* Verbose mode. Put the second line in brackets. */
  22001. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22002. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), " (");
  22003. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), line2);
  22004. ma_strcat_s (deviceInfo.name, sizeof(deviceInfo.name), ")");
  22005. } else {
  22006. /* Simplified mode. Strip the second line entirely. */
  22007. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, lfPos);
  22008. }
  22009. } else {
  22010. /* There's no second line. Just copy the whole description. */
  22011. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), DESC, (size_t)-1);
  22012. }
  22013. }
  22014. if (!ma_is_device_blacklisted__alsa(deviceType, NAME)) {
  22015. cbResult = callback(pContext, deviceType, &deviceInfo, pUserData);
  22016. }
  22017. /*
  22018. Some devices are both playback and capture, but they are only enumerated by ALSA once. We need to fire the callback
  22019. again for the other device type in this case. We do this for known devices and where the IOID hint is NULL, which
  22020. means both Input and Output.
  22021. */
  22022. if (cbResult) {
  22023. if (ma_is_common_device_name__alsa(NAME) || IOID == NULL) {
  22024. if (deviceType == ma_device_type_playback) {
  22025. if (!ma_is_capture_device_blacklisted__alsa(NAME)) {
  22026. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  22027. }
  22028. } else {
  22029. if (!ma_is_playback_device_blacklisted__alsa(NAME)) {
  22030. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  22031. }
  22032. }
  22033. }
  22034. }
  22035. if (cbResult == MA_FALSE) {
  22036. stopEnumeration = MA_TRUE;
  22037. }
  22038. next_device:
  22039. free(NAME);
  22040. free(DESC);
  22041. free(IOID);
  22042. ppNextDeviceHint += 1;
  22043. /* We need to stop enumeration if the callback returned false. */
  22044. if (stopEnumeration) {
  22045. break;
  22046. }
  22047. }
  22048. ma_free(pUniqueIDs, &pContext->allocationCallbacks);
  22049. ((ma_snd_device_name_free_hint_proc)pContext->alsa.snd_device_name_free_hint)((void**)ppDeviceHints);
  22050. ma_mutex_unlock(&pContext->alsa.internalDeviceEnumLock);
  22051. return MA_SUCCESS;
  22052. }
  22053. typedef struct
  22054. {
  22055. ma_device_type deviceType;
  22056. const ma_device_id* pDeviceID;
  22057. ma_share_mode shareMode;
  22058. ma_device_info* pDeviceInfo;
  22059. ma_bool32 foundDevice;
  22060. } ma_context_get_device_info_enum_callback_data__alsa;
  22061. 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)
  22062. {
  22063. ma_context_get_device_info_enum_callback_data__alsa* pData = (ma_context_get_device_info_enum_callback_data__alsa*)pUserData;
  22064. MA_ASSERT(pData != NULL);
  22065. (void)pContext;
  22066. if (pData->pDeviceID == NULL && ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  22067. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22068. pData->foundDevice = MA_TRUE;
  22069. } else {
  22070. if (pData->deviceType == deviceType && (pData->pDeviceID != NULL && ma_strcmp(pData->pDeviceID->alsa, pDeviceInfo->id.alsa) == 0)) {
  22071. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pDeviceInfo->name, (size_t)-1);
  22072. pData->foundDevice = MA_TRUE;
  22073. }
  22074. }
  22075. /* Keep enumerating until we have found the device. */
  22076. return !pData->foundDevice;
  22077. }
  22078. 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)
  22079. {
  22080. MA_ASSERT(pPCM != NULL);
  22081. MA_ASSERT(pHWParams != NULL);
  22082. MA_ASSERT(pDeviceInfo != NULL);
  22083. 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) {
  22084. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  22085. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  22086. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  22087. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  22088. pDeviceInfo->nativeDataFormatCount += 1;
  22089. }
  22090. }
  22091. 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)
  22092. {
  22093. ma_uint32 iSampleRate;
  22094. unsigned int minSampleRate;
  22095. unsigned int maxSampleRate;
  22096. int sampleRateDir; /* Not used. Just passed into snd_pcm_hw_params_get_rate_min/max(). */
  22097. /* There could be a range. */
  22098. ((ma_snd_pcm_hw_params_get_rate_min_proc)pContext->alsa.snd_pcm_hw_params_get_rate_min)(pHWParams, &minSampleRate, &sampleRateDir);
  22099. ((ma_snd_pcm_hw_params_get_rate_max_proc)pContext->alsa.snd_pcm_hw_params_get_rate_max)(pHWParams, &maxSampleRate, &sampleRateDir);
  22100. /* Make sure our sample rates are clamped to sane values. Stupid devices like "pulse" will reports rates like "1" which is ridiculus. */
  22101. minSampleRate = ma_clamp(minSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22102. maxSampleRate = ma_clamp(maxSampleRate, (unsigned int)ma_standard_sample_rate_min, (unsigned int)ma_standard_sample_rate_max);
  22103. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  22104. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  22105. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  22106. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, standardSampleRate, flags, pDeviceInfo);
  22107. }
  22108. }
  22109. /* Now make sure our min and max rates are included just in case they aren't in the range of our standard rates. */
  22110. if (!ma_is_standard_sample_rate(minSampleRate)) {
  22111. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, minSampleRate, flags, pDeviceInfo);
  22112. }
  22113. if (!ma_is_standard_sample_rate(maxSampleRate) && maxSampleRate != minSampleRate) {
  22114. ma_context_test_rate_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, maxSampleRate, flags, pDeviceInfo);
  22115. }
  22116. }
  22117. 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)
  22118. {
  22119. ma_context_get_device_info_enum_callback_data__alsa data;
  22120. ma_result result;
  22121. int resultALSA;
  22122. ma_snd_pcm_t* pPCM;
  22123. ma_snd_pcm_hw_params_t* pHWParams;
  22124. ma_uint32 iFormat;
  22125. ma_uint32 iChannel;
  22126. MA_ASSERT(pContext != NULL);
  22127. /* We just enumerate to find basic information about the device. */
  22128. data.deviceType = deviceType;
  22129. data.pDeviceID = pDeviceID;
  22130. data.pDeviceInfo = pDeviceInfo;
  22131. data.foundDevice = MA_FALSE;
  22132. result = ma_context_enumerate_devices__alsa(pContext, ma_context_get_device_info_enum_callback__alsa, &data);
  22133. if (result != MA_SUCCESS) {
  22134. return result;
  22135. }
  22136. if (!data.foundDevice) {
  22137. return MA_NO_DEVICE;
  22138. }
  22139. if (ma_strcmp(pDeviceInfo->id.alsa, "default") == 0) {
  22140. pDeviceInfo->isDefault = MA_TRUE;
  22141. }
  22142. /* For detailed info we need to open the device. */
  22143. result = ma_context_open_pcm__alsa(pContext, ma_share_mode_shared, deviceType, pDeviceID, 0, &pPCM);
  22144. if (result != MA_SUCCESS) {
  22145. return result;
  22146. }
  22147. /* We need to initialize a HW parameters object in order to know what formats are supported. */
  22148. 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);
  22149. if (pHWParams == NULL) {
  22150. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  22151. return MA_OUT_OF_MEMORY;
  22152. }
  22153. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  22154. if (resultALSA < 0) {
  22155. ma_free(pHWParams, &pContext->allocationCallbacks);
  22156. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  22157. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  22158. return ma_result_from_errno(-resultALSA);
  22159. }
  22160. /*
  22161. Some ALSA devices can support many permutations of formats, channels and rates. We only support
  22162. a fixed number of permutations which means we need to employ some strategies to ensure the best
  22163. combinations are returned. An example is the "pulse" device which can do it's own data conversion
  22164. in software and as a result can support any combination of format, channels and rate.
  22165. We want to ensure the the first data formats are the best. We have a list of favored sample
  22166. formats and sample rates, so these will be the basis of our iteration.
  22167. */
  22168. /* Formats. We just iterate over our standard formats and test them, making sure we reset the configuration space each iteration. */
  22169. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  22170. ma_format format = g_maFormatPriorities[iFormat];
  22171. /*
  22172. For each format we need to make sure we reset the configuration space so we don't return
  22173. channel counts and rates that aren't compatible with a format.
  22174. */
  22175. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  22176. /* Test the format first. If this fails it means the format is not supported and we can skip it. */
  22177. 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) {
  22178. /* The format is supported. */
  22179. unsigned int minChannels;
  22180. unsigned int maxChannels;
  22181. /*
  22182. The configuration space needs to be restricted to this format so we can get an accurate
  22183. picture of which sample rates and channel counts are support with this format.
  22184. */
  22185. ((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));
  22186. /* Now we need to check for supported channels. */
  22187. ((ma_snd_pcm_hw_params_get_channels_min_proc)pContext->alsa.snd_pcm_hw_params_get_channels_min)(pHWParams, &minChannels);
  22188. ((ma_snd_pcm_hw_params_get_channels_max_proc)pContext->alsa.snd_pcm_hw_params_get_channels_max)(pHWParams, &maxChannels);
  22189. if (minChannels > MA_MAX_CHANNELS) {
  22190. continue; /* Too many channels. */
  22191. }
  22192. if (maxChannels < MA_MIN_CHANNELS) {
  22193. continue; /* Not enough channels. */
  22194. }
  22195. /*
  22196. Make sure the channel count is clamped. This is mainly intended for the max channels
  22197. because some devices can report an unbound maximum.
  22198. */
  22199. minChannels = ma_clamp(minChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  22200. maxChannels = ma_clamp(maxChannels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  22201. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  22202. /* 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. */
  22203. 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. */
  22204. } else {
  22205. /* The device only supports a specific set of channels. We need to iterate over all of them. */
  22206. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  22207. /* Test the channel before applying it to the configuration space. */
  22208. unsigned int channels = iChannel;
  22209. /* Make sure our channel range is reset before testing again or else we'll always fail the test. */
  22210. ((ma_snd_pcm_hw_params_any_proc)pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  22211. ((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));
  22212. if (((ma_snd_pcm_hw_params_test_channels_proc)pContext->alsa.snd_pcm_hw_params_test_channels)(pPCM, pHWParams, channels) == 0) {
  22213. /* The channel count is supported. */
  22214. /* The configuration space now needs to be restricted to the channel count before extracting the sample rate. */
  22215. ((ma_snd_pcm_hw_params_set_channels_proc)pContext->alsa.snd_pcm_hw_params_set_channels)(pPCM, pHWParams, channels);
  22216. /* Only after the configuration space has been restricted to the specific channel count should we iterate over our sample rates. */
  22217. ma_context_iterate_rates_and_add_native_data_format__alsa(pContext, pPCM, pHWParams, format, channels, 0, pDeviceInfo);
  22218. } else {
  22219. /* The channel count is not supported. Skip. */
  22220. }
  22221. }
  22222. }
  22223. } else {
  22224. /* The format is not supported. Skip. */
  22225. }
  22226. }
  22227. ma_free(pHWParams, &pContext->allocationCallbacks);
  22228. ((ma_snd_pcm_close_proc)pContext->alsa.snd_pcm_close)(pPCM);
  22229. return MA_SUCCESS;
  22230. }
  22231. static ma_result ma_device_uninit__alsa(ma_device* pDevice)
  22232. {
  22233. MA_ASSERT(pDevice != NULL);
  22234. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) {
  22235. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  22236. close(pDevice->alsa.wakeupfdCapture);
  22237. ma_free(pDevice->alsa.pPollDescriptorsCapture, &pDevice->pContext->allocationCallbacks);
  22238. }
  22239. if ((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) {
  22240. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  22241. close(pDevice->alsa.wakeupfdPlayback);
  22242. ma_free(pDevice->alsa.pPollDescriptorsPlayback, &pDevice->pContext->allocationCallbacks);
  22243. }
  22244. return MA_SUCCESS;
  22245. }
  22246. 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)
  22247. {
  22248. ma_result result;
  22249. int resultALSA;
  22250. ma_snd_pcm_t* pPCM;
  22251. ma_bool32 isUsingMMap;
  22252. ma_snd_pcm_format_t formatALSA;
  22253. ma_format internalFormat;
  22254. ma_uint32 internalChannels;
  22255. ma_uint32 internalSampleRate;
  22256. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  22257. ma_uint32 internalPeriodSizeInFrames;
  22258. ma_uint32 internalPeriods;
  22259. int openMode;
  22260. ma_snd_pcm_hw_params_t* pHWParams;
  22261. ma_snd_pcm_sw_params_t* pSWParams;
  22262. ma_snd_pcm_uframes_t bufferBoundary;
  22263. int pollDescriptorCount;
  22264. struct pollfd* pPollDescriptors;
  22265. int wakeupfd;
  22266. MA_ASSERT(pConfig != NULL);
  22267. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should only be called for playback _or_ capture, never duplex. */
  22268. MA_ASSERT(pDevice != NULL);
  22269. formatALSA = ma_convert_ma_format_to_alsa_format(pDescriptor->format);
  22270. openMode = 0;
  22271. if (pConfig->alsa.noAutoResample) {
  22272. openMode |= MA_SND_PCM_NO_AUTO_RESAMPLE;
  22273. }
  22274. if (pConfig->alsa.noAutoChannels) {
  22275. openMode |= MA_SND_PCM_NO_AUTO_CHANNELS;
  22276. }
  22277. if (pConfig->alsa.noAutoFormat) {
  22278. openMode |= MA_SND_PCM_NO_AUTO_FORMAT;
  22279. }
  22280. result = ma_context_open_pcm__alsa(pDevice->pContext, pDescriptor->shareMode, deviceType, pDescriptor->pDeviceID, openMode, &pPCM);
  22281. if (result != MA_SUCCESS) {
  22282. return result;
  22283. }
  22284. /* Hardware parameters. */
  22285. 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);
  22286. if (pHWParams == NULL) {
  22287. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22288. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for hardware parameters.");
  22289. return MA_OUT_OF_MEMORY;
  22290. }
  22291. resultALSA = ((ma_snd_pcm_hw_params_any_proc)pDevice->pContext->alsa.snd_pcm_hw_params_any)(pPCM, pHWParams);
  22292. if (resultALSA < 0) {
  22293. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22294. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22295. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize hardware parameters. snd_pcm_hw_params_any() failed.");
  22296. return ma_result_from_errno(-resultALSA);
  22297. }
  22298. /* MMAP Mode. Try using interleaved MMAP access. If this fails, fall back to standard readi/writei. */
  22299. isUsingMMap = MA_FALSE;
  22300. #if 0 /* NOTE: MMAP mode temporarily disabled. */
  22301. 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. */
  22302. if (!pConfig->alsa.noMMap && ma_device__is_async(pDevice)) {
  22303. 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) {
  22304. pDevice->alsa.isUsingMMap = MA_TRUE;
  22305. }
  22306. }
  22307. }
  22308. #endif
  22309. if (!isUsingMMap) {
  22310. 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);
  22311. if (resultALSA < 0) {
  22312. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22313. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22314. 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.");
  22315. return ma_result_from_errno(-resultALSA);
  22316. }
  22317. }
  22318. /*
  22319. Most important properties first. The documentation for OSS (yes, I know this is ALSA!) recommends format, channels, then sample rate. I can't
  22320. find any documentation for ALSA specifically, so I'm going to copy the recommendation for OSS.
  22321. */
  22322. /* Format. */
  22323. {
  22324. /*
  22325. 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
  22326. 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.
  22327. */
  22328. 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) {
  22329. /* We're either requesting the native format or the specified format is not supported. */
  22330. size_t iFormat;
  22331. formatALSA = MA_SND_PCM_FORMAT_UNKNOWN;
  22332. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); ++iFormat) {
  22333. 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) {
  22334. formatALSA = ma_convert_ma_format_to_alsa_format(g_maFormatPriorities[iFormat]);
  22335. break;
  22336. }
  22337. }
  22338. if (formatALSA == MA_SND_PCM_FORMAT_UNKNOWN) {
  22339. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22340. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22341. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. The device does not support any miniaudio formats.");
  22342. return MA_FORMAT_NOT_SUPPORTED;
  22343. }
  22344. }
  22345. resultALSA = ((ma_snd_pcm_hw_params_set_format_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_format)(pPCM, pHWParams, formatALSA);
  22346. if (resultALSA < 0) {
  22347. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22348. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22349. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Format not supported. snd_pcm_hw_params_set_format() failed.");
  22350. return ma_result_from_errno(-resultALSA);
  22351. }
  22352. internalFormat = ma_format_from_alsa(formatALSA);
  22353. if (internalFormat == ma_format_unknown) {
  22354. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22355. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22356. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] The chosen format is not supported by miniaudio.");
  22357. return MA_FORMAT_NOT_SUPPORTED;
  22358. }
  22359. }
  22360. /* Channels. */
  22361. {
  22362. unsigned int channels = pDescriptor->channels;
  22363. if (channels == 0) {
  22364. channels = MA_DEFAULT_CHANNELS;
  22365. }
  22366. resultALSA = ((ma_snd_pcm_hw_params_set_channels_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_channels_near)(pPCM, pHWParams, &channels);
  22367. if (resultALSA < 0) {
  22368. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22369. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22370. 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.");
  22371. return ma_result_from_errno(-resultALSA);
  22372. }
  22373. internalChannels = (ma_uint32)channels;
  22374. }
  22375. /* Sample Rate */
  22376. {
  22377. unsigned int sampleRate;
  22378. /*
  22379. 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
  22380. problems with some device configurations when used in conjunction with MMAP access mode. To fix this problem we need to disable
  22381. resampling.
  22382. To reproduce this problem, open the "plug:dmix" device, and set the sample rate to 44100. Internally, it looks like dmix uses a
  22383. sample rate of 48000. The hardware parameters will get set correctly with no errors, but it looks like the 44100 -> 48000 resampling
  22384. 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
  22385. faster rate.
  22386. miniaudio has built-in support for sample rate conversion (albeit low quality at the moment), so disabling resampling should be fine
  22387. 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
  22388. good quality until I get a chance to improve the quality of miniaudio's software sample rate conversion.
  22389. 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
  22390. this error with. In the future, we may want to restrict the disabling of resampling to only known bad plugins.
  22391. */
  22392. ((ma_snd_pcm_hw_params_set_rate_resample_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_resample)(pPCM, pHWParams, 0);
  22393. sampleRate = pDescriptor->sampleRate;
  22394. if (sampleRate == 0) {
  22395. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  22396. }
  22397. resultALSA = ((ma_snd_pcm_hw_params_set_rate_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_rate_near)(pPCM, pHWParams, &sampleRate, 0);
  22398. if (resultALSA < 0) {
  22399. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22400. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22401. 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.");
  22402. return ma_result_from_errno(-resultALSA);
  22403. }
  22404. internalSampleRate = (ma_uint32)sampleRate;
  22405. }
  22406. /* Periods. */
  22407. {
  22408. ma_uint32 periods = pDescriptor->periodCount;
  22409. resultALSA = ((ma_snd_pcm_hw_params_set_periods_near_proc)pDevice->pContext->alsa.snd_pcm_hw_params_set_periods_near)(pPCM, pHWParams, &periods, NULL);
  22410. if (resultALSA < 0) {
  22411. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22412. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22413. 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.");
  22414. return ma_result_from_errno(-resultALSA);
  22415. }
  22416. internalPeriods = periods;
  22417. }
  22418. /* Buffer Size */
  22419. {
  22420. ma_snd_pcm_uframes_t actualBufferSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile) * internalPeriods;
  22421. 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);
  22422. if (resultALSA < 0) {
  22423. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22424. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22425. 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.");
  22426. return ma_result_from_errno(-resultALSA);
  22427. }
  22428. internalPeriodSizeInFrames = actualBufferSizeInFrames / internalPeriods;
  22429. }
  22430. /* Apply hardware parameters. */
  22431. resultALSA = ((ma_snd_pcm_hw_params_proc)pDevice->pContext->alsa.snd_pcm_hw_params)(pPCM, pHWParams);
  22432. if (resultALSA < 0) {
  22433. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22434. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22435. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set hardware parameters. snd_pcm_hw_params() failed.");
  22436. return ma_result_from_errno(-resultALSA);
  22437. }
  22438. ma_free(pHWParams, &pDevice->pContext->allocationCallbacks);
  22439. pHWParams = NULL;
  22440. /* Software parameters. */
  22441. 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);
  22442. if (pSWParams == NULL) {
  22443. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22444. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for software parameters.");
  22445. return MA_OUT_OF_MEMORY;
  22446. }
  22447. resultALSA = ((ma_snd_pcm_sw_params_current_proc)pDevice->pContext->alsa.snd_pcm_sw_params_current)(pPCM, pSWParams);
  22448. if (resultALSA < 0) {
  22449. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22450. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22451. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to initialize software parameters. snd_pcm_sw_params_current() failed.");
  22452. return ma_result_from_errno(-resultALSA);
  22453. }
  22454. 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));
  22455. if (resultALSA < 0) {
  22456. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22457. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22458. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_sw_params_set_avail_min() failed.");
  22459. return ma_result_from_errno(-resultALSA);
  22460. }
  22461. resultALSA = ((ma_snd_pcm_sw_params_get_boundary_proc)pDevice->pContext->alsa.snd_pcm_sw_params_get_boundary)(pSWParams, &bufferBoundary);
  22462. if (resultALSA < 0) {
  22463. bufferBoundary = internalPeriodSizeInFrames * internalPeriods;
  22464. }
  22465. if (deviceType == ma_device_type_playback && !isUsingMMap) { /* Only playback devices in writei/readi mode need a start threshold. */
  22466. /*
  22467. Subtle detail here with the start threshold. When in playback-only mode (no full-duplex) we can set the start threshold to
  22468. the size of a period. But for full-duplex we need to set it such that it is at least two periods.
  22469. */
  22470. resultALSA = ((ma_snd_pcm_sw_params_set_start_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_start_threshold)(pPCM, pSWParams, internalPeriodSizeInFrames*2);
  22471. if (resultALSA < 0) {
  22472. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22473. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22474. 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.");
  22475. return ma_result_from_errno(-resultALSA);
  22476. }
  22477. resultALSA = ((ma_snd_pcm_sw_params_set_stop_threshold_proc)pDevice->pContext->alsa.snd_pcm_sw_params_set_stop_threshold)(pPCM, pSWParams, bufferBoundary);
  22478. if (resultALSA < 0) { /* Set to boundary to loop instead of stop in the event of an xrun. */
  22479. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22480. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22481. 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.");
  22482. return ma_result_from_errno(-resultALSA);
  22483. }
  22484. }
  22485. resultALSA = ((ma_snd_pcm_sw_params_proc)pDevice->pContext->alsa.snd_pcm_sw_params)(pPCM, pSWParams);
  22486. if (resultALSA < 0) {
  22487. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22488. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22489. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to set software parameters. snd_pcm_sw_params() failed.");
  22490. return ma_result_from_errno(-resultALSA);
  22491. }
  22492. ma_free(pSWParams, &pDevice->pContext->allocationCallbacks);
  22493. pSWParams = NULL;
  22494. /* 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. */
  22495. {
  22496. ma_snd_pcm_chmap_t* pChmap = NULL;
  22497. if (pDevice->pContext->alsa.snd_pcm_get_chmap != NULL) {
  22498. pChmap = ((ma_snd_pcm_get_chmap_proc)pDevice->pContext->alsa.snd_pcm_get_chmap)(pPCM);
  22499. }
  22500. if (pChmap != NULL) {
  22501. ma_uint32 iChannel;
  22502. /* 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(). */
  22503. if (pChmap->channels >= internalChannels) {
  22504. /* Drop excess channels. */
  22505. for (iChannel = 0; iChannel < internalChannels; ++iChannel) {
  22506. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  22507. }
  22508. } else {
  22509. ma_uint32 i;
  22510. /*
  22511. Excess channels use defaults. Do an initial fill with defaults, overwrite the first pChmap->channels, validate to ensure there are no duplicate
  22512. channels. If validation fails, fall back to defaults.
  22513. */
  22514. ma_bool32 isValid = MA_TRUE;
  22515. /* Fill with defaults. */
  22516. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  22517. /* Overwrite first pChmap->channels channels. */
  22518. for (iChannel = 0; iChannel < pChmap->channels; ++iChannel) {
  22519. internalChannelMap[iChannel] = ma_convert_alsa_channel_position_to_ma_channel(pChmap->pos[iChannel]);
  22520. }
  22521. /* Validate. */
  22522. for (i = 0; i < internalChannels && isValid; ++i) {
  22523. ma_uint32 j;
  22524. for (j = i+1; j < internalChannels; ++j) {
  22525. if (internalChannelMap[i] == internalChannelMap[j]) {
  22526. isValid = MA_FALSE;
  22527. break;
  22528. }
  22529. }
  22530. }
  22531. /* If our channel map is invalid, fall back to defaults. */
  22532. if (!isValid) {
  22533. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  22534. }
  22535. }
  22536. free(pChmap);
  22537. pChmap = NULL;
  22538. } else {
  22539. /* Could not retrieve the channel map. Fall back to a hard-coded assumption. */
  22540. ma_channel_map_init_standard(ma_standard_channel_map_alsa, internalChannelMap, ma_countof(internalChannelMap), internalChannels);
  22541. }
  22542. }
  22543. /*
  22544. We need to retrieve the poll descriptors so we can use poll() to wait for data to become
  22545. available for reading or writing. There's no well defined maximum for this so we're just going
  22546. to allocate this on the heap.
  22547. */
  22548. pollDescriptorCount = ((ma_snd_pcm_poll_descriptors_count_proc)pDevice->pContext->alsa.snd_pcm_poll_descriptors_count)(pPCM);
  22549. if (pollDescriptorCount <= 0) {
  22550. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22551. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors count.");
  22552. return MA_ERROR;
  22553. }
  22554. pPollDescriptors = (struct pollfd*)ma_malloc(sizeof(*pPollDescriptors) * (pollDescriptorCount + 1), &pDevice->pContext->allocationCallbacks); /* +1 because we want room for the wakeup descriptor. */
  22555. if (pPollDescriptors == NULL) {
  22556. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22557. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to allocate memory for poll descriptors.");
  22558. return MA_OUT_OF_MEMORY;
  22559. }
  22560. /*
  22561. We need an eventfd to wakeup from poll() and avoid a deadlock in situations where the driver
  22562. never returns from writei() and readi(). This has been observed with the "pulse" device.
  22563. */
  22564. wakeupfd = eventfd(0, 0);
  22565. if (wakeupfd < 0) {
  22566. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  22567. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22568. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to create eventfd for poll wakeup.");
  22569. return ma_result_from_errno(errno);
  22570. }
  22571. /* We'll place the wakeup fd at the start of the buffer. */
  22572. pPollDescriptors[0].fd = wakeupfd;
  22573. pPollDescriptors[0].events = POLLIN; /* We only care about waiting to read from the wakeup file descriptor. */
  22574. pPollDescriptors[0].revents = 0;
  22575. /* We can now extract the PCM poll descriptors which we place after the wakeup descriptor. */
  22576. 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. */
  22577. if (pollDescriptorCount <= 0) {
  22578. close(wakeupfd);
  22579. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  22580. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22581. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to retrieve poll descriptors.");
  22582. return MA_ERROR;
  22583. }
  22584. if (deviceType == ma_device_type_capture) {
  22585. pDevice->alsa.pollDescriptorCountCapture = pollDescriptorCount;
  22586. pDevice->alsa.pPollDescriptorsCapture = pPollDescriptors;
  22587. pDevice->alsa.wakeupfdCapture = wakeupfd;
  22588. } else {
  22589. pDevice->alsa.pollDescriptorCountPlayback = pollDescriptorCount;
  22590. pDevice->alsa.pPollDescriptorsPlayback = pPollDescriptors;
  22591. pDevice->alsa.wakeupfdPlayback = wakeupfd;
  22592. }
  22593. /* We're done. Prepare the device. */
  22594. resultALSA = ((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)(pPCM);
  22595. if (resultALSA < 0) {
  22596. close(wakeupfd);
  22597. ma_free(pPollDescriptors, &pDevice->pContext->allocationCallbacks);
  22598. ((ma_snd_pcm_close_proc)pDevice->pContext->alsa.snd_pcm_close)(pPCM);
  22599. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to prepare device.");
  22600. return ma_result_from_errno(-resultALSA);
  22601. }
  22602. if (deviceType == ma_device_type_capture) {
  22603. pDevice->alsa.pPCMCapture = (ma_ptr)pPCM;
  22604. pDevice->alsa.isUsingMMapCapture = isUsingMMap;
  22605. } else {
  22606. pDevice->alsa.pPCMPlayback = (ma_ptr)pPCM;
  22607. pDevice->alsa.isUsingMMapPlayback = isUsingMMap;
  22608. }
  22609. pDescriptor->format = internalFormat;
  22610. pDescriptor->channels = internalChannels;
  22611. pDescriptor->sampleRate = internalSampleRate;
  22612. ma_channel_map_copy(pDescriptor->channelMap, internalChannelMap, ma_min(internalChannels, MA_MAX_CHANNELS));
  22613. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  22614. pDescriptor->periodCount = internalPeriods;
  22615. return MA_SUCCESS;
  22616. }
  22617. static ma_result ma_device_init__alsa(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  22618. {
  22619. MA_ASSERT(pDevice != NULL);
  22620. MA_ZERO_OBJECT(&pDevice->alsa);
  22621. if (pConfig->deviceType == ma_device_type_loopback) {
  22622. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  22623. }
  22624. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  22625. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  22626. if (result != MA_SUCCESS) {
  22627. return result;
  22628. }
  22629. }
  22630. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  22631. ma_result result = ma_device_init_by_type__alsa(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  22632. if (result != MA_SUCCESS) {
  22633. return result;
  22634. }
  22635. }
  22636. return MA_SUCCESS;
  22637. }
  22638. static ma_result ma_device_start__alsa(ma_device* pDevice)
  22639. {
  22640. int resultALSA;
  22641. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  22642. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  22643. if (resultALSA < 0) {
  22644. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start capture device.");
  22645. return ma_result_from_errno(-resultALSA);
  22646. }
  22647. }
  22648. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  22649. /* Don't need to do anything for playback because it'll be started automatically when enough data has been written. */
  22650. }
  22651. return MA_SUCCESS;
  22652. }
  22653. static ma_result ma_device_stop__alsa(ma_device* pDevice)
  22654. {
  22655. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  22656. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device...\n");
  22657. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  22658. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping capture device successful.\n");
  22659. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  22660. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device...\n");
  22661. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture) < 0) {
  22662. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device failed.\n");
  22663. } else {
  22664. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing capture device successful.\n");
  22665. }
  22666. }
  22667. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  22668. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device...\n");
  22669. ((ma_snd_pcm_drop_proc)pDevice->pContext->alsa.snd_pcm_drop)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  22670. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Dropping playback device successful.\n");
  22671. /* We need to prepare the device again, otherwise we won't be able to restart the device. */
  22672. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device...\n");
  22673. if (((ma_snd_pcm_prepare_proc)pDevice->pContext->alsa.snd_pcm_prepare)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback) < 0) {
  22674. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device failed.\n");
  22675. } else {
  22676. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Preparing playback device successful.\n");
  22677. }
  22678. }
  22679. return MA_SUCCESS;
  22680. }
  22681. static ma_result ma_device_wait__alsa(ma_device* pDevice, ma_snd_pcm_t* pPCM, struct pollfd* pPollDescriptors, int pollDescriptorCount, short requiredEvent)
  22682. {
  22683. for (;;) {
  22684. unsigned short revents;
  22685. int resultALSA;
  22686. int resultPoll = poll(pPollDescriptors, pollDescriptorCount, -1);
  22687. if (resultPoll < 0) {
  22688. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] poll() failed.");
  22689. return ma_result_from_errno(errno);
  22690. }
  22691. /*
  22692. Before checking the ALSA poll descriptor flag we need to check if the wakeup descriptor
  22693. has had it's POLLIN flag set. If so, we need to actually read the data and then exit
  22694. function. The wakeup descriptor will be the first item in the descriptors buffer.
  22695. */
  22696. if ((pPollDescriptors[0].revents & POLLIN) != 0) {
  22697. ma_uint64 t;
  22698. int resultRead = read(pPollDescriptors[0].fd, &t, sizeof(t)); /* <-- Important that we read here so that the next write() does not block. */
  22699. if (resultRead < 0) {
  22700. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] read() failed.");
  22701. return ma_result_from_errno(errno);
  22702. }
  22703. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] POLLIN set for wakeupfd\n");
  22704. return MA_DEVICE_NOT_STARTED;
  22705. }
  22706. /*
  22707. Getting here means that some data should be able to be read. We need to use ALSA to
  22708. translate the revents flags for us.
  22709. */
  22710. 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. */
  22711. if (resultALSA < 0) {
  22712. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] snd_pcm_poll_descriptors_revents() failed.");
  22713. return ma_result_from_errno(-resultALSA);
  22714. }
  22715. if ((revents & POLLERR) != 0) {
  22716. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] POLLERR detected.");
  22717. return ma_result_from_errno(errno);
  22718. }
  22719. if ((revents & requiredEvent) == requiredEvent) {
  22720. break; /* We're done. Data available for reading or writing. */
  22721. }
  22722. }
  22723. return MA_SUCCESS;
  22724. }
  22725. static ma_result ma_device_wait_read__alsa(ma_device* pDevice)
  22726. {
  22727. 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. */
  22728. }
  22729. static ma_result ma_device_wait_write__alsa(ma_device* pDevice)
  22730. {
  22731. 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. */
  22732. }
  22733. static ma_result ma_device_read__alsa(ma_device* pDevice, void* pFramesOut, ma_uint32 frameCount, ma_uint32* pFramesRead)
  22734. {
  22735. ma_snd_pcm_sframes_t resultALSA = 0;
  22736. MA_ASSERT(pDevice != NULL);
  22737. MA_ASSERT(pFramesOut != NULL);
  22738. if (pFramesRead != NULL) {
  22739. *pFramesRead = 0;
  22740. }
  22741. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  22742. ma_result result;
  22743. /* 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. */
  22744. result = ma_device_wait_read__alsa(pDevice);
  22745. if (result != MA_SUCCESS) {
  22746. return result;
  22747. }
  22748. /* Getting here means we should have data available. */
  22749. resultALSA = ((ma_snd_pcm_readi_proc)pDevice->pContext->alsa.snd_pcm_readi)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, pFramesOut, frameCount);
  22750. if (resultALSA >= 0) {
  22751. break; /* Success. */
  22752. } else {
  22753. if (resultALSA == -EAGAIN) {
  22754. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (read)\n");*/
  22755. continue; /* Try again. */
  22756. } else if (resultALSA == -EPIPE) {
  22757. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (read)\n");
  22758. /* Overrun. Recover and try again. If this fails we need to return an error. */
  22759. resultALSA = ((ma_snd_pcm_recover_proc)pDevice->pContext->alsa.snd_pcm_recover)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture, resultALSA, MA_TRUE);
  22760. if (resultALSA < 0) {
  22761. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after overrun.");
  22762. return ma_result_from_errno((int)-resultALSA);
  22763. }
  22764. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMCapture);
  22765. if (resultALSA < 0) {
  22766. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  22767. return ma_result_from_errno((int)-resultALSA);
  22768. }
  22769. continue; /* Try reading again. */
  22770. }
  22771. }
  22772. }
  22773. if (pFramesRead != NULL) {
  22774. *pFramesRead = resultALSA;
  22775. }
  22776. return MA_SUCCESS;
  22777. }
  22778. static ma_result ma_device_write__alsa(ma_device* pDevice, const void* pFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  22779. {
  22780. ma_snd_pcm_sframes_t resultALSA = 0;
  22781. MA_ASSERT(pDevice != NULL);
  22782. MA_ASSERT(pFrames != NULL);
  22783. if (pFramesWritten != NULL) {
  22784. *pFramesWritten = 0;
  22785. }
  22786. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  22787. ma_result result;
  22788. /* 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. */
  22789. result = ma_device_wait_write__alsa(pDevice);
  22790. if (result != MA_SUCCESS) {
  22791. return result;
  22792. }
  22793. resultALSA = ((ma_snd_pcm_writei_proc)pDevice->pContext->alsa.snd_pcm_writei)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback, pFrames, frameCount);
  22794. if (resultALSA >= 0) {
  22795. break; /* Success. */
  22796. } else {
  22797. if (resultALSA == -EAGAIN) {
  22798. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EGAIN (write)\n");*/
  22799. continue; /* Try again. */
  22800. } else if (resultALSA == -EPIPE) {
  22801. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "EPIPE (write)\n");
  22802. /* Underrun. Recover and try again. If this fails we need to return an error. */
  22803. 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). */
  22804. if (resultALSA < 0) {
  22805. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to recover device after underrun.");
  22806. return ma_result_from_errno((int)-resultALSA);
  22807. }
  22808. /*
  22809. In my testing I have had a situation where writei() does not automatically restart the device even though I've set it
  22810. up as such in the software parameters. What will happen is writei() will block indefinitely even though the number of
  22811. frames is well beyond the auto-start threshold. To work around this I've needed to add an explicit start here. Not sure
  22812. if this is me just being stupid and not recovering the device properly, but this definitely feels like something isn't
  22813. quite right here.
  22814. */
  22815. resultALSA = ((ma_snd_pcm_start_proc)pDevice->pContext->alsa.snd_pcm_start)((ma_snd_pcm_t*)pDevice->alsa.pPCMPlayback);
  22816. if (resultALSA < 0) {
  22817. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] Failed to start device after underrun.");
  22818. return ma_result_from_errno((int)-resultALSA);
  22819. }
  22820. continue; /* Try writing again. */
  22821. }
  22822. }
  22823. }
  22824. if (pFramesWritten != NULL) {
  22825. *pFramesWritten = resultALSA;
  22826. }
  22827. return MA_SUCCESS;
  22828. }
  22829. static ma_result ma_device_data_loop_wakeup__alsa(ma_device* pDevice)
  22830. {
  22831. ma_uint64 t = 1;
  22832. int resultWrite = 0;
  22833. MA_ASSERT(pDevice != NULL);
  22834. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up...\n");
  22835. /* Write to an eventfd to trigger a wakeup from poll() and abort any reading or writing. */
  22836. if (pDevice->alsa.pPollDescriptorsCapture != NULL) {
  22837. resultWrite = write(pDevice->alsa.wakeupfdCapture, &t, sizeof(t));
  22838. }
  22839. if (pDevice->alsa.pPollDescriptorsPlayback != NULL) {
  22840. resultWrite = write(pDevice->alsa.wakeupfdPlayback, &t, sizeof(t));
  22841. }
  22842. if (resultWrite < 0) {
  22843. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[ALSA] write() failed.\n");
  22844. return ma_result_from_errno(errno);
  22845. }
  22846. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[ALSA] Waking up completed successfully.\n");
  22847. return MA_SUCCESS;
  22848. }
  22849. static ma_result ma_context_uninit__alsa(ma_context* pContext)
  22850. {
  22851. MA_ASSERT(pContext != NULL);
  22852. MA_ASSERT(pContext->backend == ma_backend_alsa);
  22853. /* Clean up memory for memory leak checkers. */
  22854. ((ma_snd_config_update_free_global_proc)pContext->alsa.snd_config_update_free_global)();
  22855. #ifndef MA_NO_RUNTIME_LINKING
  22856. ma_dlclose(pContext, pContext->alsa.asoundSO);
  22857. #endif
  22858. ma_mutex_uninit(&pContext->alsa.internalDeviceEnumLock);
  22859. return MA_SUCCESS;
  22860. }
  22861. static ma_result ma_context_init__alsa(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  22862. {
  22863. ma_result result;
  22864. #ifndef MA_NO_RUNTIME_LINKING
  22865. const char* libasoundNames[] = {
  22866. "libasound.so.2",
  22867. "libasound.so"
  22868. };
  22869. size_t i;
  22870. for (i = 0; i < ma_countof(libasoundNames); ++i) {
  22871. pContext->alsa.asoundSO = ma_dlopen(pContext, libasoundNames[i]);
  22872. if (pContext->alsa.asoundSO != NULL) {
  22873. break;
  22874. }
  22875. }
  22876. if (pContext->alsa.asoundSO == NULL) {
  22877. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "[ALSA] Failed to open shared object.\n");
  22878. return MA_NO_BACKEND;
  22879. }
  22880. pContext->alsa.snd_pcm_open = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_open");
  22881. pContext->alsa.snd_pcm_close = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_close");
  22882. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_sizeof");
  22883. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_any");
  22884. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format");
  22885. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_format_first");
  22886. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format_mask");
  22887. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels");
  22888. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_near");
  22889. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_channels_minmax");
  22890. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_resample");
  22891. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate");
  22892. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_rate_near");
  22893. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_buffer_size_near");
  22894. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_periods_near");
  22895. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_set_access");
  22896. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_format");
  22897. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels");
  22898. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_min");
  22899. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_channels_max");
  22900. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate");
  22901. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_min");
  22902. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_rate_max");
  22903. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_buffer_size");
  22904. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_periods");
  22905. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_get_access");
  22906. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_format");
  22907. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_channels");
  22908. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params_test_rate");
  22909. pContext->alsa.snd_pcm_hw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_hw_params");
  22910. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_sizeof");
  22911. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_current");
  22912. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_get_boundary");
  22913. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_avail_min");
  22914. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_start_threshold");
  22915. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params_set_stop_threshold");
  22916. pContext->alsa.snd_pcm_sw_params = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_sw_params");
  22917. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_sizeof");
  22918. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_format_mask_test");
  22919. pContext->alsa.snd_pcm_get_chmap = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_get_chmap");
  22920. pContext->alsa.snd_pcm_state = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_state");
  22921. pContext->alsa.snd_pcm_prepare = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_prepare");
  22922. pContext->alsa.snd_pcm_start = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_start");
  22923. pContext->alsa.snd_pcm_drop = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drop");
  22924. pContext->alsa.snd_pcm_drain = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_drain");
  22925. pContext->alsa.snd_pcm_reset = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_reset");
  22926. pContext->alsa.snd_device_name_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_hint");
  22927. pContext->alsa.snd_device_name_get_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_get_hint");
  22928. pContext->alsa.snd_card_get_index = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_card_get_index");
  22929. pContext->alsa.snd_device_name_free_hint = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_device_name_free_hint");
  22930. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_begin");
  22931. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_mmap_commit");
  22932. pContext->alsa.snd_pcm_recover = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_recover");
  22933. pContext->alsa.snd_pcm_readi = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_readi");
  22934. pContext->alsa.snd_pcm_writei = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_writei");
  22935. pContext->alsa.snd_pcm_avail = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail");
  22936. pContext->alsa.snd_pcm_avail_update = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_avail_update");
  22937. pContext->alsa.snd_pcm_wait = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_wait");
  22938. pContext->alsa.snd_pcm_nonblock = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_nonblock");
  22939. pContext->alsa.snd_pcm_info = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info");
  22940. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_sizeof");
  22941. pContext->alsa.snd_pcm_info_get_name = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_info_get_name");
  22942. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors");
  22943. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_count");
  22944. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_pcm_poll_descriptors_revents");
  22945. pContext->alsa.snd_config_update_free_global = (ma_proc)ma_dlsym(pContext, pContext->alsa.asoundSO, "snd_config_update_free_global");
  22946. #else
  22947. /* The system below is just for type safety. */
  22948. ma_snd_pcm_open_proc _snd_pcm_open = snd_pcm_open;
  22949. ma_snd_pcm_close_proc _snd_pcm_close = snd_pcm_close;
  22950. ma_snd_pcm_hw_params_sizeof_proc _snd_pcm_hw_params_sizeof = snd_pcm_hw_params_sizeof;
  22951. ma_snd_pcm_hw_params_any_proc _snd_pcm_hw_params_any = snd_pcm_hw_params_any;
  22952. ma_snd_pcm_hw_params_set_format_proc _snd_pcm_hw_params_set_format = snd_pcm_hw_params_set_format;
  22953. ma_snd_pcm_hw_params_set_format_first_proc _snd_pcm_hw_params_set_format_first = snd_pcm_hw_params_set_format_first;
  22954. ma_snd_pcm_hw_params_get_format_mask_proc _snd_pcm_hw_params_get_format_mask = snd_pcm_hw_params_get_format_mask;
  22955. ma_snd_pcm_hw_params_set_channels_proc _snd_pcm_hw_params_set_channels = snd_pcm_hw_params_set_channels;
  22956. ma_snd_pcm_hw_params_set_channels_near_proc _snd_pcm_hw_params_set_channels_near = snd_pcm_hw_params_set_channels_near;
  22957. ma_snd_pcm_hw_params_set_rate_resample_proc _snd_pcm_hw_params_set_rate_resample = snd_pcm_hw_params_set_rate_resample;
  22958. ma_snd_pcm_hw_params_set_rate_near _snd_pcm_hw_params_set_rate = snd_pcm_hw_params_set_rate;
  22959. ma_snd_pcm_hw_params_set_rate_near_proc _snd_pcm_hw_params_set_rate_near = snd_pcm_hw_params_set_rate_near;
  22960. ma_snd_pcm_hw_params_set_rate_minmax_proc _snd_pcm_hw_params_set_rate_minmax = snd_pcm_hw_params_set_rate_minmax;
  22961. 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;
  22962. ma_snd_pcm_hw_params_set_periods_near_proc _snd_pcm_hw_params_set_periods_near = snd_pcm_hw_params_set_periods_near;
  22963. ma_snd_pcm_hw_params_set_access_proc _snd_pcm_hw_params_set_access = snd_pcm_hw_params_set_access;
  22964. ma_snd_pcm_hw_params_get_format_proc _snd_pcm_hw_params_get_format = snd_pcm_hw_params_get_format;
  22965. ma_snd_pcm_hw_params_get_channels_proc _snd_pcm_hw_params_get_channels = snd_pcm_hw_params_get_channels;
  22966. ma_snd_pcm_hw_params_get_channels_min_proc _snd_pcm_hw_params_get_channels_min = snd_pcm_hw_params_get_channels_min;
  22967. ma_snd_pcm_hw_params_get_channels_max_proc _snd_pcm_hw_params_get_channels_max = snd_pcm_hw_params_get_channels_max;
  22968. ma_snd_pcm_hw_params_get_rate_proc _snd_pcm_hw_params_get_rate = snd_pcm_hw_params_get_rate;
  22969. ma_snd_pcm_hw_params_get_rate_min_proc _snd_pcm_hw_params_get_rate_min = snd_pcm_hw_params_get_rate_min;
  22970. ma_snd_pcm_hw_params_get_rate_max_proc _snd_pcm_hw_params_get_rate_max = snd_pcm_hw_params_get_rate_max;
  22971. ma_snd_pcm_hw_params_get_buffer_size_proc _snd_pcm_hw_params_get_buffer_size = snd_pcm_hw_params_get_buffer_size;
  22972. ma_snd_pcm_hw_params_get_periods_proc _snd_pcm_hw_params_get_periods = snd_pcm_hw_params_get_periods;
  22973. ma_snd_pcm_hw_params_get_access_proc _snd_pcm_hw_params_get_access = snd_pcm_hw_params_get_access;
  22974. ma_snd_pcm_hw_params_test_format_proc _snd_pcm_hw_params_test_format = snd_pcm_hw_params_test_format;
  22975. ma_snd_pcm_hw_params_test_channels_proc _snd_pcm_hw_params_test_channels = snd_pcm_hw_params_test_channels;
  22976. ma_snd_pcm_hw_params_test_rate_proc _snd_pcm_hw_params_test_rate = snd_pcm_hw_params_test_rate;
  22977. ma_snd_pcm_hw_params_proc _snd_pcm_hw_params = snd_pcm_hw_params;
  22978. ma_snd_pcm_sw_params_sizeof_proc _snd_pcm_sw_params_sizeof = snd_pcm_sw_params_sizeof;
  22979. ma_snd_pcm_sw_params_current_proc _snd_pcm_sw_params_current = snd_pcm_sw_params_current;
  22980. ma_snd_pcm_sw_params_get_boundary_proc _snd_pcm_sw_params_get_boundary = snd_pcm_sw_params_get_boundary;
  22981. ma_snd_pcm_sw_params_set_avail_min_proc _snd_pcm_sw_params_set_avail_min = snd_pcm_sw_params_set_avail_min;
  22982. ma_snd_pcm_sw_params_set_start_threshold_proc _snd_pcm_sw_params_set_start_threshold = snd_pcm_sw_params_set_start_threshold;
  22983. ma_snd_pcm_sw_params_set_stop_threshold_proc _snd_pcm_sw_params_set_stop_threshold = snd_pcm_sw_params_set_stop_threshold;
  22984. ma_snd_pcm_sw_params_proc _snd_pcm_sw_params = snd_pcm_sw_params;
  22985. ma_snd_pcm_format_mask_sizeof_proc _snd_pcm_format_mask_sizeof = snd_pcm_format_mask_sizeof;
  22986. ma_snd_pcm_format_mask_test_proc _snd_pcm_format_mask_test = snd_pcm_format_mask_test;
  22987. ma_snd_pcm_get_chmap_proc _snd_pcm_get_chmap = snd_pcm_get_chmap;
  22988. ma_snd_pcm_state_proc _snd_pcm_state = snd_pcm_state;
  22989. ma_snd_pcm_prepare_proc _snd_pcm_prepare = snd_pcm_prepare;
  22990. ma_snd_pcm_start_proc _snd_pcm_start = snd_pcm_start;
  22991. ma_snd_pcm_drop_proc _snd_pcm_drop = snd_pcm_drop;
  22992. ma_snd_pcm_drain_proc _snd_pcm_drain = snd_pcm_drain;
  22993. ma_snd_pcm_reset_proc _snd_pcm_reset = snd_pcm_reset;
  22994. ma_snd_device_name_hint_proc _snd_device_name_hint = snd_device_name_hint;
  22995. ma_snd_device_name_get_hint_proc _snd_device_name_get_hint = snd_device_name_get_hint;
  22996. ma_snd_card_get_index_proc _snd_card_get_index = snd_card_get_index;
  22997. ma_snd_device_name_free_hint_proc _snd_device_name_free_hint = snd_device_name_free_hint;
  22998. ma_snd_pcm_mmap_begin_proc _snd_pcm_mmap_begin = snd_pcm_mmap_begin;
  22999. ma_snd_pcm_mmap_commit_proc _snd_pcm_mmap_commit = snd_pcm_mmap_commit;
  23000. ma_snd_pcm_recover_proc _snd_pcm_recover = snd_pcm_recover;
  23001. ma_snd_pcm_readi_proc _snd_pcm_readi = snd_pcm_readi;
  23002. ma_snd_pcm_writei_proc _snd_pcm_writei = snd_pcm_writei;
  23003. ma_snd_pcm_avail_proc _snd_pcm_avail = snd_pcm_avail;
  23004. ma_snd_pcm_avail_update_proc _snd_pcm_avail_update = snd_pcm_avail_update;
  23005. ma_snd_pcm_wait_proc _snd_pcm_wait = snd_pcm_wait;
  23006. ma_snd_pcm_nonblock_proc _snd_pcm_nonblock = snd_pcm_nonblock;
  23007. ma_snd_pcm_info_proc _snd_pcm_info = snd_pcm_info;
  23008. ma_snd_pcm_info_sizeof_proc _snd_pcm_info_sizeof = snd_pcm_info_sizeof;
  23009. ma_snd_pcm_info_get_name_proc _snd_pcm_info_get_name = snd_pcm_info_get_name;
  23010. ma_snd_pcm_poll_descriptors _snd_pcm_poll_descriptors = snd_pcm_poll_descriptors;
  23011. ma_snd_pcm_poll_descriptors_count _snd_pcm_poll_descriptors_count = snd_pcm_poll_descriptors_count;
  23012. ma_snd_pcm_poll_descriptors_revents _snd_pcm_poll_descriptors_revents = snd_pcm_poll_descriptors_revents;
  23013. ma_snd_config_update_free_global_proc _snd_config_update_free_global = snd_config_update_free_global;
  23014. pContext->alsa.snd_pcm_open = (ma_proc)_snd_pcm_open;
  23015. pContext->alsa.snd_pcm_close = (ma_proc)_snd_pcm_close;
  23016. pContext->alsa.snd_pcm_hw_params_sizeof = (ma_proc)_snd_pcm_hw_params_sizeof;
  23017. pContext->alsa.snd_pcm_hw_params_any = (ma_proc)_snd_pcm_hw_params_any;
  23018. pContext->alsa.snd_pcm_hw_params_set_format = (ma_proc)_snd_pcm_hw_params_set_format;
  23019. pContext->alsa.snd_pcm_hw_params_set_format_first = (ma_proc)_snd_pcm_hw_params_set_format_first;
  23020. pContext->alsa.snd_pcm_hw_params_get_format_mask = (ma_proc)_snd_pcm_hw_params_get_format_mask;
  23021. pContext->alsa.snd_pcm_hw_params_set_channels = (ma_proc)_snd_pcm_hw_params_set_channels;
  23022. pContext->alsa.snd_pcm_hw_params_set_channels_near = (ma_proc)_snd_pcm_hw_params_set_channels_near;
  23023. pContext->alsa.snd_pcm_hw_params_set_channels_minmax = (ma_proc)_snd_pcm_hw_params_set_channels_minmax;
  23024. pContext->alsa.snd_pcm_hw_params_set_rate_resample = (ma_proc)_snd_pcm_hw_params_set_rate_resample;
  23025. pContext->alsa.snd_pcm_hw_params_set_rate = (ma_proc)_snd_pcm_hw_params_set_rate;
  23026. pContext->alsa.snd_pcm_hw_params_set_rate_near = (ma_proc)_snd_pcm_hw_params_set_rate_near;
  23027. pContext->alsa.snd_pcm_hw_params_set_buffer_size_near = (ma_proc)_snd_pcm_hw_params_set_buffer_size_near;
  23028. pContext->alsa.snd_pcm_hw_params_set_periods_near = (ma_proc)_snd_pcm_hw_params_set_periods_near;
  23029. pContext->alsa.snd_pcm_hw_params_set_access = (ma_proc)_snd_pcm_hw_params_set_access;
  23030. pContext->alsa.snd_pcm_hw_params_get_format = (ma_proc)_snd_pcm_hw_params_get_format;
  23031. pContext->alsa.snd_pcm_hw_params_get_channels = (ma_proc)_snd_pcm_hw_params_get_channels;
  23032. pContext->alsa.snd_pcm_hw_params_get_channels_min = (ma_proc)_snd_pcm_hw_params_get_channels_min;
  23033. pContext->alsa.snd_pcm_hw_params_get_channels_max = (ma_proc)_snd_pcm_hw_params_get_channels_max;
  23034. pContext->alsa.snd_pcm_hw_params_get_rate = (ma_proc)_snd_pcm_hw_params_get_rate;
  23035. pContext->alsa.snd_pcm_hw_params_get_rate_min = (ma_proc)_snd_pcm_hw_params_get_rate_min;
  23036. pContext->alsa.snd_pcm_hw_params_get_rate_max = (ma_proc)_snd_pcm_hw_params_get_rate_max;
  23037. pContext->alsa.snd_pcm_hw_params_get_buffer_size = (ma_proc)_snd_pcm_hw_params_get_buffer_size;
  23038. pContext->alsa.snd_pcm_hw_params_get_periods = (ma_proc)_snd_pcm_hw_params_get_periods;
  23039. pContext->alsa.snd_pcm_hw_params_get_access = (ma_proc)_snd_pcm_hw_params_get_access;
  23040. pContext->alsa.snd_pcm_hw_params_test_format = (ma_proc)_snd_pcm_hw_params_test_format;
  23041. pContext->alsa.snd_pcm_hw_params_test_channels = (ma_proc)_snd_pcm_hw_params_test_channels;
  23042. pContext->alsa.snd_pcm_hw_params_test_rate = (ma_proc)_snd_pcm_hw_params_test_rate;
  23043. pContext->alsa.snd_pcm_hw_params = (ma_proc)_snd_pcm_hw_params;
  23044. pContext->alsa.snd_pcm_sw_params_sizeof = (ma_proc)_snd_pcm_sw_params_sizeof;
  23045. pContext->alsa.snd_pcm_sw_params_current = (ma_proc)_snd_pcm_sw_params_current;
  23046. pContext->alsa.snd_pcm_sw_params_get_boundary = (ma_proc)_snd_pcm_sw_params_get_boundary;
  23047. pContext->alsa.snd_pcm_sw_params_set_avail_min = (ma_proc)_snd_pcm_sw_params_set_avail_min;
  23048. pContext->alsa.snd_pcm_sw_params_set_start_threshold = (ma_proc)_snd_pcm_sw_params_set_start_threshold;
  23049. pContext->alsa.snd_pcm_sw_params_set_stop_threshold = (ma_proc)_snd_pcm_sw_params_set_stop_threshold;
  23050. pContext->alsa.snd_pcm_sw_params = (ma_proc)_snd_pcm_sw_params;
  23051. pContext->alsa.snd_pcm_format_mask_sizeof = (ma_proc)_snd_pcm_format_mask_sizeof;
  23052. pContext->alsa.snd_pcm_format_mask_test = (ma_proc)_snd_pcm_format_mask_test;
  23053. pContext->alsa.snd_pcm_get_chmap = (ma_proc)_snd_pcm_get_chmap;
  23054. pContext->alsa.snd_pcm_state = (ma_proc)_snd_pcm_state;
  23055. pContext->alsa.snd_pcm_prepare = (ma_proc)_snd_pcm_prepare;
  23056. pContext->alsa.snd_pcm_start = (ma_proc)_snd_pcm_start;
  23057. pContext->alsa.snd_pcm_drop = (ma_proc)_snd_pcm_drop;
  23058. pContext->alsa.snd_pcm_drain = (ma_proc)_snd_pcm_drain;
  23059. pContext->alsa.snd_pcm_reset = (ma_proc)_snd_pcm_reset;
  23060. pContext->alsa.snd_device_name_hint = (ma_proc)_snd_device_name_hint;
  23061. pContext->alsa.snd_device_name_get_hint = (ma_proc)_snd_device_name_get_hint;
  23062. pContext->alsa.snd_card_get_index = (ma_proc)_snd_card_get_index;
  23063. pContext->alsa.snd_device_name_free_hint = (ma_proc)_snd_device_name_free_hint;
  23064. pContext->alsa.snd_pcm_mmap_begin = (ma_proc)_snd_pcm_mmap_begin;
  23065. pContext->alsa.snd_pcm_mmap_commit = (ma_proc)_snd_pcm_mmap_commit;
  23066. pContext->alsa.snd_pcm_recover = (ma_proc)_snd_pcm_recover;
  23067. pContext->alsa.snd_pcm_readi = (ma_proc)_snd_pcm_readi;
  23068. pContext->alsa.snd_pcm_writei = (ma_proc)_snd_pcm_writei;
  23069. pContext->alsa.snd_pcm_avail = (ma_proc)_snd_pcm_avail;
  23070. pContext->alsa.snd_pcm_avail_update = (ma_proc)_snd_pcm_avail_update;
  23071. pContext->alsa.snd_pcm_wait = (ma_proc)_snd_pcm_wait;
  23072. pContext->alsa.snd_pcm_nonblock = (ma_proc)_snd_pcm_nonblock;
  23073. pContext->alsa.snd_pcm_info = (ma_proc)_snd_pcm_info;
  23074. pContext->alsa.snd_pcm_info_sizeof = (ma_proc)_snd_pcm_info_sizeof;
  23075. pContext->alsa.snd_pcm_info_get_name = (ma_proc)_snd_pcm_info_get_name;
  23076. pContext->alsa.snd_pcm_poll_descriptors = (ma_proc)_snd_pcm_poll_descriptors;
  23077. pContext->alsa.snd_pcm_poll_descriptors_count = (ma_proc)_snd_pcm_poll_descriptors_count;
  23078. pContext->alsa.snd_pcm_poll_descriptors_revents = (ma_proc)_snd_pcm_poll_descriptors_revents;
  23079. pContext->alsa.snd_config_update_free_global = (ma_proc)_snd_config_update_free_global;
  23080. #endif
  23081. pContext->alsa.useVerboseDeviceEnumeration = pConfig->alsa.useVerboseDeviceEnumeration;
  23082. result = ma_mutex_init(&pContext->alsa.internalDeviceEnumLock);
  23083. if (result != MA_SUCCESS) {
  23084. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[ALSA] WARNING: Failed to initialize mutex for internal device enumeration.");
  23085. return result;
  23086. }
  23087. pCallbacks->onContextInit = ma_context_init__alsa;
  23088. pCallbacks->onContextUninit = ma_context_uninit__alsa;
  23089. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__alsa;
  23090. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__alsa;
  23091. pCallbacks->onDeviceInit = ma_device_init__alsa;
  23092. pCallbacks->onDeviceUninit = ma_device_uninit__alsa;
  23093. pCallbacks->onDeviceStart = ma_device_start__alsa;
  23094. pCallbacks->onDeviceStop = ma_device_stop__alsa;
  23095. pCallbacks->onDeviceRead = ma_device_read__alsa;
  23096. pCallbacks->onDeviceWrite = ma_device_write__alsa;
  23097. pCallbacks->onDeviceDataLoop = NULL;
  23098. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__alsa;
  23099. return MA_SUCCESS;
  23100. }
  23101. #endif /* ALSA */
  23102. /******************************************************************************
  23103. PulseAudio Backend
  23104. ******************************************************************************/
  23105. #ifdef MA_HAS_PULSEAUDIO
  23106. /*
  23107. 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
  23108. in the PulseAudio backend. I apologize if this gets a bit ranty for your liking - you might want to skip this discussion.
  23109. PulseAudio has something they call the "Simple API", which unfortunately isn't suitable for miniaudio. I've not seen anywhere where it
  23110. allows you to enumerate over devices, nor does it seem to support the ability to stop and start streams. Looking at the documentation, it
  23111. appears as though the stream is constantly running and you prevent sound from being emitted or captured by simply not calling the read or
  23112. write functions. This is not a professional solution as it would be much better to *actually* stop the underlying stream. Perhaps the
  23113. 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
  23114. when you want to have multiple streams to a single context. For these reasons, miniaudio is not using the simple API.
  23115. 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
  23116. get fun, and I don't mean that in a good way...
  23117. The problems start with the very name of the API - "asynchronous". Yes, this is an asynchronous oriented API which means your commands
  23118. don't immediately take effect. You instead need to issue your commands, and then wait for them to complete. The waiting mechanism is
  23119. 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
  23120. all of PulseAudio's problems stem from.
  23121. When you first initialize PulseAudio you need an object referred to as "main loop". You can implement this yourself by defining your own
  23122. vtable, but it's much easier to just use one of the built-in main loop implementations. There's two generic implementations called
  23123. pa_mainloop and pa_threaded_mainloop, and another implementation specific to GLib called pa_glib_mainloop. We're using pa_threaded_mainloop
  23124. because it simplifies management of the worker thread. The idea of the main loop object is pretty self explanatory - you're supposed to use
  23125. it to implement a worker thread which runs in a loop. The main loop is where operations are actually executed.
  23126. 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
  23127. to the vtable with `pa_threaded_mainloop_get_api()` (the main loop vtable is called `pa_mainloop_api`). Again, you can bypass the threaded
  23128. main loop object entirely and just implement `pa_mainloop_api` directly, but there's no need for it unless you're doing something extremely
  23129. specialized such as if you want to integrate it into your application's existing main loop infrastructure.
  23130. (EDIT 2021-01-26: miniaudio is no longer using `pa_threaded_mainloop` due to this issue: https://github.com/mackron/miniaudio/issues/262.
  23131. It is now using `pa_mainloop` which turns out to be a simpler solution anyway. The rest of this rant still applies, however.)
  23132. Once you have your main loop vtable (the `pa_mainloop_api` object) you can create the PulseAudio context. This is very similar to
  23133. 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
  23134. 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
  23135. is done with `pa_context_new()`, it's not actually connected to anything. When you connect, you call `pa_context_connect()`. However, if
  23136. you remember, PulseAudio is an asynchronous API. That means you cannot just assume the context is connected after `pa_context_context()`
  23137. 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
  23138. 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.
  23139. 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.
  23140. This waiting loop is therefore unavoidable. In order for the waiting to ever complete, however, the main loop needs to be running. Before
  23141. attempting to connect the context, the main loop needs to be started with `pa_threaded_mainloop_start()`.
  23142. 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
  23143. internet connection. However, the *VAST* majority of cases don't involve this at all - they just connect to a local "server" running on the
  23144. host machine. The fact that this would be the default rather than making `pa_context_connect()` synchronous tends to boggle the mind.
  23145. Once the context has been created and connected you can start creating a stream. A PulseAudio stream is analogous to miniaudio's device.
  23146. The initialization of a stream is fairly standard - you configure some attributes (analogous to miniaudio's device config) and then call
  23147. `pa_stream_new()` to actually create it. Here is where we start to get into "operations". When configuring the stream, you can get
  23148. information about the source (such as sample format, sample rate, etc.), however it's not synchronous. Instead, a `pa_operation` object
  23149. is returned from `pa_context_get_source_info_by_name()` (capture) or `pa_context_get_sink_info_by_name()` (playback). Then, you need to
  23150. 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
  23151. context. Then, as an added bonus, you need to decrement the reference counter of the `pa_operation` object to ensure memory is cleaned up.
  23152. All of that just to retrieve basic information about a device!
  23153. Once the basic information about the device has been retrieved, miniaudio can now create the stream with `ma_stream_new()`. Like the
  23154. 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
  23155. choices in PulseAudio.
  23156. 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
  23157. because PulseAudio takes it literally, specifically the "can be". You would think these callbacks would be appropriate as the place for
  23158. 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
  23159. set a flag that tells PulseAudio to not start the stream automatically. This is required because miniaudio does not auto-start devices
  23160. straight after initialization - you need to call `ma_device_start()` manually. The problem is that even when this flag is specified,
  23161. PulseAudio will immediately fire it's write or read callback. This is *technically* correct (based on the wording in the documentation)
  23162. 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
  23163. 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
  23164. 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
  23165. that point (it may still need to load files or whatnot). Instead, this callback should only be fired when the application requests the
  23166. stream be started which is how it works with literally *every* other callback-based audio API. Since miniaudio forbids firing of the data
  23167. callback until the device has been started (as it should be with *all* callback based APIs), logic needs to be added to ensure miniaudio
  23168. doesn't just blindly fire the application-defined data callback from within the PulseAudio callback before the stream has actually been
  23169. 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
  23170. callback is not fired.
  23171. This, unfortunately, is not the end of the problems with the PulseAudio write callback. Any normal callback based audio API will
  23172. continuously fire the callback at regular intervals based on the size of the internal buffer. This will only ever be fired when the device
  23173. 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
  23174. PulseAudio. In PulseAudio, the data callback will *only* be called if you wrote something to it previously. That means, if you don't call
  23175. `pa_stream_write()`, the callback will not get fired. On the surface you wouldn't think this would matter because you should be always
  23176. 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
  23177. 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
  23178. *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
  23179. important? Because that's how we've defined stopping to work in miniaudio. In miniaudio, stopping the device requires it to be drained
  23180. before returning from ma_device_stop(). So we've stopped the device, which requires us to drain, but draining requires us to *not* write
  23181. 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!
  23182. This becomes a problem when stopping and then restarting the device. When the device is stopped, it's drained, which requires us to *not*
  23183. 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
  23184. resume the stream naively. This means that starting the stream requires us to write data to the stream from outside the callback. This
  23185. disconnect is something PulseAudio has got seriously wrong - there should only ever be a single source of data delivery, that being the
  23186. callback. (I have tried using `pa_stream_flush()` to trigger the write callback to fire, but this just doesn't work for some reason.)
  23187. 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,
  23188. 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
  23189. "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
  23190. 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
  23191. guessed it, asynchronous. This means you'll need our waiting loop as usual. Again, why this asynchronous design is the default is
  23192. absolutely beyond me. Would it really be that hard to just make it run synchronously?
  23193. Teardown is pretty simple (what?!). It's just a matter of calling the relevant `_unref()` function on each object in reverse order that
  23194. they were initialized in.
  23195. 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
  23196. embarrassingly unpractical. The main loop thing is an easy fix - have synchronous versions of all APIs. If an application wants these to
  23197. run asynchronously, they can execute them in a separate thread themselves. The desire to run these asynchronously is such a niche
  23198. requirement - it makes no sense to make it the default. The stream write callback needs to be change, or an alternative provided, that is
  23199. 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
  23200. parameter which the program just writes to directly rather than having to call `pa_stream_writable_size()` and `pa_stream_write()`. These
  23201. changes alone will change PulseAudio from one of the worst audio APIs to one of the best.
  23202. */
  23203. /*
  23204. It is assumed pulseaudio.h is available when linking at compile time. When linking at compile time, we use the declarations in the header
  23205. to check for type safety. We cannot do this when linking at run time because the header might not be available.
  23206. */
  23207. #ifdef MA_NO_RUNTIME_LINKING
  23208. /* pulseaudio.h marks some functions with "inline" which isn't always supported. Need to emulate it. */
  23209. #if !defined(__cplusplus)
  23210. #if defined(__STRICT_ANSI__)
  23211. #if !defined(inline)
  23212. #define inline __inline__ __attribute__((always_inline))
  23213. #define MA_INLINE_DEFINED
  23214. #endif
  23215. #endif
  23216. #endif
  23217. #include <pulse/pulseaudio.h>
  23218. #if defined(MA_INLINE_DEFINED)
  23219. #undef inline
  23220. #undef MA_INLINE_DEFINED
  23221. #endif
  23222. #define MA_PA_OK PA_OK
  23223. #define MA_PA_ERR_ACCESS PA_ERR_ACCESS
  23224. #define MA_PA_ERR_INVALID PA_ERR_INVALID
  23225. #define MA_PA_ERR_NOENTITY PA_ERR_NOENTITY
  23226. #define MA_PA_ERR_NOTSUPPORTED PA_ERR_NOTSUPPORTED
  23227. #define MA_PA_CHANNELS_MAX PA_CHANNELS_MAX
  23228. #define MA_PA_RATE_MAX PA_RATE_MAX
  23229. typedef pa_context_flags_t ma_pa_context_flags_t;
  23230. #define MA_PA_CONTEXT_NOFLAGS PA_CONTEXT_NOFLAGS
  23231. #define MA_PA_CONTEXT_NOAUTOSPAWN PA_CONTEXT_NOAUTOSPAWN
  23232. #define MA_PA_CONTEXT_NOFAIL PA_CONTEXT_NOFAIL
  23233. typedef pa_stream_flags_t ma_pa_stream_flags_t;
  23234. #define MA_PA_STREAM_NOFLAGS PA_STREAM_NOFLAGS
  23235. #define MA_PA_STREAM_START_CORKED PA_STREAM_START_CORKED
  23236. #define MA_PA_STREAM_INTERPOLATE_TIMING PA_STREAM_INTERPOLATE_TIMING
  23237. #define MA_PA_STREAM_NOT_MONOTONIC PA_STREAM_NOT_MONOTONIC
  23238. #define MA_PA_STREAM_AUTO_TIMING_UPDATE PA_STREAM_AUTO_TIMING_UPDATE
  23239. #define MA_PA_STREAM_NO_REMAP_CHANNELS PA_STREAM_NO_REMAP_CHANNELS
  23240. #define MA_PA_STREAM_NO_REMIX_CHANNELS PA_STREAM_NO_REMIX_CHANNELS
  23241. #define MA_PA_STREAM_FIX_FORMAT PA_STREAM_FIX_FORMAT
  23242. #define MA_PA_STREAM_FIX_RATE PA_STREAM_FIX_RATE
  23243. #define MA_PA_STREAM_FIX_CHANNELS PA_STREAM_FIX_CHANNELS
  23244. #define MA_PA_STREAM_DONT_MOVE PA_STREAM_DONT_MOVE
  23245. #define MA_PA_STREAM_VARIABLE_RATE PA_STREAM_VARIABLE_RATE
  23246. #define MA_PA_STREAM_PEAK_DETECT PA_STREAM_PEAK_DETECT
  23247. #define MA_PA_STREAM_START_MUTED PA_STREAM_START_MUTED
  23248. #define MA_PA_STREAM_ADJUST_LATENCY PA_STREAM_ADJUST_LATENCY
  23249. #define MA_PA_STREAM_EARLY_REQUESTS PA_STREAM_EARLY_REQUESTS
  23250. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND
  23251. #define MA_PA_STREAM_START_UNMUTED PA_STREAM_START_UNMUTED
  23252. #define MA_PA_STREAM_FAIL_ON_SUSPEND PA_STREAM_FAIL_ON_SUSPEND
  23253. #define MA_PA_STREAM_RELATIVE_VOLUME PA_STREAM_RELATIVE_VOLUME
  23254. #define MA_PA_STREAM_PASSTHROUGH PA_STREAM_PASSTHROUGH
  23255. typedef pa_sink_flags_t ma_pa_sink_flags_t;
  23256. #define MA_PA_SINK_NOFLAGS PA_SINK_NOFLAGS
  23257. #define MA_PA_SINK_HW_VOLUME_CTRL PA_SINK_HW_VOLUME_CTRL
  23258. #define MA_PA_SINK_LATENCY PA_SINK_LATENCY
  23259. #define MA_PA_SINK_HARDWARE PA_SINK_HARDWARE
  23260. #define MA_PA_SINK_NETWORK PA_SINK_NETWORK
  23261. #define MA_PA_SINK_HW_MUTE_CTRL PA_SINK_HW_MUTE_CTRL
  23262. #define MA_PA_SINK_DECIBEL_VOLUME PA_SINK_DECIBEL_VOLUME
  23263. #define MA_PA_SINK_FLAT_VOLUME PA_SINK_FLAT_VOLUME
  23264. #define MA_PA_SINK_DYNAMIC_LATENCY PA_SINK_DYNAMIC_LATENCY
  23265. #define MA_PA_SINK_SET_FORMATS PA_SINK_SET_FORMATS
  23266. typedef pa_source_flags_t ma_pa_source_flags_t;
  23267. #define MA_PA_SOURCE_NOFLAGS PA_SOURCE_NOFLAGS
  23268. #define MA_PA_SOURCE_HW_VOLUME_CTRL PA_SOURCE_HW_VOLUME_CTRL
  23269. #define MA_PA_SOURCE_LATENCY PA_SOURCE_LATENCY
  23270. #define MA_PA_SOURCE_HARDWARE PA_SOURCE_HARDWARE
  23271. #define MA_PA_SOURCE_NETWORK PA_SOURCE_NETWORK
  23272. #define MA_PA_SOURCE_HW_MUTE_CTRL PA_SOURCE_HW_MUTE_CTRL
  23273. #define MA_PA_SOURCE_DECIBEL_VOLUME PA_SOURCE_DECIBEL_VOLUME
  23274. #define MA_PA_SOURCE_DYNAMIC_LATENCY PA_SOURCE_DYNAMIC_LATENCY
  23275. #define MA_PA_SOURCE_FLAT_VOLUME PA_SOURCE_FLAT_VOLUME
  23276. typedef pa_context_state_t ma_pa_context_state_t;
  23277. #define MA_PA_CONTEXT_UNCONNECTED PA_CONTEXT_UNCONNECTED
  23278. #define MA_PA_CONTEXT_CONNECTING PA_CONTEXT_CONNECTING
  23279. #define MA_PA_CONTEXT_AUTHORIZING PA_CONTEXT_AUTHORIZING
  23280. #define MA_PA_CONTEXT_SETTING_NAME PA_CONTEXT_SETTING_NAME
  23281. #define MA_PA_CONTEXT_READY PA_CONTEXT_READY
  23282. #define MA_PA_CONTEXT_FAILED PA_CONTEXT_FAILED
  23283. #define MA_PA_CONTEXT_TERMINATED PA_CONTEXT_TERMINATED
  23284. typedef pa_stream_state_t ma_pa_stream_state_t;
  23285. #define MA_PA_STREAM_UNCONNECTED PA_STREAM_UNCONNECTED
  23286. #define MA_PA_STREAM_CREATING PA_STREAM_CREATING
  23287. #define MA_PA_STREAM_READY PA_STREAM_READY
  23288. #define MA_PA_STREAM_FAILED PA_STREAM_FAILED
  23289. #define MA_PA_STREAM_TERMINATED PA_STREAM_TERMINATED
  23290. typedef pa_operation_state_t ma_pa_operation_state_t;
  23291. #define MA_PA_OPERATION_RUNNING PA_OPERATION_RUNNING
  23292. #define MA_PA_OPERATION_DONE PA_OPERATION_DONE
  23293. #define MA_PA_OPERATION_CANCELLED PA_OPERATION_CANCELLED
  23294. typedef pa_sink_state_t ma_pa_sink_state_t;
  23295. #define MA_PA_SINK_INVALID_STATE PA_SINK_INVALID_STATE
  23296. #define MA_PA_SINK_RUNNING PA_SINK_RUNNING
  23297. #define MA_PA_SINK_IDLE PA_SINK_IDLE
  23298. #define MA_PA_SINK_SUSPENDED PA_SINK_SUSPENDED
  23299. typedef pa_source_state_t ma_pa_source_state_t;
  23300. #define MA_PA_SOURCE_INVALID_STATE PA_SOURCE_INVALID_STATE
  23301. #define MA_PA_SOURCE_RUNNING PA_SOURCE_RUNNING
  23302. #define MA_PA_SOURCE_IDLE PA_SOURCE_IDLE
  23303. #define MA_PA_SOURCE_SUSPENDED PA_SOURCE_SUSPENDED
  23304. typedef pa_seek_mode_t ma_pa_seek_mode_t;
  23305. #define MA_PA_SEEK_RELATIVE PA_SEEK_RELATIVE
  23306. #define MA_PA_SEEK_ABSOLUTE PA_SEEK_ABSOLUTE
  23307. #define MA_PA_SEEK_RELATIVE_ON_READ PA_SEEK_RELATIVE_ON_READ
  23308. #define MA_PA_SEEK_RELATIVE_END PA_SEEK_RELATIVE_END
  23309. typedef pa_channel_position_t ma_pa_channel_position_t;
  23310. #define MA_PA_CHANNEL_POSITION_INVALID PA_CHANNEL_POSITION_INVALID
  23311. #define MA_PA_CHANNEL_POSITION_MONO PA_CHANNEL_POSITION_MONO
  23312. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT PA_CHANNEL_POSITION_FRONT_LEFT
  23313. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT PA_CHANNEL_POSITION_FRONT_RIGHT
  23314. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER PA_CHANNEL_POSITION_FRONT_CENTER
  23315. #define MA_PA_CHANNEL_POSITION_REAR_CENTER PA_CHANNEL_POSITION_REAR_CENTER
  23316. #define MA_PA_CHANNEL_POSITION_REAR_LEFT PA_CHANNEL_POSITION_REAR_LEFT
  23317. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT PA_CHANNEL_POSITION_REAR_RIGHT
  23318. #define MA_PA_CHANNEL_POSITION_LFE PA_CHANNEL_POSITION_LFE
  23319. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER
  23320. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER
  23321. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT PA_CHANNEL_POSITION_SIDE_LEFT
  23322. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT PA_CHANNEL_POSITION_SIDE_RIGHT
  23323. #define MA_PA_CHANNEL_POSITION_AUX0 PA_CHANNEL_POSITION_AUX0
  23324. #define MA_PA_CHANNEL_POSITION_AUX1 PA_CHANNEL_POSITION_AUX1
  23325. #define MA_PA_CHANNEL_POSITION_AUX2 PA_CHANNEL_POSITION_AUX2
  23326. #define MA_PA_CHANNEL_POSITION_AUX3 PA_CHANNEL_POSITION_AUX3
  23327. #define MA_PA_CHANNEL_POSITION_AUX4 PA_CHANNEL_POSITION_AUX4
  23328. #define MA_PA_CHANNEL_POSITION_AUX5 PA_CHANNEL_POSITION_AUX5
  23329. #define MA_PA_CHANNEL_POSITION_AUX6 PA_CHANNEL_POSITION_AUX6
  23330. #define MA_PA_CHANNEL_POSITION_AUX7 PA_CHANNEL_POSITION_AUX7
  23331. #define MA_PA_CHANNEL_POSITION_AUX8 PA_CHANNEL_POSITION_AUX8
  23332. #define MA_PA_CHANNEL_POSITION_AUX9 PA_CHANNEL_POSITION_AUX9
  23333. #define MA_PA_CHANNEL_POSITION_AUX10 PA_CHANNEL_POSITION_AUX10
  23334. #define MA_PA_CHANNEL_POSITION_AUX11 PA_CHANNEL_POSITION_AUX11
  23335. #define MA_PA_CHANNEL_POSITION_AUX12 PA_CHANNEL_POSITION_AUX12
  23336. #define MA_PA_CHANNEL_POSITION_AUX13 PA_CHANNEL_POSITION_AUX13
  23337. #define MA_PA_CHANNEL_POSITION_AUX14 PA_CHANNEL_POSITION_AUX14
  23338. #define MA_PA_CHANNEL_POSITION_AUX15 PA_CHANNEL_POSITION_AUX15
  23339. #define MA_PA_CHANNEL_POSITION_AUX16 PA_CHANNEL_POSITION_AUX16
  23340. #define MA_PA_CHANNEL_POSITION_AUX17 PA_CHANNEL_POSITION_AUX17
  23341. #define MA_PA_CHANNEL_POSITION_AUX18 PA_CHANNEL_POSITION_AUX18
  23342. #define MA_PA_CHANNEL_POSITION_AUX19 PA_CHANNEL_POSITION_AUX19
  23343. #define MA_PA_CHANNEL_POSITION_AUX20 PA_CHANNEL_POSITION_AUX20
  23344. #define MA_PA_CHANNEL_POSITION_AUX21 PA_CHANNEL_POSITION_AUX21
  23345. #define MA_PA_CHANNEL_POSITION_AUX22 PA_CHANNEL_POSITION_AUX22
  23346. #define MA_PA_CHANNEL_POSITION_AUX23 PA_CHANNEL_POSITION_AUX23
  23347. #define MA_PA_CHANNEL_POSITION_AUX24 PA_CHANNEL_POSITION_AUX24
  23348. #define MA_PA_CHANNEL_POSITION_AUX25 PA_CHANNEL_POSITION_AUX25
  23349. #define MA_PA_CHANNEL_POSITION_AUX26 PA_CHANNEL_POSITION_AUX26
  23350. #define MA_PA_CHANNEL_POSITION_AUX27 PA_CHANNEL_POSITION_AUX27
  23351. #define MA_PA_CHANNEL_POSITION_AUX28 PA_CHANNEL_POSITION_AUX28
  23352. #define MA_PA_CHANNEL_POSITION_AUX29 PA_CHANNEL_POSITION_AUX29
  23353. #define MA_PA_CHANNEL_POSITION_AUX30 PA_CHANNEL_POSITION_AUX30
  23354. #define MA_PA_CHANNEL_POSITION_AUX31 PA_CHANNEL_POSITION_AUX31
  23355. #define MA_PA_CHANNEL_POSITION_TOP_CENTER PA_CHANNEL_POSITION_TOP_CENTER
  23356. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT PA_CHANNEL_POSITION_TOP_FRONT_LEFT
  23357. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT PA_CHANNEL_POSITION_TOP_FRONT_RIGHT
  23358. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER PA_CHANNEL_POSITION_TOP_FRONT_CENTER
  23359. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT PA_CHANNEL_POSITION_TOP_REAR_LEFT
  23360. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT PA_CHANNEL_POSITION_TOP_REAR_RIGHT
  23361. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER PA_CHANNEL_POSITION_TOP_REAR_CENTER
  23362. #define MA_PA_CHANNEL_POSITION_LEFT PA_CHANNEL_POSITION_LEFT
  23363. #define MA_PA_CHANNEL_POSITION_RIGHT PA_CHANNEL_POSITION_RIGHT
  23364. #define MA_PA_CHANNEL_POSITION_CENTER PA_CHANNEL_POSITION_CENTER
  23365. #define MA_PA_CHANNEL_POSITION_SUBWOOFER PA_CHANNEL_POSITION_SUBWOOFER
  23366. typedef pa_channel_map_def_t ma_pa_channel_map_def_t;
  23367. #define MA_PA_CHANNEL_MAP_AIFF PA_CHANNEL_MAP_AIFF
  23368. #define MA_PA_CHANNEL_MAP_ALSA PA_CHANNEL_MAP_ALSA
  23369. #define MA_PA_CHANNEL_MAP_AUX PA_CHANNEL_MAP_AUX
  23370. #define MA_PA_CHANNEL_MAP_WAVEEX PA_CHANNEL_MAP_WAVEEX
  23371. #define MA_PA_CHANNEL_MAP_OSS PA_CHANNEL_MAP_OSS
  23372. #define MA_PA_CHANNEL_MAP_DEFAULT PA_CHANNEL_MAP_DEFAULT
  23373. typedef pa_sample_format_t ma_pa_sample_format_t;
  23374. #define MA_PA_SAMPLE_INVALID PA_SAMPLE_INVALID
  23375. #define MA_PA_SAMPLE_U8 PA_SAMPLE_U8
  23376. #define MA_PA_SAMPLE_ALAW PA_SAMPLE_ALAW
  23377. #define MA_PA_SAMPLE_ULAW PA_SAMPLE_ULAW
  23378. #define MA_PA_SAMPLE_S16LE PA_SAMPLE_S16LE
  23379. #define MA_PA_SAMPLE_S16BE PA_SAMPLE_S16BE
  23380. #define MA_PA_SAMPLE_FLOAT32LE PA_SAMPLE_FLOAT32LE
  23381. #define MA_PA_SAMPLE_FLOAT32BE PA_SAMPLE_FLOAT32BE
  23382. #define MA_PA_SAMPLE_S32LE PA_SAMPLE_S32LE
  23383. #define MA_PA_SAMPLE_S32BE PA_SAMPLE_S32BE
  23384. #define MA_PA_SAMPLE_S24LE PA_SAMPLE_S24LE
  23385. #define MA_PA_SAMPLE_S24BE PA_SAMPLE_S24BE
  23386. #define MA_PA_SAMPLE_S24_32LE PA_SAMPLE_S24_32LE
  23387. #define MA_PA_SAMPLE_S24_32BE PA_SAMPLE_S24_32BE
  23388. typedef pa_mainloop ma_pa_mainloop;
  23389. typedef pa_threaded_mainloop ma_pa_threaded_mainloop;
  23390. typedef pa_mainloop_api ma_pa_mainloop_api;
  23391. typedef pa_context ma_pa_context;
  23392. typedef pa_operation ma_pa_operation;
  23393. typedef pa_stream ma_pa_stream;
  23394. typedef pa_spawn_api ma_pa_spawn_api;
  23395. typedef pa_buffer_attr ma_pa_buffer_attr;
  23396. typedef pa_channel_map ma_pa_channel_map;
  23397. typedef pa_cvolume ma_pa_cvolume;
  23398. typedef pa_sample_spec ma_pa_sample_spec;
  23399. typedef pa_sink_info ma_pa_sink_info;
  23400. typedef pa_source_info ma_pa_source_info;
  23401. typedef pa_context_notify_cb_t ma_pa_context_notify_cb_t;
  23402. typedef pa_sink_info_cb_t ma_pa_sink_info_cb_t;
  23403. typedef pa_source_info_cb_t ma_pa_source_info_cb_t;
  23404. typedef pa_stream_success_cb_t ma_pa_stream_success_cb_t;
  23405. typedef pa_stream_request_cb_t ma_pa_stream_request_cb_t;
  23406. typedef pa_stream_notify_cb_t ma_pa_stream_notify_cb_t;
  23407. typedef pa_free_cb_t ma_pa_free_cb_t;
  23408. #else
  23409. #define MA_PA_OK 0
  23410. #define MA_PA_ERR_ACCESS 1
  23411. #define MA_PA_ERR_INVALID 2
  23412. #define MA_PA_ERR_NOENTITY 5
  23413. #define MA_PA_ERR_NOTSUPPORTED 19
  23414. #define MA_PA_CHANNELS_MAX 32
  23415. #define MA_PA_RATE_MAX 384000
  23416. typedef int ma_pa_context_flags_t;
  23417. #define MA_PA_CONTEXT_NOFLAGS 0x00000000
  23418. #define MA_PA_CONTEXT_NOAUTOSPAWN 0x00000001
  23419. #define MA_PA_CONTEXT_NOFAIL 0x00000002
  23420. typedef int ma_pa_stream_flags_t;
  23421. #define MA_PA_STREAM_NOFLAGS 0x00000000
  23422. #define MA_PA_STREAM_START_CORKED 0x00000001
  23423. #define MA_PA_STREAM_INTERPOLATE_TIMING 0x00000002
  23424. #define MA_PA_STREAM_NOT_MONOTONIC 0x00000004
  23425. #define MA_PA_STREAM_AUTO_TIMING_UPDATE 0x00000008
  23426. #define MA_PA_STREAM_NO_REMAP_CHANNELS 0x00000010
  23427. #define MA_PA_STREAM_NO_REMIX_CHANNELS 0x00000020
  23428. #define MA_PA_STREAM_FIX_FORMAT 0x00000040
  23429. #define MA_PA_STREAM_FIX_RATE 0x00000080
  23430. #define MA_PA_STREAM_FIX_CHANNELS 0x00000100
  23431. #define MA_PA_STREAM_DONT_MOVE 0x00000200
  23432. #define MA_PA_STREAM_VARIABLE_RATE 0x00000400
  23433. #define MA_PA_STREAM_PEAK_DETECT 0x00000800
  23434. #define MA_PA_STREAM_START_MUTED 0x00001000
  23435. #define MA_PA_STREAM_ADJUST_LATENCY 0x00002000
  23436. #define MA_PA_STREAM_EARLY_REQUESTS 0x00004000
  23437. #define MA_PA_STREAM_DONT_INHIBIT_AUTO_SUSPEND 0x00008000
  23438. #define MA_PA_STREAM_START_UNMUTED 0x00010000
  23439. #define MA_PA_STREAM_FAIL_ON_SUSPEND 0x00020000
  23440. #define MA_PA_STREAM_RELATIVE_VOLUME 0x00040000
  23441. #define MA_PA_STREAM_PASSTHROUGH 0x00080000
  23442. typedef int ma_pa_sink_flags_t;
  23443. #define MA_PA_SINK_NOFLAGS 0x00000000
  23444. #define MA_PA_SINK_HW_VOLUME_CTRL 0x00000001
  23445. #define MA_PA_SINK_LATENCY 0x00000002
  23446. #define MA_PA_SINK_HARDWARE 0x00000004
  23447. #define MA_PA_SINK_NETWORK 0x00000008
  23448. #define MA_PA_SINK_HW_MUTE_CTRL 0x00000010
  23449. #define MA_PA_SINK_DECIBEL_VOLUME 0x00000020
  23450. #define MA_PA_SINK_FLAT_VOLUME 0x00000040
  23451. #define MA_PA_SINK_DYNAMIC_LATENCY 0x00000080
  23452. #define MA_PA_SINK_SET_FORMATS 0x00000100
  23453. typedef int ma_pa_source_flags_t;
  23454. #define MA_PA_SOURCE_NOFLAGS 0x00000000
  23455. #define MA_PA_SOURCE_HW_VOLUME_CTRL 0x00000001
  23456. #define MA_PA_SOURCE_LATENCY 0x00000002
  23457. #define MA_PA_SOURCE_HARDWARE 0x00000004
  23458. #define MA_PA_SOURCE_NETWORK 0x00000008
  23459. #define MA_PA_SOURCE_HW_MUTE_CTRL 0x00000010
  23460. #define MA_PA_SOURCE_DECIBEL_VOLUME 0x00000020
  23461. #define MA_PA_SOURCE_DYNAMIC_LATENCY 0x00000040
  23462. #define MA_PA_SOURCE_FLAT_VOLUME 0x00000080
  23463. typedef int ma_pa_context_state_t;
  23464. #define MA_PA_CONTEXT_UNCONNECTED 0
  23465. #define MA_PA_CONTEXT_CONNECTING 1
  23466. #define MA_PA_CONTEXT_AUTHORIZING 2
  23467. #define MA_PA_CONTEXT_SETTING_NAME 3
  23468. #define MA_PA_CONTEXT_READY 4
  23469. #define MA_PA_CONTEXT_FAILED 5
  23470. #define MA_PA_CONTEXT_TERMINATED 6
  23471. typedef int ma_pa_stream_state_t;
  23472. #define MA_PA_STREAM_UNCONNECTED 0
  23473. #define MA_PA_STREAM_CREATING 1
  23474. #define MA_PA_STREAM_READY 2
  23475. #define MA_PA_STREAM_FAILED 3
  23476. #define MA_PA_STREAM_TERMINATED 4
  23477. typedef int ma_pa_operation_state_t;
  23478. #define MA_PA_OPERATION_RUNNING 0
  23479. #define MA_PA_OPERATION_DONE 1
  23480. #define MA_PA_OPERATION_CANCELLED 2
  23481. typedef int ma_pa_sink_state_t;
  23482. #define MA_PA_SINK_INVALID_STATE -1
  23483. #define MA_PA_SINK_RUNNING 0
  23484. #define MA_PA_SINK_IDLE 1
  23485. #define MA_PA_SINK_SUSPENDED 2
  23486. typedef int ma_pa_source_state_t;
  23487. #define MA_PA_SOURCE_INVALID_STATE -1
  23488. #define MA_PA_SOURCE_RUNNING 0
  23489. #define MA_PA_SOURCE_IDLE 1
  23490. #define MA_PA_SOURCE_SUSPENDED 2
  23491. typedef int ma_pa_seek_mode_t;
  23492. #define MA_PA_SEEK_RELATIVE 0
  23493. #define MA_PA_SEEK_ABSOLUTE 1
  23494. #define MA_PA_SEEK_RELATIVE_ON_READ 2
  23495. #define MA_PA_SEEK_RELATIVE_END 3
  23496. typedef int ma_pa_channel_position_t;
  23497. #define MA_PA_CHANNEL_POSITION_INVALID -1
  23498. #define MA_PA_CHANNEL_POSITION_MONO 0
  23499. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT 1
  23500. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT 2
  23501. #define MA_PA_CHANNEL_POSITION_FRONT_CENTER 3
  23502. #define MA_PA_CHANNEL_POSITION_REAR_CENTER 4
  23503. #define MA_PA_CHANNEL_POSITION_REAR_LEFT 5
  23504. #define MA_PA_CHANNEL_POSITION_REAR_RIGHT 6
  23505. #define MA_PA_CHANNEL_POSITION_LFE 7
  23506. #define MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER 8
  23507. #define MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER 9
  23508. #define MA_PA_CHANNEL_POSITION_SIDE_LEFT 10
  23509. #define MA_PA_CHANNEL_POSITION_SIDE_RIGHT 11
  23510. #define MA_PA_CHANNEL_POSITION_AUX0 12
  23511. #define MA_PA_CHANNEL_POSITION_AUX1 13
  23512. #define MA_PA_CHANNEL_POSITION_AUX2 14
  23513. #define MA_PA_CHANNEL_POSITION_AUX3 15
  23514. #define MA_PA_CHANNEL_POSITION_AUX4 16
  23515. #define MA_PA_CHANNEL_POSITION_AUX5 17
  23516. #define MA_PA_CHANNEL_POSITION_AUX6 18
  23517. #define MA_PA_CHANNEL_POSITION_AUX7 19
  23518. #define MA_PA_CHANNEL_POSITION_AUX8 20
  23519. #define MA_PA_CHANNEL_POSITION_AUX9 21
  23520. #define MA_PA_CHANNEL_POSITION_AUX10 22
  23521. #define MA_PA_CHANNEL_POSITION_AUX11 23
  23522. #define MA_PA_CHANNEL_POSITION_AUX12 24
  23523. #define MA_PA_CHANNEL_POSITION_AUX13 25
  23524. #define MA_PA_CHANNEL_POSITION_AUX14 26
  23525. #define MA_PA_CHANNEL_POSITION_AUX15 27
  23526. #define MA_PA_CHANNEL_POSITION_AUX16 28
  23527. #define MA_PA_CHANNEL_POSITION_AUX17 29
  23528. #define MA_PA_CHANNEL_POSITION_AUX18 30
  23529. #define MA_PA_CHANNEL_POSITION_AUX19 31
  23530. #define MA_PA_CHANNEL_POSITION_AUX20 32
  23531. #define MA_PA_CHANNEL_POSITION_AUX21 33
  23532. #define MA_PA_CHANNEL_POSITION_AUX22 34
  23533. #define MA_PA_CHANNEL_POSITION_AUX23 35
  23534. #define MA_PA_CHANNEL_POSITION_AUX24 36
  23535. #define MA_PA_CHANNEL_POSITION_AUX25 37
  23536. #define MA_PA_CHANNEL_POSITION_AUX26 38
  23537. #define MA_PA_CHANNEL_POSITION_AUX27 39
  23538. #define MA_PA_CHANNEL_POSITION_AUX28 40
  23539. #define MA_PA_CHANNEL_POSITION_AUX29 41
  23540. #define MA_PA_CHANNEL_POSITION_AUX30 42
  23541. #define MA_PA_CHANNEL_POSITION_AUX31 43
  23542. #define MA_PA_CHANNEL_POSITION_TOP_CENTER 44
  23543. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT 45
  23544. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT 46
  23545. #define MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER 47
  23546. #define MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT 48
  23547. #define MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT 49
  23548. #define MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER 50
  23549. #define MA_PA_CHANNEL_POSITION_LEFT MA_PA_CHANNEL_POSITION_FRONT_LEFT
  23550. #define MA_PA_CHANNEL_POSITION_RIGHT MA_PA_CHANNEL_POSITION_FRONT_RIGHT
  23551. #define MA_PA_CHANNEL_POSITION_CENTER MA_PA_CHANNEL_POSITION_FRONT_CENTER
  23552. #define MA_PA_CHANNEL_POSITION_SUBWOOFER MA_PA_CHANNEL_POSITION_LFE
  23553. typedef int ma_pa_channel_map_def_t;
  23554. #define MA_PA_CHANNEL_MAP_AIFF 0
  23555. #define MA_PA_CHANNEL_MAP_ALSA 1
  23556. #define MA_PA_CHANNEL_MAP_AUX 2
  23557. #define MA_PA_CHANNEL_MAP_WAVEEX 3
  23558. #define MA_PA_CHANNEL_MAP_OSS 4
  23559. #define MA_PA_CHANNEL_MAP_DEFAULT MA_PA_CHANNEL_MAP_AIFF
  23560. typedef int ma_pa_sample_format_t;
  23561. #define MA_PA_SAMPLE_INVALID -1
  23562. #define MA_PA_SAMPLE_U8 0
  23563. #define MA_PA_SAMPLE_ALAW 1
  23564. #define MA_PA_SAMPLE_ULAW 2
  23565. #define MA_PA_SAMPLE_S16LE 3
  23566. #define MA_PA_SAMPLE_S16BE 4
  23567. #define MA_PA_SAMPLE_FLOAT32LE 5
  23568. #define MA_PA_SAMPLE_FLOAT32BE 6
  23569. #define MA_PA_SAMPLE_S32LE 7
  23570. #define MA_PA_SAMPLE_S32BE 8
  23571. #define MA_PA_SAMPLE_S24LE 9
  23572. #define MA_PA_SAMPLE_S24BE 10
  23573. #define MA_PA_SAMPLE_S24_32LE 11
  23574. #define MA_PA_SAMPLE_S24_32BE 12
  23575. typedef struct ma_pa_mainloop ma_pa_mainloop;
  23576. typedef struct ma_pa_threaded_mainloop ma_pa_threaded_mainloop;
  23577. typedef struct ma_pa_mainloop_api ma_pa_mainloop_api;
  23578. typedef struct ma_pa_context ma_pa_context;
  23579. typedef struct ma_pa_operation ma_pa_operation;
  23580. typedef struct ma_pa_stream ma_pa_stream;
  23581. typedef struct ma_pa_spawn_api ma_pa_spawn_api;
  23582. typedef struct
  23583. {
  23584. ma_uint32 maxlength;
  23585. ma_uint32 tlength;
  23586. ma_uint32 prebuf;
  23587. ma_uint32 minreq;
  23588. ma_uint32 fragsize;
  23589. } ma_pa_buffer_attr;
  23590. typedef struct
  23591. {
  23592. ma_uint8 channels;
  23593. ma_pa_channel_position_t map[MA_PA_CHANNELS_MAX];
  23594. } ma_pa_channel_map;
  23595. typedef struct
  23596. {
  23597. ma_uint8 channels;
  23598. ma_uint32 values[MA_PA_CHANNELS_MAX];
  23599. } ma_pa_cvolume;
  23600. typedef struct
  23601. {
  23602. ma_pa_sample_format_t format;
  23603. ma_uint32 rate;
  23604. ma_uint8 channels;
  23605. } ma_pa_sample_spec;
  23606. typedef struct
  23607. {
  23608. const char* name;
  23609. ma_uint32 index;
  23610. const char* description;
  23611. ma_pa_sample_spec sample_spec;
  23612. ma_pa_channel_map channel_map;
  23613. ma_uint32 owner_module;
  23614. ma_pa_cvolume volume;
  23615. int mute;
  23616. ma_uint32 monitor_source;
  23617. const char* monitor_source_name;
  23618. ma_uint64 latency;
  23619. const char* driver;
  23620. ma_pa_sink_flags_t flags;
  23621. void* proplist;
  23622. ma_uint64 configured_latency;
  23623. ma_uint32 base_volume;
  23624. ma_pa_sink_state_t state;
  23625. ma_uint32 n_volume_steps;
  23626. ma_uint32 card;
  23627. ma_uint32 n_ports;
  23628. void** ports;
  23629. void* active_port;
  23630. ma_uint8 n_formats;
  23631. void** formats;
  23632. } ma_pa_sink_info;
  23633. typedef struct
  23634. {
  23635. const char *name;
  23636. ma_uint32 index;
  23637. const char *description;
  23638. ma_pa_sample_spec sample_spec;
  23639. ma_pa_channel_map channel_map;
  23640. ma_uint32 owner_module;
  23641. ma_pa_cvolume volume;
  23642. int mute;
  23643. ma_uint32 monitor_of_sink;
  23644. const char *monitor_of_sink_name;
  23645. ma_uint64 latency;
  23646. const char *driver;
  23647. ma_pa_source_flags_t flags;
  23648. void* proplist;
  23649. ma_uint64 configured_latency;
  23650. ma_uint32 base_volume;
  23651. ma_pa_source_state_t state;
  23652. ma_uint32 n_volume_steps;
  23653. ma_uint32 card;
  23654. ma_uint32 n_ports;
  23655. void** ports;
  23656. void* active_port;
  23657. ma_uint8 n_formats;
  23658. void** formats;
  23659. } ma_pa_source_info;
  23660. typedef void (* ma_pa_context_notify_cb_t)(ma_pa_context* c, void* userdata);
  23661. typedef void (* ma_pa_sink_info_cb_t) (ma_pa_context* c, const ma_pa_sink_info* i, int eol, void* userdata);
  23662. typedef void (* ma_pa_source_info_cb_t) (ma_pa_context* c, const ma_pa_source_info* i, int eol, void* userdata);
  23663. typedef void (* ma_pa_stream_success_cb_t)(ma_pa_stream* s, int success, void* userdata);
  23664. typedef void (* ma_pa_stream_request_cb_t)(ma_pa_stream* s, size_t nbytes, void* userdata);
  23665. typedef void (* ma_pa_stream_notify_cb_t) (ma_pa_stream* s, void* userdata);
  23666. typedef void (* ma_pa_free_cb_t) (void* p);
  23667. #endif
  23668. typedef ma_pa_mainloop* (* ma_pa_mainloop_new_proc) (void);
  23669. typedef void (* ma_pa_mainloop_free_proc) (ma_pa_mainloop* m);
  23670. typedef void (* ma_pa_mainloop_quit_proc) (ma_pa_mainloop* m, int retval);
  23671. typedef ma_pa_mainloop_api* (* ma_pa_mainloop_get_api_proc) (ma_pa_mainloop* m);
  23672. typedef int (* ma_pa_mainloop_iterate_proc) (ma_pa_mainloop* m, int block, int* retval);
  23673. typedef void (* ma_pa_mainloop_wakeup_proc) (ma_pa_mainloop* m);
  23674. typedef ma_pa_threaded_mainloop* (* ma_pa_threaded_mainloop_new_proc) (void);
  23675. typedef void (* ma_pa_threaded_mainloop_free_proc) (ma_pa_threaded_mainloop* m);
  23676. typedef int (* ma_pa_threaded_mainloop_start_proc) (ma_pa_threaded_mainloop* m);
  23677. typedef void (* ma_pa_threaded_mainloop_stop_proc) (ma_pa_threaded_mainloop* m);
  23678. typedef void (* ma_pa_threaded_mainloop_lock_proc) (ma_pa_threaded_mainloop* m);
  23679. typedef void (* ma_pa_threaded_mainloop_unlock_proc) (ma_pa_threaded_mainloop* m);
  23680. typedef void (* ma_pa_threaded_mainloop_wait_proc) (ma_pa_threaded_mainloop* m);
  23681. typedef void (* ma_pa_threaded_mainloop_signal_proc) (ma_pa_threaded_mainloop* m, int wait_for_accept);
  23682. typedef void (* ma_pa_threaded_mainloop_accept_proc) (ma_pa_threaded_mainloop* m);
  23683. typedef int (* ma_pa_threaded_mainloop_get_retval_proc) (ma_pa_threaded_mainloop* m);
  23684. typedef ma_pa_mainloop_api* (* ma_pa_threaded_mainloop_get_api_proc) (ma_pa_threaded_mainloop* m);
  23685. typedef int (* ma_pa_threaded_mainloop_in_thread_proc) (ma_pa_threaded_mainloop* m);
  23686. typedef void (* ma_pa_threaded_mainloop_set_name_proc) (ma_pa_threaded_mainloop* m, const char* name);
  23687. typedef ma_pa_context* (* ma_pa_context_new_proc) (ma_pa_mainloop_api* mainloop, const char* name);
  23688. typedef void (* ma_pa_context_unref_proc) (ma_pa_context* c);
  23689. 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);
  23690. typedef void (* ma_pa_context_disconnect_proc) (ma_pa_context* c);
  23691. typedef void (* ma_pa_context_set_state_callback_proc) (ma_pa_context* c, ma_pa_context_notify_cb_t cb, void* userdata);
  23692. typedef ma_pa_context_state_t (* ma_pa_context_get_state_proc) (ma_pa_context* c);
  23693. 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);
  23694. 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);
  23695. 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);
  23696. 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);
  23697. typedef void (* ma_pa_operation_unref_proc) (ma_pa_operation* o);
  23698. typedef ma_pa_operation_state_t (* ma_pa_operation_get_state_proc) (ma_pa_operation* o);
  23699. 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);
  23700. typedef int (* ma_pa_channel_map_valid_proc) (const ma_pa_channel_map* m);
  23701. typedef int (* ma_pa_channel_map_compatible_proc) (const ma_pa_channel_map* m, const ma_pa_sample_spec* ss);
  23702. 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);
  23703. typedef void (* ma_pa_stream_unref_proc) (ma_pa_stream* s);
  23704. 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);
  23705. 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);
  23706. typedef int (* ma_pa_stream_disconnect_proc) (ma_pa_stream* s);
  23707. typedef ma_pa_stream_state_t (* ma_pa_stream_get_state_proc) (ma_pa_stream* s);
  23708. typedef const ma_pa_sample_spec* (* ma_pa_stream_get_sample_spec_proc) (ma_pa_stream* s);
  23709. typedef const ma_pa_channel_map* (* ma_pa_stream_get_channel_map_proc) (ma_pa_stream* s);
  23710. typedef const ma_pa_buffer_attr* (* ma_pa_stream_get_buffer_attr_proc) (ma_pa_stream* s);
  23711. 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);
  23712. typedef const char* (* ma_pa_stream_get_device_name_proc) (ma_pa_stream* s);
  23713. typedef void (* ma_pa_stream_set_write_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  23714. typedef void (* ma_pa_stream_set_read_callback_proc) (ma_pa_stream* s, ma_pa_stream_request_cb_t cb, void* userdata);
  23715. typedef void (* ma_pa_stream_set_suspended_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  23716. typedef void (* ma_pa_stream_set_moved_callback_proc) (ma_pa_stream* s, ma_pa_stream_notify_cb_t cb, void* userdata);
  23717. typedef int (* ma_pa_stream_is_suspended_proc) (const ma_pa_stream* s);
  23718. typedef ma_pa_operation* (* ma_pa_stream_flush_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  23719. typedef ma_pa_operation* (* ma_pa_stream_drain_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  23720. typedef int (* ma_pa_stream_is_corked_proc) (ma_pa_stream* s);
  23721. typedef ma_pa_operation* (* ma_pa_stream_cork_proc) (ma_pa_stream* s, int b, ma_pa_stream_success_cb_t cb, void* userdata);
  23722. typedef ma_pa_operation* (* ma_pa_stream_trigger_proc) (ma_pa_stream* s, ma_pa_stream_success_cb_t cb, void* userdata);
  23723. typedef int (* ma_pa_stream_begin_write_proc) (ma_pa_stream* s, void** data, size_t* nbytes);
  23724. 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);
  23725. typedef int (* ma_pa_stream_peek_proc) (ma_pa_stream* s, const void** data, size_t* nbytes);
  23726. typedef int (* ma_pa_stream_drop_proc) (ma_pa_stream* s);
  23727. typedef size_t (* ma_pa_stream_writable_size_proc) (ma_pa_stream* s);
  23728. typedef size_t (* ma_pa_stream_readable_size_proc) (ma_pa_stream* s);
  23729. typedef struct
  23730. {
  23731. ma_uint32 count;
  23732. ma_uint32 capacity;
  23733. ma_device_info* pInfo;
  23734. } ma_pulse_device_enum_data;
  23735. static ma_result ma_result_from_pulse(int result)
  23736. {
  23737. if (result < 0) {
  23738. return MA_ERROR;
  23739. }
  23740. switch (result) {
  23741. case MA_PA_OK: return MA_SUCCESS;
  23742. case MA_PA_ERR_ACCESS: return MA_ACCESS_DENIED;
  23743. case MA_PA_ERR_INVALID: return MA_INVALID_ARGS;
  23744. case MA_PA_ERR_NOENTITY: return MA_NO_DEVICE;
  23745. default: return MA_ERROR;
  23746. }
  23747. }
  23748. #if 0
  23749. static ma_pa_sample_format_t ma_format_to_pulse(ma_format format)
  23750. {
  23751. if (ma_is_little_endian()) {
  23752. switch (format) {
  23753. case ma_format_s16: return MA_PA_SAMPLE_S16LE;
  23754. case ma_format_s24: return MA_PA_SAMPLE_S24LE;
  23755. case ma_format_s32: return MA_PA_SAMPLE_S32LE;
  23756. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32LE;
  23757. default: break;
  23758. }
  23759. } else {
  23760. switch (format) {
  23761. case ma_format_s16: return MA_PA_SAMPLE_S16BE;
  23762. case ma_format_s24: return MA_PA_SAMPLE_S24BE;
  23763. case ma_format_s32: return MA_PA_SAMPLE_S32BE;
  23764. case ma_format_f32: return MA_PA_SAMPLE_FLOAT32BE;
  23765. default: break;
  23766. }
  23767. }
  23768. /* Endian agnostic. */
  23769. switch (format) {
  23770. case ma_format_u8: return MA_PA_SAMPLE_U8;
  23771. default: return MA_PA_SAMPLE_INVALID;
  23772. }
  23773. }
  23774. #endif
  23775. static ma_format ma_format_from_pulse(ma_pa_sample_format_t format)
  23776. {
  23777. if (ma_is_little_endian()) {
  23778. switch (format) {
  23779. case MA_PA_SAMPLE_S16LE: return ma_format_s16;
  23780. case MA_PA_SAMPLE_S24LE: return ma_format_s24;
  23781. case MA_PA_SAMPLE_S32LE: return ma_format_s32;
  23782. case MA_PA_SAMPLE_FLOAT32LE: return ma_format_f32;
  23783. default: break;
  23784. }
  23785. } else {
  23786. switch (format) {
  23787. case MA_PA_SAMPLE_S16BE: return ma_format_s16;
  23788. case MA_PA_SAMPLE_S24BE: return ma_format_s24;
  23789. case MA_PA_SAMPLE_S32BE: return ma_format_s32;
  23790. case MA_PA_SAMPLE_FLOAT32BE: return ma_format_f32;
  23791. default: break;
  23792. }
  23793. }
  23794. /* Endian agnostic. */
  23795. switch (format) {
  23796. case MA_PA_SAMPLE_U8: return ma_format_u8;
  23797. default: return ma_format_unknown;
  23798. }
  23799. }
  23800. static ma_channel ma_channel_position_from_pulse(ma_pa_channel_position_t position)
  23801. {
  23802. switch (position)
  23803. {
  23804. case MA_PA_CHANNEL_POSITION_INVALID: return MA_CHANNEL_NONE;
  23805. case MA_PA_CHANNEL_POSITION_MONO: return MA_CHANNEL_MONO;
  23806. case MA_PA_CHANNEL_POSITION_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  23807. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  23808. case MA_PA_CHANNEL_POSITION_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  23809. case MA_PA_CHANNEL_POSITION_REAR_CENTER: return MA_CHANNEL_BACK_CENTER;
  23810. case MA_PA_CHANNEL_POSITION_REAR_LEFT: return MA_CHANNEL_BACK_LEFT;
  23811. case MA_PA_CHANNEL_POSITION_REAR_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  23812. case MA_PA_CHANNEL_POSITION_LFE: return MA_CHANNEL_LFE;
  23813. case MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  23814. case MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  23815. case MA_PA_CHANNEL_POSITION_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  23816. case MA_PA_CHANNEL_POSITION_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  23817. case MA_PA_CHANNEL_POSITION_AUX0: return MA_CHANNEL_AUX_0;
  23818. case MA_PA_CHANNEL_POSITION_AUX1: return MA_CHANNEL_AUX_1;
  23819. case MA_PA_CHANNEL_POSITION_AUX2: return MA_CHANNEL_AUX_2;
  23820. case MA_PA_CHANNEL_POSITION_AUX3: return MA_CHANNEL_AUX_3;
  23821. case MA_PA_CHANNEL_POSITION_AUX4: return MA_CHANNEL_AUX_4;
  23822. case MA_PA_CHANNEL_POSITION_AUX5: return MA_CHANNEL_AUX_5;
  23823. case MA_PA_CHANNEL_POSITION_AUX6: return MA_CHANNEL_AUX_6;
  23824. case MA_PA_CHANNEL_POSITION_AUX7: return MA_CHANNEL_AUX_7;
  23825. case MA_PA_CHANNEL_POSITION_AUX8: return MA_CHANNEL_AUX_8;
  23826. case MA_PA_CHANNEL_POSITION_AUX9: return MA_CHANNEL_AUX_9;
  23827. case MA_PA_CHANNEL_POSITION_AUX10: return MA_CHANNEL_AUX_10;
  23828. case MA_PA_CHANNEL_POSITION_AUX11: return MA_CHANNEL_AUX_11;
  23829. case MA_PA_CHANNEL_POSITION_AUX12: return MA_CHANNEL_AUX_12;
  23830. case MA_PA_CHANNEL_POSITION_AUX13: return MA_CHANNEL_AUX_13;
  23831. case MA_PA_CHANNEL_POSITION_AUX14: return MA_CHANNEL_AUX_14;
  23832. case MA_PA_CHANNEL_POSITION_AUX15: return MA_CHANNEL_AUX_15;
  23833. case MA_PA_CHANNEL_POSITION_AUX16: return MA_CHANNEL_AUX_16;
  23834. case MA_PA_CHANNEL_POSITION_AUX17: return MA_CHANNEL_AUX_17;
  23835. case MA_PA_CHANNEL_POSITION_AUX18: return MA_CHANNEL_AUX_18;
  23836. case MA_PA_CHANNEL_POSITION_AUX19: return MA_CHANNEL_AUX_19;
  23837. case MA_PA_CHANNEL_POSITION_AUX20: return MA_CHANNEL_AUX_20;
  23838. case MA_PA_CHANNEL_POSITION_AUX21: return MA_CHANNEL_AUX_21;
  23839. case MA_PA_CHANNEL_POSITION_AUX22: return MA_CHANNEL_AUX_22;
  23840. case MA_PA_CHANNEL_POSITION_AUX23: return MA_CHANNEL_AUX_23;
  23841. case MA_PA_CHANNEL_POSITION_AUX24: return MA_CHANNEL_AUX_24;
  23842. case MA_PA_CHANNEL_POSITION_AUX25: return MA_CHANNEL_AUX_25;
  23843. case MA_PA_CHANNEL_POSITION_AUX26: return MA_CHANNEL_AUX_26;
  23844. case MA_PA_CHANNEL_POSITION_AUX27: return MA_CHANNEL_AUX_27;
  23845. case MA_PA_CHANNEL_POSITION_AUX28: return MA_CHANNEL_AUX_28;
  23846. case MA_PA_CHANNEL_POSITION_AUX29: return MA_CHANNEL_AUX_29;
  23847. case MA_PA_CHANNEL_POSITION_AUX30: return MA_CHANNEL_AUX_30;
  23848. case MA_PA_CHANNEL_POSITION_AUX31: return MA_CHANNEL_AUX_31;
  23849. case MA_PA_CHANNEL_POSITION_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  23850. case MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  23851. case MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  23852. case MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  23853. case MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  23854. case MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  23855. case MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  23856. default: return MA_CHANNEL_NONE;
  23857. }
  23858. }
  23859. #if 0
  23860. static ma_pa_channel_position_t ma_channel_position_to_pulse(ma_channel position)
  23861. {
  23862. switch (position)
  23863. {
  23864. case MA_CHANNEL_NONE: return MA_PA_CHANNEL_POSITION_INVALID;
  23865. case MA_CHANNEL_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_FRONT_LEFT;
  23866. case MA_CHANNEL_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT;
  23867. case MA_CHANNEL_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_CENTER;
  23868. case MA_CHANNEL_LFE: return MA_PA_CHANNEL_POSITION_LFE;
  23869. case MA_CHANNEL_BACK_LEFT: return MA_PA_CHANNEL_POSITION_REAR_LEFT;
  23870. case MA_CHANNEL_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_REAR_RIGHT;
  23871. case MA_CHANNEL_FRONT_LEFT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_LEFT_OF_CENTER;
  23872. case MA_CHANNEL_FRONT_RIGHT_CENTER: return MA_PA_CHANNEL_POSITION_FRONT_RIGHT_OF_CENTER;
  23873. case MA_CHANNEL_BACK_CENTER: return MA_PA_CHANNEL_POSITION_REAR_CENTER;
  23874. case MA_CHANNEL_SIDE_LEFT: return MA_PA_CHANNEL_POSITION_SIDE_LEFT;
  23875. case MA_CHANNEL_SIDE_RIGHT: return MA_PA_CHANNEL_POSITION_SIDE_RIGHT;
  23876. case MA_CHANNEL_TOP_CENTER: return MA_PA_CHANNEL_POSITION_TOP_CENTER;
  23877. case MA_CHANNEL_TOP_FRONT_LEFT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_LEFT;
  23878. case MA_CHANNEL_TOP_FRONT_CENTER: return MA_PA_CHANNEL_POSITION_TOP_FRONT_CENTER;
  23879. case MA_CHANNEL_TOP_FRONT_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_FRONT_RIGHT;
  23880. case MA_CHANNEL_TOP_BACK_LEFT: return MA_PA_CHANNEL_POSITION_TOP_REAR_LEFT;
  23881. case MA_CHANNEL_TOP_BACK_CENTER: return MA_PA_CHANNEL_POSITION_TOP_REAR_CENTER;
  23882. case MA_CHANNEL_TOP_BACK_RIGHT: return MA_PA_CHANNEL_POSITION_TOP_REAR_RIGHT;
  23883. case MA_CHANNEL_19: return MA_PA_CHANNEL_POSITION_AUX18;
  23884. case MA_CHANNEL_20: return MA_PA_CHANNEL_POSITION_AUX19;
  23885. case MA_CHANNEL_21: return MA_PA_CHANNEL_POSITION_AUX20;
  23886. case MA_CHANNEL_22: return MA_PA_CHANNEL_POSITION_AUX21;
  23887. case MA_CHANNEL_23: return MA_PA_CHANNEL_POSITION_AUX22;
  23888. case MA_CHANNEL_24: return MA_PA_CHANNEL_POSITION_AUX23;
  23889. case MA_CHANNEL_25: return MA_PA_CHANNEL_POSITION_AUX24;
  23890. case MA_CHANNEL_26: return MA_PA_CHANNEL_POSITION_AUX25;
  23891. case MA_CHANNEL_27: return MA_PA_CHANNEL_POSITION_AUX26;
  23892. case MA_CHANNEL_28: return MA_PA_CHANNEL_POSITION_AUX27;
  23893. case MA_CHANNEL_29: return MA_PA_CHANNEL_POSITION_AUX28;
  23894. case MA_CHANNEL_30: return MA_PA_CHANNEL_POSITION_AUX29;
  23895. case MA_CHANNEL_31: return MA_PA_CHANNEL_POSITION_AUX30;
  23896. case MA_CHANNEL_32: return MA_PA_CHANNEL_POSITION_AUX31;
  23897. default: return (ma_pa_channel_position_t)position;
  23898. }
  23899. }
  23900. #endif
  23901. static ma_result ma_wait_for_operation__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  23902. {
  23903. int resultPA;
  23904. ma_pa_operation_state_t state;
  23905. MA_ASSERT(pContext != NULL);
  23906. MA_ASSERT(pOP != NULL);
  23907. for (;;) {
  23908. state = ((ma_pa_operation_get_state_proc)pContext->pulse.pa_operation_get_state)(pOP);
  23909. if (state != MA_PA_OPERATION_RUNNING) {
  23910. break; /* Done. */
  23911. }
  23912. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  23913. if (resultPA < 0) {
  23914. return ma_result_from_pulse(resultPA);
  23915. }
  23916. }
  23917. return MA_SUCCESS;
  23918. }
  23919. static ma_result ma_wait_for_operation_and_unref__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_pa_operation* pOP)
  23920. {
  23921. ma_result result;
  23922. if (pOP == NULL) {
  23923. return MA_INVALID_ARGS;
  23924. }
  23925. result = ma_wait_for_operation__pulse(pContext, pMainLoop, pOP);
  23926. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  23927. return result;
  23928. }
  23929. static ma_result ma_wait_for_pa_context_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pPulseContext)
  23930. {
  23931. int resultPA;
  23932. ma_pa_context_state_t state;
  23933. for (;;) {
  23934. state = ((ma_pa_context_get_state_proc)pContext->pulse.pa_context_get_state)((ma_pa_context*)pPulseContext);
  23935. if (state == MA_PA_CONTEXT_READY) {
  23936. break; /* Done. */
  23937. }
  23938. if (state == MA_PA_CONTEXT_FAILED || state == MA_PA_CONTEXT_TERMINATED) {
  23939. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio context.");
  23940. return MA_ERROR;
  23941. }
  23942. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  23943. if (resultPA < 0) {
  23944. return ma_result_from_pulse(resultPA);
  23945. }
  23946. }
  23947. /* Should never get here. */
  23948. return MA_SUCCESS;
  23949. }
  23950. static ma_result ma_wait_for_pa_stream_to_connect__pulse(ma_context* pContext, ma_ptr pMainLoop, ma_ptr pStream)
  23951. {
  23952. int resultPA;
  23953. ma_pa_stream_state_t state;
  23954. for (;;) {
  23955. state = ((ma_pa_stream_get_state_proc)pContext->pulse.pa_stream_get_state)((ma_pa_stream*)pStream);
  23956. if (state == MA_PA_STREAM_READY) {
  23957. break; /* Done. */
  23958. }
  23959. if (state == MA_PA_STREAM_FAILED || state == MA_PA_STREAM_TERMINATED) {
  23960. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while connecting the PulseAudio stream.");
  23961. return MA_ERROR;
  23962. }
  23963. resultPA = ((ma_pa_mainloop_iterate_proc)pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pMainLoop, 1, NULL);
  23964. if (resultPA < 0) {
  23965. return ma_result_from_pulse(resultPA);
  23966. }
  23967. }
  23968. return MA_SUCCESS;
  23969. }
  23970. 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)
  23971. {
  23972. ma_result result;
  23973. ma_ptr pMainLoop;
  23974. ma_ptr pPulseContext;
  23975. MA_ASSERT(ppMainLoop != NULL);
  23976. MA_ASSERT(ppPulseContext != NULL);
  23977. /* 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. */
  23978. pMainLoop = ((ma_pa_mainloop_new_proc)pContext->pulse.pa_mainloop_new)();
  23979. if (pMainLoop == NULL) {
  23980. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create mainloop.");
  23981. return MA_FAILED_TO_INIT_BACKEND;
  23982. }
  23983. 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);
  23984. if (pPulseContext == NULL) {
  23985. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio context.");
  23986. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  23987. return MA_FAILED_TO_INIT_BACKEND;
  23988. }
  23989. /* Now we need to connect to the context. Everything is asynchronous so we need to wait for it to connect before returning. */
  23990. 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));
  23991. if (result != MA_SUCCESS) {
  23992. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio context.");
  23993. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  23994. return result;
  23995. }
  23996. /* Since ma_context_init() runs synchronously we need to wait for the PulseAudio context to connect before we return. */
  23997. result = ma_wait_for_pa_context_to_connect__pulse(pContext, pMainLoop, pPulseContext);
  23998. if (result != MA_SUCCESS) {
  23999. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[PulseAudio] Waiting for connection failed.");
  24000. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)(pMainLoop));
  24001. return result;
  24002. }
  24003. *ppMainLoop = pMainLoop;
  24004. *ppPulseContext = pPulseContext;
  24005. return MA_SUCCESS;
  24006. }
  24007. static void ma_device_sink_info_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24008. {
  24009. ma_pa_sink_info* pInfoOut;
  24010. if (endOfList > 0) {
  24011. return;
  24012. }
  24013. /*
  24014. There has been a report that indicates that pInfo can be null which results
  24015. in a null pointer dereference below. We'll check for this for safety.
  24016. */
  24017. if (pInfo == NULL) {
  24018. return;
  24019. }
  24020. pInfoOut = (ma_pa_sink_info*)pUserData;
  24021. MA_ASSERT(pInfoOut != NULL);
  24022. *pInfoOut = *pInfo;
  24023. (void)pPulseContext; /* Unused. */
  24024. }
  24025. static void ma_device_source_info_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24026. {
  24027. ma_pa_source_info* pInfoOut;
  24028. if (endOfList > 0) {
  24029. return;
  24030. }
  24031. /*
  24032. There has been a report that indicates that pInfo can be null which results
  24033. in a null pointer dereference below. We'll check for this for safety.
  24034. */
  24035. if (pInfo == NULL) {
  24036. return;
  24037. }
  24038. pInfoOut = (ma_pa_source_info*)pUserData;
  24039. MA_ASSERT(pInfoOut != NULL);
  24040. *pInfoOut = *pInfo;
  24041. (void)pPulseContext; /* Unused. */
  24042. }
  24043. #if 0
  24044. static void ma_device_sink_name_callback(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24045. {
  24046. ma_device* pDevice;
  24047. if (endOfList > 0) {
  24048. return;
  24049. }
  24050. pDevice = (ma_device*)pUserData;
  24051. MA_ASSERT(pDevice != NULL);
  24052. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), pInfo->description, (size_t)-1);
  24053. (void)pPulseContext; /* Unused. */
  24054. }
  24055. static void ma_device_source_name_callback(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24056. {
  24057. ma_device* pDevice;
  24058. if (endOfList > 0) {
  24059. return;
  24060. }
  24061. pDevice = (ma_device*)pUserData;
  24062. MA_ASSERT(pDevice != NULL);
  24063. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), pInfo->description, (size_t)-1);
  24064. (void)pPulseContext; /* Unused. */
  24065. }
  24066. #endif
  24067. static ma_result ma_context_get_sink_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_sink_info* pSinkInfo)
  24068. {
  24069. ma_pa_operation* pOP;
  24070. 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);
  24071. if (pOP == NULL) {
  24072. return MA_ERROR;
  24073. }
  24074. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24075. }
  24076. static ma_result ma_context_get_source_info__pulse(ma_context* pContext, const char* pDeviceName, ma_pa_source_info* pSourceInfo)
  24077. {
  24078. ma_pa_operation* pOP;
  24079. 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);
  24080. if (pOP == NULL) {
  24081. return MA_ERROR;
  24082. }
  24083. return ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24084. }
  24085. static ma_result ma_context_get_default_device_index__pulse(ma_context* pContext, ma_device_type deviceType, ma_uint32* pIndex)
  24086. {
  24087. ma_result result;
  24088. MA_ASSERT(pContext != NULL);
  24089. MA_ASSERT(pIndex != NULL);
  24090. if (pIndex != NULL) {
  24091. *pIndex = (ma_uint32)-1;
  24092. }
  24093. if (deviceType == ma_device_type_playback) {
  24094. ma_pa_sink_info sinkInfo;
  24095. result = ma_context_get_sink_info__pulse(pContext, NULL, &sinkInfo);
  24096. if (result != MA_SUCCESS) {
  24097. return result;
  24098. }
  24099. if (pIndex != NULL) {
  24100. *pIndex = sinkInfo.index;
  24101. }
  24102. }
  24103. if (deviceType == ma_device_type_capture) {
  24104. ma_pa_source_info sourceInfo;
  24105. result = ma_context_get_source_info__pulse(pContext, NULL, &sourceInfo);
  24106. if (result != MA_SUCCESS) {
  24107. return result;
  24108. }
  24109. if (pIndex != NULL) {
  24110. *pIndex = sourceInfo.index;
  24111. }
  24112. }
  24113. return MA_SUCCESS;
  24114. }
  24115. typedef struct
  24116. {
  24117. ma_context* pContext;
  24118. ma_enum_devices_callback_proc callback;
  24119. void* pUserData;
  24120. ma_bool32 isTerminated;
  24121. ma_uint32 defaultDeviceIndexPlayback;
  24122. ma_uint32 defaultDeviceIndexCapture;
  24123. } ma_context_enumerate_devices_callback_data__pulse;
  24124. static void ma_context_enumerate_devices_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pSinkInfo, int endOfList, void* pUserData)
  24125. {
  24126. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  24127. ma_device_info deviceInfo;
  24128. MA_ASSERT(pData != NULL);
  24129. if (endOfList || pData->isTerminated) {
  24130. return;
  24131. }
  24132. MA_ZERO_OBJECT(&deviceInfo);
  24133. /* The name from PulseAudio is the ID for miniaudio. */
  24134. if (pSinkInfo->name != NULL) {
  24135. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSinkInfo->name, (size_t)-1);
  24136. }
  24137. /* The description from PulseAudio is the name for miniaudio. */
  24138. if (pSinkInfo->description != NULL) {
  24139. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSinkInfo->description, (size_t)-1);
  24140. }
  24141. if (pSinkInfo->index == pData->defaultDeviceIndexPlayback) {
  24142. deviceInfo.isDefault = MA_TRUE;
  24143. }
  24144. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_playback, &deviceInfo, pData->pUserData);
  24145. (void)pPulseContext; /* Unused. */
  24146. }
  24147. static void ma_context_enumerate_devices_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pSourceInfo, int endOfList, void* pUserData)
  24148. {
  24149. ma_context_enumerate_devices_callback_data__pulse* pData = (ma_context_enumerate_devices_callback_data__pulse*)pUserData;
  24150. ma_device_info deviceInfo;
  24151. MA_ASSERT(pData != NULL);
  24152. if (endOfList || pData->isTerminated) {
  24153. return;
  24154. }
  24155. MA_ZERO_OBJECT(&deviceInfo);
  24156. /* The name from PulseAudio is the ID for miniaudio. */
  24157. if (pSourceInfo->name != NULL) {
  24158. ma_strncpy_s(deviceInfo.id.pulse, sizeof(deviceInfo.id.pulse), pSourceInfo->name, (size_t)-1);
  24159. }
  24160. /* The description from PulseAudio is the name for miniaudio. */
  24161. if (pSourceInfo->description != NULL) {
  24162. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), pSourceInfo->description, (size_t)-1);
  24163. }
  24164. if (pSourceInfo->index == pData->defaultDeviceIndexCapture) {
  24165. deviceInfo.isDefault = MA_TRUE;
  24166. }
  24167. pData->isTerminated = !pData->callback(pData->pContext, ma_device_type_capture, &deviceInfo, pData->pUserData);
  24168. (void)pPulseContext; /* Unused. */
  24169. }
  24170. static ma_result ma_context_enumerate_devices__pulse(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  24171. {
  24172. ma_result result = MA_SUCCESS;
  24173. ma_context_enumerate_devices_callback_data__pulse callbackData;
  24174. ma_pa_operation* pOP = NULL;
  24175. MA_ASSERT(pContext != NULL);
  24176. MA_ASSERT(callback != NULL);
  24177. callbackData.pContext = pContext;
  24178. callbackData.callback = callback;
  24179. callbackData.pUserData = pUserData;
  24180. callbackData.isTerminated = MA_FALSE;
  24181. callbackData.defaultDeviceIndexPlayback = (ma_uint32)-1;
  24182. callbackData.defaultDeviceIndexCapture = (ma_uint32)-1;
  24183. /* We need to get the index of the default devices. */
  24184. ma_context_get_default_device_index__pulse(pContext, ma_device_type_playback, &callbackData.defaultDeviceIndexPlayback);
  24185. ma_context_get_default_device_index__pulse(pContext, ma_device_type_capture, &callbackData.defaultDeviceIndexCapture);
  24186. /* Playback. */
  24187. if (!callbackData.isTerminated) {
  24188. 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);
  24189. if (pOP == NULL) {
  24190. result = MA_ERROR;
  24191. goto done;
  24192. }
  24193. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24194. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  24195. if (result != MA_SUCCESS) {
  24196. goto done;
  24197. }
  24198. }
  24199. /* Capture. */
  24200. if (!callbackData.isTerminated) {
  24201. 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);
  24202. if (pOP == NULL) {
  24203. result = MA_ERROR;
  24204. goto done;
  24205. }
  24206. result = ma_wait_for_operation__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24207. ((ma_pa_operation_unref_proc)pContext->pulse.pa_operation_unref)(pOP);
  24208. if (result != MA_SUCCESS) {
  24209. goto done;
  24210. }
  24211. }
  24212. done:
  24213. return result;
  24214. }
  24215. typedef struct
  24216. {
  24217. ma_device_info* pDeviceInfo;
  24218. ma_uint32 defaultDeviceIndex;
  24219. ma_bool32 foundDevice;
  24220. } ma_context_get_device_info_callback_data__pulse;
  24221. static void ma_context_get_device_info_sink_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_sink_info* pInfo, int endOfList, void* pUserData)
  24222. {
  24223. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  24224. if (endOfList > 0) {
  24225. return;
  24226. }
  24227. MA_ASSERT(pData != NULL);
  24228. pData->foundDevice = MA_TRUE;
  24229. if (pInfo->name != NULL) {
  24230. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  24231. }
  24232. if (pInfo->description != NULL) {
  24233. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  24234. }
  24235. /*
  24236. We're just reporting a single data format here. I think technically PulseAudio might support
  24237. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  24238. report the "native" device format.
  24239. */
  24240. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  24241. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  24242. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  24243. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  24244. pData->pDeviceInfo->nativeDataFormatCount = 1;
  24245. if (pData->defaultDeviceIndex == pInfo->index) {
  24246. pData->pDeviceInfo->isDefault = MA_TRUE;
  24247. }
  24248. (void)pPulseContext; /* Unused. */
  24249. }
  24250. static void ma_context_get_device_info_source_callback__pulse(ma_pa_context* pPulseContext, const ma_pa_source_info* pInfo, int endOfList, void* pUserData)
  24251. {
  24252. ma_context_get_device_info_callback_data__pulse* pData = (ma_context_get_device_info_callback_data__pulse*)pUserData;
  24253. if (endOfList > 0) {
  24254. return;
  24255. }
  24256. MA_ASSERT(pData != NULL);
  24257. pData->foundDevice = MA_TRUE;
  24258. if (pInfo->name != NULL) {
  24259. ma_strncpy_s(pData->pDeviceInfo->id.pulse, sizeof(pData->pDeviceInfo->id.pulse), pInfo->name, (size_t)-1);
  24260. }
  24261. if (pInfo->description != NULL) {
  24262. ma_strncpy_s(pData->pDeviceInfo->name, sizeof(pData->pDeviceInfo->name), pInfo->description, (size_t)-1);
  24263. }
  24264. /*
  24265. We're just reporting a single data format here. I think technically PulseAudio might support
  24266. all formats, but I don't trust that PulseAudio will do *anything* right, so I'm just going to
  24267. report the "native" device format.
  24268. */
  24269. pData->pDeviceInfo->nativeDataFormats[0].format = ma_format_from_pulse(pInfo->sample_spec.format);
  24270. pData->pDeviceInfo->nativeDataFormats[0].channels = pInfo->sample_spec.channels;
  24271. pData->pDeviceInfo->nativeDataFormats[0].sampleRate = pInfo->sample_spec.rate;
  24272. pData->pDeviceInfo->nativeDataFormats[0].flags = 0;
  24273. pData->pDeviceInfo->nativeDataFormatCount = 1;
  24274. if (pData->defaultDeviceIndex == pInfo->index) {
  24275. pData->pDeviceInfo->isDefault = MA_TRUE;
  24276. }
  24277. (void)pPulseContext; /* Unused. */
  24278. }
  24279. 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)
  24280. {
  24281. ma_result result = MA_SUCCESS;
  24282. ma_context_get_device_info_callback_data__pulse callbackData;
  24283. ma_pa_operation* pOP = NULL;
  24284. const char* pDeviceName = NULL;
  24285. MA_ASSERT(pContext != NULL);
  24286. callbackData.pDeviceInfo = pDeviceInfo;
  24287. callbackData.foundDevice = MA_FALSE;
  24288. if (pDeviceID != NULL) {
  24289. pDeviceName = pDeviceID->pulse;
  24290. } else {
  24291. pDeviceName = NULL;
  24292. }
  24293. result = ma_context_get_default_device_index__pulse(pContext, deviceType, &callbackData.defaultDeviceIndex);
  24294. if (deviceType == ma_device_type_playback) {
  24295. 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);
  24296. } else {
  24297. 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);
  24298. }
  24299. if (pOP != NULL) {
  24300. ma_wait_for_operation_and_unref__pulse(pContext, pContext->pulse.pMainLoop, pOP);
  24301. } else {
  24302. result = MA_ERROR;
  24303. goto done;
  24304. }
  24305. if (!callbackData.foundDevice) {
  24306. result = MA_NO_DEVICE;
  24307. goto done;
  24308. }
  24309. done:
  24310. return result;
  24311. }
  24312. static ma_result ma_device_uninit__pulse(ma_device* pDevice)
  24313. {
  24314. ma_context* pContext;
  24315. MA_ASSERT(pDevice != NULL);
  24316. pContext = pDevice->pContext;
  24317. MA_ASSERT(pContext != NULL);
  24318. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  24319. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24320. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24321. }
  24322. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  24323. ((ma_pa_stream_disconnect_proc)pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24324. ((ma_pa_stream_unref_proc)pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24325. }
  24326. if (pDevice->type == ma_device_type_duplex) {
  24327. ma_duplex_rb_uninit(&pDevice->duplexRB);
  24328. }
  24329. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pDevice->pulse.pPulseContext);
  24330. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pDevice->pulse.pPulseContext);
  24331. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  24332. return MA_SUCCESS;
  24333. }
  24334. static ma_pa_buffer_attr ma_device__pa_buffer_attr_new(ma_uint32 periodSizeInFrames, ma_uint32 periods, const ma_pa_sample_spec* ss)
  24335. {
  24336. ma_pa_buffer_attr attr;
  24337. attr.maxlength = periodSizeInFrames * periods * ma_get_bytes_per_frame(ma_format_from_pulse(ss->format), ss->channels);
  24338. attr.tlength = attr.maxlength / periods;
  24339. attr.prebuf = (ma_uint32)-1;
  24340. attr.minreq = (ma_uint32)-1;
  24341. attr.fragsize = attr.maxlength / periods;
  24342. return attr;
  24343. }
  24344. 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)
  24345. {
  24346. static int g_StreamCounter = 0;
  24347. char actualStreamName[256];
  24348. if (pStreamName != NULL) {
  24349. ma_strncpy_s(actualStreamName, sizeof(actualStreamName), pStreamName, (size_t)-1);
  24350. } else {
  24351. ma_strcpy_s(actualStreamName, sizeof(actualStreamName), "miniaudio:");
  24352. ma_itoa_s(g_StreamCounter, actualStreamName + 8, sizeof(actualStreamName)-8, 10); /* 8 = strlen("miniaudio:") */
  24353. }
  24354. g_StreamCounter += 1;
  24355. return ((ma_pa_stream_new_proc)pDevice->pContext->pulse.pa_stream_new)((ma_pa_context*)pDevice->pulse.pPulseContext, actualStreamName, ss, cmap);
  24356. }
  24357. static void ma_device_on_read__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  24358. {
  24359. ma_device* pDevice = (ma_device*)pUserData;
  24360. ma_uint32 bpf;
  24361. ma_uint32 deviceState;
  24362. ma_uint64 frameCount;
  24363. ma_uint64 framesProcessed;
  24364. MA_ASSERT(pDevice != NULL);
  24365. /*
  24366. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  24367. can fire this callback before the stream has even started. Ridiculous.
  24368. */
  24369. deviceState = ma_device_get_state(pDevice);
  24370. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  24371. return;
  24372. }
  24373. bpf = ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  24374. MA_ASSERT(bpf > 0);
  24375. frameCount = byteCount / bpf;
  24376. framesProcessed = 0;
  24377. while (ma_device_get_state(pDevice) == ma_device_state_started && framesProcessed < frameCount) {
  24378. const void* pMappedPCMFrames;
  24379. size_t bytesMapped;
  24380. ma_uint64 framesMapped;
  24381. int pulseResult = ((ma_pa_stream_peek_proc)pDevice->pContext->pulse.pa_stream_peek)(pStream, &pMappedPCMFrames, &bytesMapped);
  24382. if (pulseResult < 0) {
  24383. break; /* Failed to map. Abort. */
  24384. }
  24385. framesMapped = bytesMapped / bpf;
  24386. if (framesMapped > 0) {
  24387. if (pMappedPCMFrames != NULL) {
  24388. ma_device_handle_backend_data_callback(pDevice, NULL, pMappedPCMFrames, framesMapped);
  24389. } else {
  24390. /* It's a hole. */
  24391. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[PulseAudio] ma_device_on_read__pulse: Hole.\n");
  24392. }
  24393. pulseResult = ((ma_pa_stream_drop_proc)pDevice->pContext->pulse.pa_stream_drop)(pStream);
  24394. if (pulseResult < 0) {
  24395. break; /* Failed to drop the buffer. */
  24396. }
  24397. framesProcessed += framesMapped;
  24398. } else {
  24399. /* Nothing was mapped. Just abort. */
  24400. break;
  24401. }
  24402. }
  24403. }
  24404. static ma_result ma_device_write_to_stream__pulse(ma_device* pDevice, ma_pa_stream* pStream, ma_uint64* pFramesProcessed)
  24405. {
  24406. ma_result result = MA_SUCCESS;
  24407. ma_uint64 framesProcessed = 0;
  24408. size_t bytesMapped;
  24409. ma_uint32 bpf;
  24410. ma_uint32 deviceState;
  24411. MA_ASSERT(pDevice != NULL);
  24412. MA_ASSERT(pStream != NULL);
  24413. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  24414. MA_ASSERT(bpf > 0);
  24415. deviceState = ma_device_get_state(pDevice);
  24416. bytesMapped = ((ma_pa_stream_writable_size_proc)pDevice->pContext->pulse.pa_stream_writable_size)(pStream);
  24417. if (bytesMapped != (size_t)-1) {
  24418. if (bytesMapped > 0) {
  24419. ma_uint64 framesMapped;
  24420. void* pMappedPCMFrames;
  24421. int pulseResult = ((ma_pa_stream_begin_write_proc)pDevice->pContext->pulse.pa_stream_begin_write)(pStream, &pMappedPCMFrames, &bytesMapped);
  24422. if (pulseResult < 0) {
  24423. result = ma_result_from_pulse(pulseResult);
  24424. goto done;
  24425. }
  24426. framesMapped = bytesMapped / bpf;
  24427. 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. */
  24428. ma_device_handle_backend_data_callback(pDevice, pMappedPCMFrames, NULL, framesMapped);
  24429. } else {
  24430. /* Device is not started. Write silence. */
  24431. ma_silence_pcm_frames(pMappedPCMFrames, framesMapped, pDevice->playback.format, pDevice->playback.channels);
  24432. }
  24433. pulseResult = ((ma_pa_stream_write_proc)pDevice->pContext->pulse.pa_stream_write)(pStream, pMappedPCMFrames, bytesMapped, NULL, 0, MA_PA_SEEK_RELATIVE);
  24434. if (pulseResult < 0) {
  24435. result = ma_result_from_pulse(pulseResult);
  24436. goto done; /* Failed to write data to stream. */
  24437. }
  24438. framesProcessed += framesMapped;
  24439. } else {
  24440. result = MA_SUCCESS; /* No data available for writing. */
  24441. goto done;
  24442. }
  24443. } else {
  24444. result = MA_ERROR; /* Failed to retrieve the writable size. Abort. */
  24445. goto done;
  24446. }
  24447. done:
  24448. if (pFramesProcessed != NULL) {
  24449. *pFramesProcessed = framesProcessed;
  24450. }
  24451. return result;
  24452. }
  24453. static void ma_device_on_write__pulse(ma_pa_stream* pStream, size_t byteCount, void* pUserData)
  24454. {
  24455. ma_device* pDevice = (ma_device*)pUserData;
  24456. ma_uint32 bpf;
  24457. ma_uint64 frameCount;
  24458. ma_uint64 framesProcessed;
  24459. ma_uint32 deviceState;
  24460. ma_result result;
  24461. MA_ASSERT(pDevice != NULL);
  24462. /*
  24463. Don't do anything if the device isn't initialized yet. Yes, this can happen because PulseAudio
  24464. can fire this callback before the stream has even started. Ridiculous.
  24465. */
  24466. deviceState = ma_device_get_state(pDevice);
  24467. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  24468. return;
  24469. }
  24470. bpf = ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  24471. MA_ASSERT(bpf > 0);
  24472. frameCount = byteCount / bpf;
  24473. framesProcessed = 0;
  24474. while (framesProcessed < frameCount) {
  24475. ma_uint64 framesProcessedThisIteration;
  24476. /* Don't keep trying to process frames if the device isn't started. */
  24477. deviceState = ma_device_get_state(pDevice);
  24478. if (deviceState != ma_device_state_starting && deviceState != ma_device_state_started) {
  24479. break;
  24480. }
  24481. result = ma_device_write_to_stream__pulse(pDevice, pStream, &framesProcessedThisIteration);
  24482. if (result != MA_SUCCESS) {
  24483. break;
  24484. }
  24485. framesProcessed += framesProcessedThisIteration;
  24486. }
  24487. }
  24488. static void ma_device_on_suspended__pulse(ma_pa_stream* pStream, void* pUserData)
  24489. {
  24490. ma_device* pDevice = (ma_device*)pUserData;
  24491. int suspended;
  24492. (void)pStream;
  24493. suspended = ((ma_pa_stream_is_suspended_proc)pDevice->pContext->pulse.pa_stream_is_suspended)(pStream);
  24494. 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);
  24495. if (suspended < 0) {
  24496. return;
  24497. }
  24498. if (suspended == 1) {
  24499. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Suspended.\n");
  24500. ma_device__on_notification_stopped(pDevice);
  24501. } else {
  24502. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "[Pulse] Device suspended state changed. Resumed.\n");
  24503. ma_device__on_notification_started(pDevice);
  24504. }
  24505. }
  24506. static void ma_device_on_rerouted__pulse(ma_pa_stream* pStream, void* pUserData)
  24507. {
  24508. ma_device* pDevice = (ma_device*)pUserData;
  24509. (void)pStream;
  24510. (void)pUserData;
  24511. ma_device__on_notification_rerouted(pDevice);
  24512. }
  24513. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__pulse(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  24514. {
  24515. /*
  24516. There have been reports from users where buffers of < ~20ms result glitches when running through
  24517. PipeWire. To work around this we're going to have to use a different default buffer size.
  24518. */
  24519. const ma_uint32 defaultPeriodSizeInMilliseconds_LowLatency = 25;
  24520. const ma_uint32 defaultPeriodSizeInMilliseconds_Conservative = MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE;
  24521. MA_ASSERT(nativeSampleRate != 0);
  24522. if (pDescriptor->periodSizeInFrames == 0) {
  24523. if (pDescriptor->periodSizeInMilliseconds == 0) {
  24524. if (performanceProfile == ma_performance_profile_low_latency) {
  24525. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_LowLatency, nativeSampleRate);
  24526. } else {
  24527. return ma_calculate_buffer_size_in_frames_from_milliseconds(defaultPeriodSizeInMilliseconds_Conservative, nativeSampleRate);
  24528. }
  24529. } else {
  24530. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  24531. }
  24532. } else {
  24533. return pDescriptor->periodSizeInFrames;
  24534. }
  24535. }
  24536. static ma_result ma_device_init__pulse(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  24537. {
  24538. /*
  24539. Notes for PulseAudio:
  24540. - We're always using native format/channels/rate regardless of whether or not PulseAudio
  24541. supports the format directly through their own data conversion system. I'm doing this to
  24542. reduce as much variability from the PulseAudio side as possible because it's seems to be
  24543. extremely unreliable at everything it does.
  24544. - When both the period size in frames and milliseconds are 0, we default to miniaudio's
  24545. default buffer sizes rather than leaving it up to PulseAudio because I don't trust
  24546. PulseAudio to give us any kind of reasonable latency by default.
  24547. - Do not ever, *ever* forget to use MA_PA_STREAM_ADJUST_LATENCY. If you don't specify this
  24548. flag, capture mode will just not work properly until you open another PulseAudio app.
  24549. */
  24550. ma_result result = MA_SUCCESS;
  24551. int error = 0;
  24552. const char* devPlayback = NULL;
  24553. const char* devCapture = NULL;
  24554. ma_format format = ma_format_unknown;
  24555. ma_uint32 channels = 0;
  24556. ma_uint32 sampleRate = 0;
  24557. ma_pa_sink_info sinkInfo;
  24558. ma_pa_source_info sourceInfo;
  24559. ma_pa_sample_spec ss;
  24560. ma_pa_channel_map cmap;
  24561. ma_pa_buffer_attr attr;
  24562. const ma_pa_sample_spec* pActualSS = NULL;
  24563. const ma_pa_channel_map* pActualCMap = NULL;
  24564. const ma_pa_buffer_attr* pActualAttr = NULL;
  24565. ma_uint32 iChannel;
  24566. ma_pa_stream_flags_t streamFlags;
  24567. MA_ASSERT(pDevice != NULL);
  24568. MA_ZERO_OBJECT(&pDevice->pulse);
  24569. if (pConfig->deviceType == ma_device_type_loopback) {
  24570. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  24571. }
  24572. /* No exclusive mode with the PulseAudio backend. */
  24573. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pConfig->playback.shareMode == ma_share_mode_exclusive) ||
  24574. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pConfig->capture.shareMode == ma_share_mode_exclusive)) {
  24575. return MA_SHARE_MODE_NOT_SUPPORTED;
  24576. }
  24577. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  24578. if (pDescriptorPlayback->pDeviceID != NULL) {
  24579. devPlayback = pDescriptorPlayback->pDeviceID->pulse;
  24580. }
  24581. format = pDescriptorPlayback->format;
  24582. channels = pDescriptorPlayback->channels;
  24583. sampleRate = pDescriptorPlayback->sampleRate;
  24584. }
  24585. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  24586. if (pDescriptorCapture->pDeviceID != NULL) {
  24587. devCapture = pDescriptorCapture->pDeviceID->pulse;
  24588. }
  24589. format = pDescriptorCapture->format;
  24590. channels = pDescriptorCapture->channels;
  24591. sampleRate = pDescriptorCapture->sampleRate;
  24592. }
  24593. 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);
  24594. if (result != MA_SUCCESS) {
  24595. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize PA mainloop and context for device.\n");
  24596. return result;
  24597. }
  24598. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  24599. result = ma_context_get_source_info__pulse(pDevice->pContext, devCapture, &sourceInfo);
  24600. if (result != MA_SUCCESS) {
  24601. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve source info for capture device.");
  24602. goto on_error0;
  24603. }
  24604. ss = sourceInfo.sample_spec;
  24605. cmap = sourceInfo.channel_map;
  24606. /* Use the requested sample rate if one was specified. */
  24607. if (pDescriptorCapture->sampleRate != 0) {
  24608. ss.rate = pDescriptorCapture->sampleRate;
  24609. }
  24610. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  24611. if (ma_is_little_endian()) {
  24612. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  24613. } else {
  24614. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  24615. }
  24616. 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");
  24617. }
  24618. if (ss.rate == 0) {
  24619. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  24620. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  24621. }
  24622. if (ss.channels == 0) {
  24623. ss.channels = MA_DEFAULT_CHANNELS;
  24624. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  24625. }
  24626. /* We now have enough information to calculate our actual period size in frames. */
  24627. pDescriptorCapture->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorCapture, ss.rate, pConfig->performanceProfile);
  24628. attr = ma_device__pa_buffer_attr_new(pDescriptorCapture->periodSizeInFrames, pDescriptorCapture->periodCount, &ss);
  24629. 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);
  24630. pDevice->pulse.pStreamCapture = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNameCapture, &ss, &cmap);
  24631. if (pDevice->pulse.pStreamCapture == NULL) {
  24632. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio capture stream.\n");
  24633. result = MA_ERROR;
  24634. goto on_error0;
  24635. }
  24636. /* The callback needs to be set before connecting the stream. */
  24637. ((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);
  24638. /* State callback for checking when the device has been corked. */
  24639. ((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);
  24640. /* Rerouting notification. */
  24641. ((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);
  24642. /* Connect after we've got all of our internal state set up. */
  24643. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
  24644. if (devCapture != NULL) {
  24645. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  24646. }
  24647. error = ((ma_pa_stream_connect_record_proc)pDevice->pContext->pulse.pa_stream_connect_record)((ma_pa_stream*)pDevice->pulse.pStreamCapture, devCapture, &attr, streamFlags);
  24648. if (error != MA_PA_OK) {
  24649. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio capture stream.");
  24650. result = ma_result_from_pulse(error);
  24651. goto on_error1;
  24652. }
  24653. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24654. if (result != MA_SUCCESS) {
  24655. goto on_error2;
  24656. }
  24657. /* Internal format. */
  24658. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24659. if (pActualSS != NULL) {
  24660. ss = *pActualSS;
  24661. 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);
  24662. } else {
  24663. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve capture sample spec.\n");
  24664. }
  24665. pDescriptorCapture->format = ma_format_from_pulse(ss.format);
  24666. pDescriptorCapture->channels = ss.channels;
  24667. pDescriptorCapture->sampleRate = ss.rate;
  24668. if (pDescriptorCapture->format == ma_format_unknown || pDescriptorCapture->channels == 0 || pDescriptorCapture->sampleRate == 0) {
  24669. 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);
  24670. result = MA_ERROR;
  24671. goto on_error4;
  24672. }
  24673. /* Internal channel map. */
  24674. /*
  24675. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  24676. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  24677. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  24678. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  24679. fixed sooner than later. I might remove this hack later.
  24680. */
  24681. if (pDescriptorCapture->channels > 2) {
  24682. pActualCMap = ((ma_pa_stream_get_channel_map_proc)pDevice->pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24683. if (pActualCMap != NULL) {
  24684. cmap = *pActualCMap;
  24685. }
  24686. for (iChannel = 0; iChannel < pDescriptorCapture->channels; ++iChannel) {
  24687. pDescriptorCapture->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  24688. }
  24689. } else {
  24690. /* Hack for mono and stereo. */
  24691. if (pDescriptorCapture->channels == 1) {
  24692. pDescriptorCapture->channelMap[0] = MA_CHANNEL_MONO;
  24693. } else if (pDescriptorCapture->channels == 2) {
  24694. pDescriptorCapture->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  24695. pDescriptorCapture->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  24696. } else {
  24697. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  24698. }
  24699. }
  24700. /* Buffer. */
  24701. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24702. if (pActualAttr != NULL) {
  24703. attr = *pActualAttr;
  24704. }
  24705. if (attr.fragsize > 0) {
  24706. pDescriptorCapture->periodCount = ma_max(attr.maxlength / attr.fragsize, 1);
  24707. } else {
  24708. pDescriptorCapture->periodCount = 1;
  24709. }
  24710. pDescriptorCapture->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) / pDescriptorCapture->periodCount;
  24711. 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);
  24712. }
  24713. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  24714. result = ma_context_get_sink_info__pulse(pDevice->pContext, devPlayback, &sinkInfo);
  24715. if (result != MA_SUCCESS) {
  24716. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to retrieve sink info for playback device.\n");
  24717. goto on_error2;
  24718. }
  24719. ss = sinkInfo.sample_spec;
  24720. cmap = sinkInfo.channel_map;
  24721. /* Use the requested sample rate if one was specified. */
  24722. if (pDescriptorPlayback->sampleRate != 0) {
  24723. ss.rate = pDescriptorPlayback->sampleRate;
  24724. }
  24725. if (ma_format_from_pulse(ss.format) == ma_format_unknown) {
  24726. if (ma_is_little_endian()) {
  24727. ss.format = MA_PA_SAMPLE_FLOAT32LE;
  24728. } else {
  24729. ss.format = MA_PA_SAMPLE_FLOAT32BE;
  24730. }
  24731. 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");
  24732. }
  24733. if (ss.rate == 0) {
  24734. ss.rate = MA_DEFAULT_SAMPLE_RATE;
  24735. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.rate = 0. Defaulting to %d.\n", ss.rate);
  24736. }
  24737. if (ss.channels == 0) {
  24738. ss.channels = MA_DEFAULT_CHANNELS;
  24739. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] sample_spec.channels = 0. Defaulting to %d.\n", ss.channels);
  24740. }
  24741. /* We now have enough information to calculate the actual buffer size in frames. */
  24742. pDescriptorPlayback->periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__pulse(pDescriptorPlayback, ss.rate, pConfig->performanceProfile);
  24743. attr = ma_device__pa_buffer_attr_new(pDescriptorPlayback->periodSizeInFrames, pDescriptorPlayback->periodCount, &ss);
  24744. 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);
  24745. pDevice->pulse.pStreamPlayback = ma_device__pa_stream_new__pulse(pDevice, pConfig->pulse.pStreamNamePlayback, &ss, &cmap);
  24746. if (pDevice->pulse.pStreamPlayback == NULL) {
  24747. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to create PulseAudio playback stream.\n");
  24748. result = MA_ERROR;
  24749. goto on_error2;
  24750. }
  24751. /*
  24752. 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
  24753. device state of ma_device_state_uninitialized.
  24754. */
  24755. ((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);
  24756. /* State callback for checking when the device has been corked. */
  24757. ((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);
  24758. /* Rerouting notification. */
  24759. ((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);
  24760. /* Connect after we've got all of our internal state set up. */
  24761. streamFlags = MA_PA_STREAM_START_CORKED | MA_PA_STREAM_ADJUST_LATENCY | MA_PA_STREAM_FIX_FORMAT | MA_PA_STREAM_FIX_RATE | MA_PA_STREAM_FIX_CHANNELS;
  24762. if (devPlayback != NULL) {
  24763. streamFlags |= MA_PA_STREAM_DONT_MOVE;
  24764. }
  24765. 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);
  24766. if (error != MA_PA_OK) {
  24767. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to connect PulseAudio playback stream.");
  24768. result = ma_result_from_pulse(error);
  24769. goto on_error3;
  24770. }
  24771. result = ma_wait_for_pa_stream_to_connect__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, (ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24772. if (result != MA_SUCCESS) {
  24773. goto on_error3;
  24774. }
  24775. /* Internal format. */
  24776. pActualSS = ((ma_pa_stream_get_sample_spec_proc)pDevice->pContext->pulse.pa_stream_get_sample_spec)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24777. if (pActualSS != NULL) {
  24778. ss = *pActualSS;
  24779. 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);
  24780. } else {
  24781. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[PulseAudio] Failed to retrieve playback sample spec.\n");
  24782. }
  24783. pDescriptorPlayback->format = ma_format_from_pulse(ss.format);
  24784. pDescriptorPlayback->channels = ss.channels;
  24785. pDescriptorPlayback->sampleRate = ss.rate;
  24786. if (pDescriptorPlayback->format == ma_format_unknown || pDescriptorPlayback->channels == 0 || pDescriptorPlayback->sampleRate == 0) {
  24787. 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);
  24788. result = MA_ERROR;
  24789. goto on_error4;
  24790. }
  24791. /* Internal channel map. */
  24792. /*
  24793. Bug in PipeWire. There have been reports that PipeWire is returning AUX channels when reporting
  24794. the channel map. To somewhat workaround this, I'm hacking in a hard coded channel map for mono
  24795. and stereo. In this case it should be safe to assume mono = MONO and stereo = LEFT/RIGHT. For
  24796. all other channel counts we need to just put up with whatever PipeWire reports and hope it gets
  24797. fixed sooner than later. I might remove this hack later.
  24798. */
  24799. if (pDescriptorPlayback->channels > 2) {
  24800. pActualCMap = ((ma_pa_stream_get_channel_map_proc)pDevice->pContext->pulse.pa_stream_get_channel_map)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24801. if (pActualCMap != NULL) {
  24802. cmap = *pActualCMap;
  24803. }
  24804. for (iChannel = 0; iChannel < pDescriptorPlayback->channels; ++iChannel) {
  24805. pDescriptorPlayback->channelMap[iChannel] = ma_channel_position_from_pulse(cmap.map[iChannel]);
  24806. }
  24807. } else {
  24808. /* Hack for mono and stereo. */
  24809. if (pDescriptorPlayback->channels == 1) {
  24810. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_MONO;
  24811. } else if (pDescriptorPlayback->channels == 2) {
  24812. pDescriptorPlayback->channelMap[0] = MA_CHANNEL_FRONT_LEFT;
  24813. pDescriptorPlayback->channelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  24814. } else {
  24815. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  24816. }
  24817. }
  24818. /* Buffer. */
  24819. pActualAttr = ((ma_pa_stream_get_buffer_attr_proc)pDevice->pContext->pulse.pa_stream_get_buffer_attr)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24820. if (pActualAttr != NULL) {
  24821. attr = *pActualAttr;
  24822. }
  24823. if (attr.tlength > 0) {
  24824. pDescriptorPlayback->periodCount = ma_max(attr.maxlength / attr.tlength, 1);
  24825. } else {
  24826. pDescriptorPlayback->periodCount = 1;
  24827. }
  24828. pDescriptorPlayback->periodSizeInFrames = attr.maxlength / ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) / pDescriptorPlayback->periodCount;
  24829. 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);
  24830. }
  24831. /*
  24832. We need a ring buffer for handling duplex mode. We can use the main duplex ring buffer in the main
  24833. part of the ma_device struct. We cannot, however, depend on ma_device_init() initializing this for
  24834. us later on because that will only do it if it's a fully asynchronous backend - i.e. the
  24835. onDeviceDataLoop callback is NULL, which is not the case for PulseAudio.
  24836. */
  24837. if (pConfig->deviceType == ma_device_type_duplex) {
  24838. ma_format rbFormat = (format != ma_format_unknown) ? format : pDescriptorCapture->format;
  24839. ma_uint32 rbChannels = (channels > 0) ? channels : pDescriptorCapture->channels;
  24840. ma_uint32 rbSampleRate = (sampleRate > 0) ? sampleRate : pDescriptorCapture->sampleRate;
  24841. result = ma_duplex_rb_init(rbFormat, rbChannels, rbSampleRate, pDescriptorCapture->sampleRate, pDescriptorCapture->periodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  24842. if (result != MA_SUCCESS) {
  24843. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to initialize ring buffer. %s.\n", ma_result_description(result));
  24844. goto on_error4;
  24845. }
  24846. }
  24847. return MA_SUCCESS;
  24848. on_error4:
  24849. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  24850. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24851. }
  24852. on_error3:
  24853. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  24854. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamPlayback);
  24855. }
  24856. on_error2:
  24857. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  24858. ((ma_pa_stream_disconnect_proc)pDevice->pContext->pulse.pa_stream_disconnect)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24859. }
  24860. on_error1:
  24861. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  24862. ((ma_pa_stream_unref_proc)pDevice->pContext->pulse.pa_stream_unref)((ma_pa_stream*)pDevice->pulse.pStreamCapture);
  24863. }
  24864. on_error0:
  24865. return result;
  24866. }
  24867. static void ma_pulse_operation_complete_callback(ma_pa_stream* pStream, int success, void* pUserData)
  24868. {
  24869. ma_bool32* pIsSuccessful = (ma_bool32*)pUserData;
  24870. MA_ASSERT(pIsSuccessful != NULL);
  24871. *pIsSuccessful = (ma_bool32)success;
  24872. (void)pStream; /* Unused. */
  24873. }
  24874. static ma_result ma_device__cork_stream__pulse(ma_device* pDevice, ma_device_type deviceType, int cork)
  24875. {
  24876. ma_context* pContext = pDevice->pContext;
  24877. ma_bool32 wasSuccessful;
  24878. ma_pa_stream* pStream;
  24879. ma_pa_operation* pOP;
  24880. ma_result result;
  24881. /* This should not be called with a duplex device type. */
  24882. if (deviceType == ma_device_type_duplex) {
  24883. return MA_INVALID_ARGS;
  24884. }
  24885. wasSuccessful = MA_FALSE;
  24886. pStream = (ma_pa_stream*)((deviceType == ma_device_type_capture) ? pDevice->pulse.pStreamCapture : pDevice->pulse.pStreamPlayback);
  24887. MA_ASSERT(pStream != NULL);
  24888. pOP = ((ma_pa_stream_cork_proc)pContext->pulse.pa_stream_cork)(pStream, cork, ma_pulse_operation_complete_callback, &wasSuccessful);
  24889. if (pOP == NULL) {
  24890. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to cork PulseAudio stream.");
  24891. return MA_ERROR;
  24892. }
  24893. result = ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  24894. if (result != MA_SUCCESS) {
  24895. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] An error occurred while waiting for the PulseAudio stream to cork.");
  24896. return result;
  24897. }
  24898. if (!wasSuccessful) {
  24899. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[PulseAudio] Failed to %s PulseAudio stream.", (cork) ? "stop" : "start");
  24900. return MA_ERROR;
  24901. }
  24902. return MA_SUCCESS;
  24903. }
  24904. static ma_result ma_device_start__pulse(ma_device* pDevice)
  24905. {
  24906. ma_result result;
  24907. MA_ASSERT(pDevice != NULL);
  24908. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  24909. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 0);
  24910. if (result != MA_SUCCESS) {
  24911. return result;
  24912. }
  24913. }
  24914. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  24915. /*
  24916. We need to fill some data before uncorking. Not doing this will result in the write callback
  24917. never getting fired. We're not going to abort if writing fails because I still want the device
  24918. to get uncorked.
  24919. */
  24920. 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.*/
  24921. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 0);
  24922. if (result != MA_SUCCESS) {
  24923. return result;
  24924. }
  24925. }
  24926. return MA_SUCCESS;
  24927. }
  24928. static ma_result ma_device_stop__pulse(ma_device* pDevice)
  24929. {
  24930. ma_result result;
  24931. MA_ASSERT(pDevice != NULL);
  24932. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  24933. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_capture, 1);
  24934. if (result != MA_SUCCESS) {
  24935. return result;
  24936. }
  24937. }
  24938. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  24939. /*
  24940. Ideally we would drain the device here, but there's been cases where PulseAudio seems to be
  24941. broken on some systems to the point where no audio processing seems to happen. When this
  24942. happens, draining never completes and we get stuck here. For now I'm disabling draining of
  24943. the device so we don't just freeze the application.
  24944. */
  24945. #if 0
  24946. 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);
  24947. ma_wait_for_operation_and_unref__pulse(pDevice->pContext, pDevice->pulse.pMainLoop, pOP);
  24948. #endif
  24949. result = ma_device__cork_stream__pulse(pDevice, ma_device_type_playback, 1);
  24950. if (result != MA_SUCCESS) {
  24951. return result;
  24952. }
  24953. }
  24954. return MA_SUCCESS;
  24955. }
  24956. static ma_result ma_device_data_loop__pulse(ma_device* pDevice)
  24957. {
  24958. int resultPA;
  24959. MA_ASSERT(pDevice != NULL);
  24960. /* NOTE: Don't start the device here. It'll be done at a higher level. */
  24961. /*
  24962. All data is handled through callbacks. All we need to do is iterate over the main loop and let
  24963. the callbacks deal with it.
  24964. */
  24965. while (ma_device_get_state(pDevice) == ma_device_state_started) {
  24966. resultPA = ((ma_pa_mainloop_iterate_proc)pDevice->pContext->pulse.pa_mainloop_iterate)((ma_pa_mainloop*)pDevice->pulse.pMainLoop, 1, NULL);
  24967. if (resultPA < 0) {
  24968. break;
  24969. }
  24970. }
  24971. /* NOTE: Don't stop the device here. It'll be done at a higher level. */
  24972. return MA_SUCCESS;
  24973. }
  24974. static ma_result ma_device_data_loop_wakeup__pulse(ma_device* pDevice)
  24975. {
  24976. MA_ASSERT(pDevice != NULL);
  24977. ((ma_pa_mainloop_wakeup_proc)pDevice->pContext->pulse.pa_mainloop_wakeup)((ma_pa_mainloop*)pDevice->pulse.pMainLoop);
  24978. return MA_SUCCESS;
  24979. }
  24980. static ma_result ma_context_uninit__pulse(ma_context* pContext)
  24981. {
  24982. MA_ASSERT(pContext != NULL);
  24983. MA_ASSERT(pContext->backend == ma_backend_pulseaudio);
  24984. ((ma_pa_context_disconnect_proc)pContext->pulse.pa_context_disconnect)((ma_pa_context*)pContext->pulse.pPulseContext);
  24985. ((ma_pa_context_unref_proc)pContext->pulse.pa_context_unref)((ma_pa_context*)pContext->pulse.pPulseContext);
  24986. ((ma_pa_mainloop_free_proc)pContext->pulse.pa_mainloop_free)((ma_pa_mainloop*)pContext->pulse.pMainLoop);
  24987. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  24988. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  24989. #ifndef MA_NO_RUNTIME_LINKING
  24990. ma_dlclose(pContext, pContext->pulse.pulseSO);
  24991. #endif
  24992. return MA_SUCCESS;
  24993. }
  24994. static ma_result ma_context_init__pulse(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  24995. {
  24996. ma_result result;
  24997. #ifndef MA_NO_RUNTIME_LINKING
  24998. const char* libpulseNames[] = {
  24999. "libpulse.so",
  25000. "libpulse.so.0"
  25001. };
  25002. size_t i;
  25003. for (i = 0; i < ma_countof(libpulseNames); ++i) {
  25004. pContext->pulse.pulseSO = ma_dlopen(pContext, libpulseNames[i]);
  25005. if (pContext->pulse.pulseSO != NULL) {
  25006. break;
  25007. }
  25008. }
  25009. if (pContext->pulse.pulseSO == NULL) {
  25010. return MA_NO_BACKEND;
  25011. }
  25012. pContext->pulse.pa_mainloop_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_new");
  25013. pContext->pulse.pa_mainloop_free = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_free");
  25014. pContext->pulse.pa_mainloop_quit = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_quit");
  25015. pContext->pulse.pa_mainloop_get_api = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_get_api");
  25016. pContext->pulse.pa_mainloop_iterate = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_iterate");
  25017. pContext->pulse.pa_mainloop_wakeup = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_mainloop_wakeup");
  25018. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_new");
  25019. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_free");
  25020. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_start");
  25021. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_stop");
  25022. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_lock");
  25023. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_unlock");
  25024. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_wait");
  25025. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_signal");
  25026. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_accept");
  25027. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_get_retval");
  25028. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_get_api");
  25029. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_in_thread");
  25030. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_threaded_mainloop_set_name");
  25031. pContext->pulse.pa_context_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_new");
  25032. pContext->pulse.pa_context_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_unref");
  25033. pContext->pulse.pa_context_connect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_connect");
  25034. pContext->pulse.pa_context_disconnect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_disconnect");
  25035. pContext->pulse.pa_context_set_state_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_set_state_callback");
  25036. pContext->pulse.pa_context_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_state");
  25037. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_sink_info_list");
  25038. pContext->pulse.pa_context_get_source_info_list = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_source_info_list");
  25039. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_sink_info_by_name");
  25040. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_context_get_source_info_by_name");
  25041. pContext->pulse.pa_operation_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_operation_unref");
  25042. pContext->pulse.pa_operation_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_operation_get_state");
  25043. pContext->pulse.pa_channel_map_init_extend = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_init_extend");
  25044. pContext->pulse.pa_channel_map_valid = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_valid");
  25045. pContext->pulse.pa_channel_map_compatible = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_channel_map_compatible");
  25046. pContext->pulse.pa_stream_new = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_new");
  25047. pContext->pulse.pa_stream_unref = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_unref");
  25048. pContext->pulse.pa_stream_connect_playback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_connect_playback");
  25049. pContext->pulse.pa_stream_connect_record = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_connect_record");
  25050. pContext->pulse.pa_stream_disconnect = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_disconnect");
  25051. pContext->pulse.pa_stream_get_state = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_state");
  25052. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_sample_spec");
  25053. pContext->pulse.pa_stream_get_channel_map = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_channel_map");
  25054. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_buffer_attr");
  25055. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_buffer_attr");
  25056. pContext->pulse.pa_stream_get_device_name = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_get_device_name");
  25057. pContext->pulse.pa_stream_set_write_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_write_callback");
  25058. pContext->pulse.pa_stream_set_read_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_read_callback");
  25059. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_suspended_callback");
  25060. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_set_moved_callback");
  25061. pContext->pulse.pa_stream_is_suspended = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_is_suspended");
  25062. pContext->pulse.pa_stream_flush = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_flush");
  25063. pContext->pulse.pa_stream_drain = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_drain");
  25064. pContext->pulse.pa_stream_is_corked = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_is_corked");
  25065. pContext->pulse.pa_stream_cork = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_cork");
  25066. pContext->pulse.pa_stream_trigger = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_trigger");
  25067. pContext->pulse.pa_stream_begin_write = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_begin_write");
  25068. pContext->pulse.pa_stream_write = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_write");
  25069. pContext->pulse.pa_stream_peek = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_peek");
  25070. pContext->pulse.pa_stream_drop = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_drop");
  25071. pContext->pulse.pa_stream_writable_size = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_writable_size");
  25072. pContext->pulse.pa_stream_readable_size = (ma_proc)ma_dlsym(pContext, pContext->pulse.pulseSO, "pa_stream_readable_size");
  25073. #else
  25074. /* This strange assignment system is just for type safety. */
  25075. ma_pa_mainloop_new_proc _pa_mainloop_new = pa_mainloop_new;
  25076. ma_pa_mainloop_free_proc _pa_mainloop_free = pa_mainloop_free;
  25077. ma_pa_mainloop_quit_proc _pa_mainloop_quit = pa_mainloop_quit;
  25078. ma_pa_mainloop_get_api_proc _pa_mainloop_get_api = pa_mainloop_get_api;
  25079. ma_pa_mainloop_iterate_proc _pa_mainloop_iterate = pa_mainloop_iterate;
  25080. ma_pa_mainloop_wakeup_proc _pa_mainloop_wakeup = pa_mainloop_wakeup;
  25081. ma_pa_threaded_mainloop_new_proc _pa_threaded_mainloop_new = pa_threaded_mainloop_new;
  25082. ma_pa_threaded_mainloop_free_proc _pa_threaded_mainloop_free = pa_threaded_mainloop_free;
  25083. ma_pa_threaded_mainloop_start_proc _pa_threaded_mainloop_start = pa_threaded_mainloop_start;
  25084. ma_pa_threaded_mainloop_stop_proc _pa_threaded_mainloop_stop = pa_threaded_mainloop_stop;
  25085. ma_pa_threaded_mainloop_lock_proc _pa_threaded_mainloop_lock = pa_threaded_mainloop_lock;
  25086. ma_pa_threaded_mainloop_unlock_proc _pa_threaded_mainloop_unlock = pa_threaded_mainloop_unlock;
  25087. ma_pa_threaded_mainloop_wait_proc _pa_threaded_mainloop_wait = pa_threaded_mainloop_wait;
  25088. ma_pa_threaded_mainloop_signal_proc _pa_threaded_mainloop_signal = pa_threaded_mainloop_signal;
  25089. ma_pa_threaded_mainloop_accept_proc _pa_threaded_mainloop_accept = pa_threaded_mainloop_accept;
  25090. ma_pa_threaded_mainloop_get_retval_proc _pa_threaded_mainloop_get_retval = pa_threaded_mainloop_get_retval;
  25091. ma_pa_threaded_mainloop_get_api_proc _pa_threaded_mainloop_get_api = pa_threaded_mainloop_get_api;
  25092. ma_pa_threaded_mainloop_in_thread_proc _pa_threaded_mainloop_in_thread = pa_threaded_mainloop_in_thread;
  25093. ma_pa_threaded_mainloop_set_name_proc _pa_threaded_mainloop_set_name = pa_threaded_mainloop_set_name;
  25094. ma_pa_context_new_proc _pa_context_new = pa_context_new;
  25095. ma_pa_context_unref_proc _pa_context_unref = pa_context_unref;
  25096. ma_pa_context_connect_proc _pa_context_connect = pa_context_connect;
  25097. ma_pa_context_disconnect_proc _pa_context_disconnect = pa_context_disconnect;
  25098. ma_pa_context_set_state_callback_proc _pa_context_set_state_callback = pa_context_set_state_callback;
  25099. ma_pa_context_get_state_proc _pa_context_get_state = pa_context_get_state;
  25100. ma_pa_context_get_sink_info_list_proc _pa_context_get_sink_info_list = pa_context_get_sink_info_list;
  25101. ma_pa_context_get_source_info_list_proc _pa_context_get_source_info_list = pa_context_get_source_info_list;
  25102. ma_pa_context_get_sink_info_by_name_proc _pa_context_get_sink_info_by_name = pa_context_get_sink_info_by_name;
  25103. ma_pa_context_get_source_info_by_name_proc _pa_context_get_source_info_by_name= pa_context_get_source_info_by_name;
  25104. ma_pa_operation_unref_proc _pa_operation_unref = pa_operation_unref;
  25105. ma_pa_operation_get_state_proc _pa_operation_get_state = pa_operation_get_state;
  25106. ma_pa_channel_map_init_extend_proc _pa_channel_map_init_extend = pa_channel_map_init_extend;
  25107. ma_pa_channel_map_valid_proc _pa_channel_map_valid = pa_channel_map_valid;
  25108. ma_pa_channel_map_compatible_proc _pa_channel_map_compatible = pa_channel_map_compatible;
  25109. ma_pa_stream_new_proc _pa_stream_new = pa_stream_new;
  25110. ma_pa_stream_unref_proc _pa_stream_unref = pa_stream_unref;
  25111. ma_pa_stream_connect_playback_proc _pa_stream_connect_playback = pa_stream_connect_playback;
  25112. ma_pa_stream_connect_record_proc _pa_stream_connect_record = pa_stream_connect_record;
  25113. ma_pa_stream_disconnect_proc _pa_stream_disconnect = pa_stream_disconnect;
  25114. ma_pa_stream_get_state_proc _pa_stream_get_state = pa_stream_get_state;
  25115. ma_pa_stream_get_sample_spec_proc _pa_stream_get_sample_spec = pa_stream_get_sample_spec;
  25116. ma_pa_stream_get_channel_map_proc _pa_stream_get_channel_map = pa_stream_get_channel_map;
  25117. ma_pa_stream_get_buffer_attr_proc _pa_stream_get_buffer_attr = pa_stream_get_buffer_attr;
  25118. ma_pa_stream_set_buffer_attr_proc _pa_stream_set_buffer_attr = pa_stream_set_buffer_attr;
  25119. ma_pa_stream_get_device_name_proc _pa_stream_get_device_name = pa_stream_get_device_name;
  25120. ma_pa_stream_set_write_callback_proc _pa_stream_set_write_callback = pa_stream_set_write_callback;
  25121. ma_pa_stream_set_read_callback_proc _pa_stream_set_read_callback = pa_stream_set_read_callback;
  25122. ma_pa_stream_set_suspended_callback_proc _pa_stream_set_suspended_callback = pa_stream_set_suspended_callback;
  25123. ma_pa_stream_set_moved_callback_proc _pa_stream_set_moved_callback = pa_stream_set_moved_callback;
  25124. ma_pa_stream_is_suspended_proc _pa_stream_is_suspended = pa_stream_is_suspended;
  25125. ma_pa_stream_flush_proc _pa_stream_flush = pa_stream_flush;
  25126. ma_pa_stream_drain_proc _pa_stream_drain = pa_stream_drain;
  25127. ma_pa_stream_is_corked_proc _pa_stream_is_corked = pa_stream_is_corked;
  25128. ma_pa_stream_cork_proc _pa_stream_cork = pa_stream_cork;
  25129. ma_pa_stream_trigger_proc _pa_stream_trigger = pa_stream_trigger;
  25130. ma_pa_stream_begin_write_proc _pa_stream_begin_write = pa_stream_begin_write;
  25131. ma_pa_stream_write_proc _pa_stream_write = pa_stream_write;
  25132. ma_pa_stream_peek_proc _pa_stream_peek = pa_stream_peek;
  25133. ma_pa_stream_drop_proc _pa_stream_drop = pa_stream_drop;
  25134. ma_pa_stream_writable_size_proc _pa_stream_writable_size = pa_stream_writable_size;
  25135. ma_pa_stream_readable_size_proc _pa_stream_readable_size = pa_stream_readable_size;
  25136. pContext->pulse.pa_mainloop_new = (ma_proc)_pa_mainloop_new;
  25137. pContext->pulse.pa_mainloop_free = (ma_proc)_pa_mainloop_free;
  25138. pContext->pulse.pa_mainloop_quit = (ma_proc)_pa_mainloop_quit;
  25139. pContext->pulse.pa_mainloop_get_api = (ma_proc)_pa_mainloop_get_api;
  25140. pContext->pulse.pa_mainloop_iterate = (ma_proc)_pa_mainloop_iterate;
  25141. pContext->pulse.pa_mainloop_wakeup = (ma_proc)_pa_mainloop_wakeup;
  25142. pContext->pulse.pa_threaded_mainloop_new = (ma_proc)_pa_threaded_mainloop_new;
  25143. pContext->pulse.pa_threaded_mainloop_free = (ma_proc)_pa_threaded_mainloop_free;
  25144. pContext->pulse.pa_threaded_mainloop_start = (ma_proc)_pa_threaded_mainloop_start;
  25145. pContext->pulse.pa_threaded_mainloop_stop = (ma_proc)_pa_threaded_mainloop_stop;
  25146. pContext->pulse.pa_threaded_mainloop_lock = (ma_proc)_pa_threaded_mainloop_lock;
  25147. pContext->pulse.pa_threaded_mainloop_unlock = (ma_proc)_pa_threaded_mainloop_unlock;
  25148. pContext->pulse.pa_threaded_mainloop_wait = (ma_proc)_pa_threaded_mainloop_wait;
  25149. pContext->pulse.pa_threaded_mainloop_signal = (ma_proc)_pa_threaded_mainloop_signal;
  25150. pContext->pulse.pa_threaded_mainloop_accept = (ma_proc)_pa_threaded_mainloop_accept;
  25151. pContext->pulse.pa_threaded_mainloop_get_retval = (ma_proc)_pa_threaded_mainloop_get_retval;
  25152. pContext->pulse.pa_threaded_mainloop_get_api = (ma_proc)_pa_threaded_mainloop_get_api;
  25153. pContext->pulse.pa_threaded_mainloop_in_thread = (ma_proc)_pa_threaded_mainloop_in_thread;
  25154. pContext->pulse.pa_threaded_mainloop_set_name = (ma_proc)_pa_threaded_mainloop_set_name;
  25155. pContext->pulse.pa_context_new = (ma_proc)_pa_context_new;
  25156. pContext->pulse.pa_context_unref = (ma_proc)_pa_context_unref;
  25157. pContext->pulse.pa_context_connect = (ma_proc)_pa_context_connect;
  25158. pContext->pulse.pa_context_disconnect = (ma_proc)_pa_context_disconnect;
  25159. pContext->pulse.pa_context_set_state_callback = (ma_proc)_pa_context_set_state_callback;
  25160. pContext->pulse.pa_context_get_state = (ma_proc)_pa_context_get_state;
  25161. pContext->pulse.pa_context_get_sink_info_list = (ma_proc)_pa_context_get_sink_info_list;
  25162. pContext->pulse.pa_context_get_source_info_list = (ma_proc)_pa_context_get_source_info_list;
  25163. pContext->pulse.pa_context_get_sink_info_by_name = (ma_proc)_pa_context_get_sink_info_by_name;
  25164. pContext->pulse.pa_context_get_source_info_by_name = (ma_proc)_pa_context_get_source_info_by_name;
  25165. pContext->pulse.pa_operation_unref = (ma_proc)_pa_operation_unref;
  25166. pContext->pulse.pa_operation_get_state = (ma_proc)_pa_operation_get_state;
  25167. pContext->pulse.pa_channel_map_init_extend = (ma_proc)_pa_channel_map_init_extend;
  25168. pContext->pulse.pa_channel_map_valid = (ma_proc)_pa_channel_map_valid;
  25169. pContext->pulse.pa_channel_map_compatible = (ma_proc)_pa_channel_map_compatible;
  25170. pContext->pulse.pa_stream_new = (ma_proc)_pa_stream_new;
  25171. pContext->pulse.pa_stream_unref = (ma_proc)_pa_stream_unref;
  25172. pContext->pulse.pa_stream_connect_playback = (ma_proc)_pa_stream_connect_playback;
  25173. pContext->pulse.pa_stream_connect_record = (ma_proc)_pa_stream_connect_record;
  25174. pContext->pulse.pa_stream_disconnect = (ma_proc)_pa_stream_disconnect;
  25175. pContext->pulse.pa_stream_get_state = (ma_proc)_pa_stream_get_state;
  25176. pContext->pulse.pa_stream_get_sample_spec = (ma_proc)_pa_stream_get_sample_spec;
  25177. pContext->pulse.pa_stream_get_channel_map = (ma_proc)_pa_stream_get_channel_map;
  25178. pContext->pulse.pa_stream_get_buffer_attr = (ma_proc)_pa_stream_get_buffer_attr;
  25179. pContext->pulse.pa_stream_set_buffer_attr = (ma_proc)_pa_stream_set_buffer_attr;
  25180. pContext->pulse.pa_stream_get_device_name = (ma_proc)_pa_stream_get_device_name;
  25181. pContext->pulse.pa_stream_set_write_callback = (ma_proc)_pa_stream_set_write_callback;
  25182. pContext->pulse.pa_stream_set_read_callback = (ma_proc)_pa_stream_set_read_callback;
  25183. pContext->pulse.pa_stream_set_suspended_callback = (ma_proc)_pa_stream_set_suspended_callback;
  25184. pContext->pulse.pa_stream_set_moved_callback = (ma_proc)_pa_stream_set_moved_callback;
  25185. pContext->pulse.pa_stream_is_suspended = (ma_proc)_pa_stream_is_suspended;
  25186. pContext->pulse.pa_stream_flush = (ma_proc)_pa_stream_flush;
  25187. pContext->pulse.pa_stream_drain = (ma_proc)_pa_stream_drain;
  25188. pContext->pulse.pa_stream_is_corked = (ma_proc)_pa_stream_is_corked;
  25189. pContext->pulse.pa_stream_cork = (ma_proc)_pa_stream_cork;
  25190. pContext->pulse.pa_stream_trigger = (ma_proc)_pa_stream_trigger;
  25191. pContext->pulse.pa_stream_begin_write = (ma_proc)_pa_stream_begin_write;
  25192. pContext->pulse.pa_stream_write = (ma_proc)_pa_stream_write;
  25193. pContext->pulse.pa_stream_peek = (ma_proc)_pa_stream_peek;
  25194. pContext->pulse.pa_stream_drop = (ma_proc)_pa_stream_drop;
  25195. pContext->pulse.pa_stream_writable_size = (ma_proc)_pa_stream_writable_size;
  25196. pContext->pulse.pa_stream_readable_size = (ma_proc)_pa_stream_readable_size;
  25197. #endif
  25198. /* We need to make a copy of the application and server names so we can pass them to the pa_context of each device. */
  25199. pContext->pulse.pApplicationName = ma_copy_string(pConfig->pulse.pApplicationName, &pContext->allocationCallbacks);
  25200. if (pContext->pulse.pApplicationName == NULL && pConfig->pulse.pApplicationName != NULL) {
  25201. return MA_OUT_OF_MEMORY;
  25202. }
  25203. pContext->pulse.pServerName = ma_copy_string(pConfig->pulse.pServerName, &pContext->allocationCallbacks);
  25204. if (pContext->pulse.pServerName == NULL && pConfig->pulse.pServerName != NULL) {
  25205. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  25206. return MA_OUT_OF_MEMORY;
  25207. }
  25208. 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);
  25209. if (result != MA_SUCCESS) {
  25210. ma_free(pContext->pulse.pServerName, &pContext->allocationCallbacks);
  25211. ma_free(pContext->pulse.pApplicationName, &pContext->allocationCallbacks);
  25212. #ifndef MA_NO_RUNTIME_LINKING
  25213. ma_dlclose(pContext, pContext->pulse.pulseSO);
  25214. #endif
  25215. return result;
  25216. }
  25217. /* With pa_mainloop we run a synchronous backend, but we implement our own main loop. */
  25218. pCallbacks->onContextInit = ma_context_init__pulse;
  25219. pCallbacks->onContextUninit = ma_context_uninit__pulse;
  25220. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__pulse;
  25221. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__pulse;
  25222. pCallbacks->onDeviceInit = ma_device_init__pulse;
  25223. pCallbacks->onDeviceUninit = ma_device_uninit__pulse;
  25224. pCallbacks->onDeviceStart = ma_device_start__pulse;
  25225. pCallbacks->onDeviceStop = ma_device_stop__pulse;
  25226. pCallbacks->onDeviceRead = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  25227. pCallbacks->onDeviceWrite = NULL; /* Not used because we're implementing onDeviceDataLoop. */
  25228. pCallbacks->onDeviceDataLoop = ma_device_data_loop__pulse;
  25229. pCallbacks->onDeviceDataLoopWakeup = ma_device_data_loop_wakeup__pulse;
  25230. return MA_SUCCESS;
  25231. }
  25232. #endif
  25233. /******************************************************************************
  25234. JACK Backend
  25235. ******************************************************************************/
  25236. #ifdef MA_HAS_JACK
  25237. /* It is assumed jack.h is available when compile-time linking is being used. */
  25238. #ifdef MA_NO_RUNTIME_LINKING
  25239. #include <jack/jack.h>
  25240. typedef jack_nframes_t ma_jack_nframes_t;
  25241. typedef jack_options_t ma_jack_options_t;
  25242. typedef jack_status_t ma_jack_status_t;
  25243. typedef jack_client_t ma_jack_client_t;
  25244. typedef jack_port_t ma_jack_port_t;
  25245. typedef JackProcessCallback ma_JackProcessCallback;
  25246. typedef JackBufferSizeCallback ma_JackBufferSizeCallback;
  25247. typedef JackShutdownCallback ma_JackShutdownCallback;
  25248. #define MA_JACK_DEFAULT_AUDIO_TYPE JACK_DEFAULT_AUDIO_TYPE
  25249. #define ma_JackNoStartServer JackNoStartServer
  25250. #define ma_JackPortIsInput JackPortIsInput
  25251. #define ma_JackPortIsOutput JackPortIsOutput
  25252. #define ma_JackPortIsPhysical JackPortIsPhysical
  25253. #else
  25254. typedef ma_uint32 ma_jack_nframes_t;
  25255. typedef int ma_jack_options_t;
  25256. typedef int ma_jack_status_t;
  25257. typedef struct ma_jack_client_t ma_jack_client_t;
  25258. typedef struct ma_jack_port_t ma_jack_port_t;
  25259. typedef int (* ma_JackProcessCallback) (ma_jack_nframes_t nframes, void* arg);
  25260. typedef int (* ma_JackBufferSizeCallback)(ma_jack_nframes_t nframes, void* arg);
  25261. typedef void (* ma_JackShutdownCallback) (void* arg);
  25262. #define MA_JACK_DEFAULT_AUDIO_TYPE "32 bit float mono audio"
  25263. #define ma_JackNoStartServer 1
  25264. #define ma_JackPortIsInput 1
  25265. #define ma_JackPortIsOutput 2
  25266. #define ma_JackPortIsPhysical 4
  25267. #endif
  25268. typedef ma_jack_client_t* (* ma_jack_client_open_proc) (const char* client_name, ma_jack_options_t options, ma_jack_status_t* status, ...);
  25269. typedef int (* ma_jack_client_close_proc) (ma_jack_client_t* client);
  25270. typedef int (* ma_jack_client_name_size_proc) (void);
  25271. typedef int (* ma_jack_set_process_callback_proc) (ma_jack_client_t* client, ma_JackProcessCallback process_callback, void* arg);
  25272. typedef int (* ma_jack_set_buffer_size_callback_proc)(ma_jack_client_t* client, ma_JackBufferSizeCallback bufsize_callback, void* arg);
  25273. typedef void (* ma_jack_on_shutdown_proc) (ma_jack_client_t* client, ma_JackShutdownCallback function, void* arg);
  25274. typedef ma_jack_nframes_t (* ma_jack_get_sample_rate_proc) (ma_jack_client_t* client);
  25275. typedef ma_jack_nframes_t (* ma_jack_get_buffer_size_proc) (ma_jack_client_t* client);
  25276. 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);
  25277. typedef int (* ma_jack_activate_proc) (ma_jack_client_t* client);
  25278. typedef int (* ma_jack_deactivate_proc) (ma_jack_client_t* client);
  25279. typedef int (* ma_jack_connect_proc) (ma_jack_client_t* client, const char* source_port, const char* destination_port);
  25280. 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);
  25281. typedef const char* (* ma_jack_port_name_proc) (const ma_jack_port_t* port);
  25282. typedef void* (* ma_jack_port_get_buffer_proc) (ma_jack_port_t* port, ma_jack_nframes_t nframes);
  25283. typedef void (* ma_jack_free_proc) (void* ptr);
  25284. static ma_result ma_context_open_client__jack(ma_context* pContext, ma_jack_client_t** ppClient)
  25285. {
  25286. size_t maxClientNameSize;
  25287. char clientName[256];
  25288. ma_jack_status_t status;
  25289. ma_jack_client_t* pClient;
  25290. MA_ASSERT(pContext != NULL);
  25291. MA_ASSERT(ppClient != NULL);
  25292. if (ppClient) {
  25293. *ppClient = NULL;
  25294. }
  25295. maxClientNameSize = ((ma_jack_client_name_size_proc)pContext->jack.jack_client_name_size)(); /* Includes null terminator. */
  25296. ma_strncpy_s(clientName, ma_min(sizeof(clientName), maxClientNameSize), (pContext->jack.pClientName != NULL) ? pContext->jack.pClientName : "miniaudio", (size_t)-1);
  25297. pClient = ((ma_jack_client_open_proc)pContext->jack.jack_client_open)(clientName, (pContext->jack.tryStartServer) ? 0 : ma_JackNoStartServer, &status, NULL);
  25298. if (pClient == NULL) {
  25299. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25300. }
  25301. if (ppClient) {
  25302. *ppClient = pClient;
  25303. }
  25304. return MA_SUCCESS;
  25305. }
  25306. static ma_result ma_context_enumerate_devices__jack(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  25307. {
  25308. ma_bool32 cbResult = MA_TRUE;
  25309. MA_ASSERT(pContext != NULL);
  25310. MA_ASSERT(callback != NULL);
  25311. /* Playback. */
  25312. if (cbResult) {
  25313. ma_device_info deviceInfo;
  25314. MA_ZERO_OBJECT(&deviceInfo);
  25315. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  25316. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  25317. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  25318. }
  25319. /* Capture. */
  25320. if (cbResult) {
  25321. ma_device_info deviceInfo;
  25322. MA_ZERO_OBJECT(&deviceInfo);
  25323. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  25324. deviceInfo.isDefault = MA_TRUE; /* JACK only uses default devices. */
  25325. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  25326. }
  25327. (void)cbResult; /* For silencing a static analysis warning. */
  25328. return MA_SUCCESS;
  25329. }
  25330. 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)
  25331. {
  25332. ma_jack_client_t* pClient;
  25333. ma_result result;
  25334. const char** ppPorts;
  25335. MA_ASSERT(pContext != NULL);
  25336. if (pDeviceID != NULL && pDeviceID->jack != 0) {
  25337. return MA_NO_DEVICE; /* Don't know the device. */
  25338. }
  25339. /* Name / Description */
  25340. if (deviceType == ma_device_type_playback) {
  25341. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  25342. } else {
  25343. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  25344. }
  25345. /* Jack only uses default devices. */
  25346. pDeviceInfo->isDefault = MA_TRUE;
  25347. /* Jack only supports f32 and has a specific channel count and sample rate. */
  25348. pDeviceInfo->nativeDataFormats[0].format = ma_format_f32;
  25349. /* The channel count and sample rate can only be determined by opening the device. */
  25350. result = ma_context_open_client__jack(pContext, &pClient);
  25351. if (result != MA_SUCCESS) {
  25352. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  25353. return result;
  25354. }
  25355. pDeviceInfo->nativeDataFormats[0].sampleRate = ((ma_jack_get_sample_rate_proc)pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pClient);
  25356. pDeviceInfo->nativeDataFormats[0].channels = 0;
  25357. 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));
  25358. if (ppPorts == NULL) {
  25359. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  25360. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  25361. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25362. }
  25363. while (ppPorts[pDeviceInfo->nativeDataFormats[0].channels] != NULL) {
  25364. pDeviceInfo->nativeDataFormats[0].channels += 1;
  25365. }
  25366. pDeviceInfo->nativeDataFormats[0].flags = 0;
  25367. pDeviceInfo->nativeDataFormatCount = 1;
  25368. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppPorts);
  25369. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pClient);
  25370. (void)pContext;
  25371. return MA_SUCCESS;
  25372. }
  25373. static ma_result ma_device_uninit__jack(ma_device* pDevice)
  25374. {
  25375. ma_context* pContext;
  25376. MA_ASSERT(pDevice != NULL);
  25377. pContext = pDevice->pContext;
  25378. MA_ASSERT(pContext != NULL);
  25379. if (pDevice->jack.pClient != NULL) {
  25380. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDevice->jack.pClient);
  25381. }
  25382. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25383. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  25384. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  25385. }
  25386. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25387. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  25388. ma_free(pDevice->jack.ppPortsPlayback, &pDevice->pContext->allocationCallbacks);
  25389. }
  25390. return MA_SUCCESS;
  25391. }
  25392. static void ma_device__jack_shutdown_callback(void* pUserData)
  25393. {
  25394. /* JACK died. Stop the device. */
  25395. ma_device* pDevice = (ma_device*)pUserData;
  25396. MA_ASSERT(pDevice != NULL);
  25397. ma_device_stop(pDevice);
  25398. }
  25399. static int ma_device__jack_buffer_size_callback(ma_jack_nframes_t frameCount, void* pUserData)
  25400. {
  25401. ma_device* pDevice = (ma_device*)pUserData;
  25402. MA_ASSERT(pDevice != NULL);
  25403. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25404. size_t newBufferSize = frameCount * (pDevice->capture.internalChannels * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  25405. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  25406. if (pNewBuffer == NULL) {
  25407. return MA_OUT_OF_MEMORY;
  25408. }
  25409. ma_free(pDevice->jack.pIntermediaryBufferCapture, &pDevice->pContext->allocationCallbacks);
  25410. pDevice->jack.pIntermediaryBufferCapture = pNewBuffer;
  25411. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  25412. }
  25413. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25414. size_t newBufferSize = frameCount * (pDevice->playback.internalChannels * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  25415. float* pNewBuffer = (float*)ma_calloc(newBufferSize, &pDevice->pContext->allocationCallbacks);
  25416. if (pNewBuffer == NULL) {
  25417. return MA_OUT_OF_MEMORY;
  25418. }
  25419. ma_free(pDevice->jack.pIntermediaryBufferPlayback, &pDevice->pContext->allocationCallbacks);
  25420. pDevice->jack.pIntermediaryBufferPlayback = pNewBuffer;
  25421. pDevice->playback.internalPeriodSizeInFrames = frameCount;
  25422. }
  25423. return 0;
  25424. }
  25425. static int ma_device__jack_process_callback(ma_jack_nframes_t frameCount, void* pUserData)
  25426. {
  25427. ma_device* pDevice;
  25428. ma_context* pContext;
  25429. ma_uint32 iChannel;
  25430. pDevice = (ma_device*)pUserData;
  25431. MA_ASSERT(pDevice != NULL);
  25432. pContext = pDevice->pContext;
  25433. MA_ASSERT(pContext != NULL);
  25434. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25435. /* Channels need to be interleaved. */
  25436. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  25437. 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);
  25438. if (pSrc != NULL) {
  25439. float* pDst = pDevice->jack.pIntermediaryBufferCapture + iChannel;
  25440. ma_jack_nframes_t iFrame;
  25441. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  25442. *pDst = *pSrc;
  25443. pDst += pDevice->capture.internalChannels;
  25444. pSrc += 1;
  25445. }
  25446. }
  25447. }
  25448. ma_device_handle_backend_data_callback(pDevice, NULL, pDevice->jack.pIntermediaryBufferCapture, frameCount);
  25449. }
  25450. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25451. ma_device_handle_backend_data_callback(pDevice, pDevice->jack.pIntermediaryBufferPlayback, NULL, frameCount);
  25452. /* Channels need to be deinterleaved. */
  25453. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  25454. float* pDst = (float*)((ma_jack_port_get_buffer_proc)pContext->jack.jack_port_get_buffer)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[iChannel], frameCount);
  25455. if (pDst != NULL) {
  25456. const float* pSrc = pDevice->jack.pIntermediaryBufferPlayback + iChannel;
  25457. ma_jack_nframes_t iFrame;
  25458. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  25459. *pDst = *pSrc;
  25460. pDst += 1;
  25461. pSrc += pDevice->playback.internalChannels;
  25462. }
  25463. }
  25464. }
  25465. }
  25466. return 0;
  25467. }
  25468. static ma_result ma_device_init__jack(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  25469. {
  25470. ma_result result;
  25471. ma_uint32 periodSizeInFrames;
  25472. MA_ASSERT(pConfig != NULL);
  25473. MA_ASSERT(pDevice != NULL);
  25474. if (pConfig->deviceType == ma_device_type_loopback) {
  25475. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Loopback mode not supported.");
  25476. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  25477. }
  25478. /* Only supporting default devices with JACK. */
  25479. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->pDeviceID != NULL && pDescriptorPlayback->pDeviceID->jack != 0) ||
  25480. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->pDeviceID != NULL && pDescriptorCapture->pDeviceID->jack != 0)) {
  25481. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Only default devices are supported.");
  25482. return MA_NO_DEVICE;
  25483. }
  25484. /* No exclusive mode with the JACK backend. */
  25485. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  25486. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  25487. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Exclusive mode not supported.");
  25488. return MA_SHARE_MODE_NOT_SUPPORTED;
  25489. }
  25490. /* Open the client. */
  25491. result = ma_context_open_client__jack(pDevice->pContext, (ma_jack_client_t**)&pDevice->jack.pClient);
  25492. if (result != MA_SUCCESS) {
  25493. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to open client.");
  25494. return result;
  25495. }
  25496. /* Callbacks. */
  25497. 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) {
  25498. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set process callback.");
  25499. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25500. }
  25501. 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) {
  25502. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to set buffer size callback.");
  25503. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25504. }
  25505. ((ma_jack_on_shutdown_proc)pDevice->pContext->jack.jack_on_shutdown)((ma_jack_client_t*)pDevice->jack.pClient, ma_device__jack_shutdown_callback, pDevice);
  25506. /* The buffer size in frames can change. */
  25507. periodSizeInFrames = ((ma_jack_get_buffer_size_proc)pDevice->pContext->jack.jack_get_buffer_size)((ma_jack_client_t*)pDevice->jack.pClient);
  25508. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  25509. ma_uint32 iPort;
  25510. const char** ppPorts;
  25511. pDescriptorCapture->format = ma_format_f32;
  25512. pDescriptorCapture->channels = 0;
  25513. pDescriptorCapture->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  25514. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap), pDescriptorCapture->channels);
  25515. 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);
  25516. if (ppPorts == NULL) {
  25517. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  25518. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25519. }
  25520. /* Need to count the number of ports first so we can allocate some memory. */
  25521. while (ppPorts[pDescriptorCapture->channels] != NULL) {
  25522. pDescriptorCapture->channels += 1;
  25523. }
  25524. pDevice->jack.ppPortsCapture = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsCapture) * pDescriptorCapture->channels, &pDevice->pContext->allocationCallbacks);
  25525. if (pDevice->jack.ppPortsCapture == NULL) {
  25526. return MA_OUT_OF_MEMORY;
  25527. }
  25528. for (iPort = 0; iPort < pDescriptorCapture->channels; iPort += 1) {
  25529. char name[64];
  25530. ma_strcpy_s(name, sizeof(name), "capture");
  25531. ma_itoa_s((int)iPort, name+7, sizeof(name)-7, 10); /* 7 = length of "capture" */
  25532. 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);
  25533. if (pDevice->jack.ppPortsCapture[iPort] == NULL) {
  25534. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  25535. ma_device_uninit__jack(pDevice);
  25536. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  25537. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25538. }
  25539. }
  25540. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  25541. pDescriptorCapture->periodSizeInFrames = periodSizeInFrames;
  25542. pDescriptorCapture->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  25543. pDevice->jack.pIntermediaryBufferCapture = (float*)ma_calloc(pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels), &pDevice->pContext->allocationCallbacks);
  25544. if (pDevice->jack.pIntermediaryBufferCapture == NULL) {
  25545. ma_device_uninit__jack(pDevice);
  25546. return MA_OUT_OF_MEMORY;
  25547. }
  25548. }
  25549. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  25550. ma_uint32 iPort;
  25551. const char** ppPorts;
  25552. pDescriptorPlayback->format = ma_format_f32;
  25553. pDescriptorPlayback->channels = 0;
  25554. pDescriptorPlayback->sampleRate = ((ma_jack_get_sample_rate_proc)pDevice->pContext->jack.jack_get_sample_rate)((ma_jack_client_t*)pDevice->jack.pClient);
  25555. ma_channel_map_init_standard(ma_standard_channel_map_alsa, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap), pDescriptorPlayback->channels);
  25556. 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);
  25557. if (ppPorts == NULL) {
  25558. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to query physical ports.");
  25559. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25560. }
  25561. /* Need to count the number of ports first so we can allocate some memory. */
  25562. while (ppPorts[pDescriptorPlayback->channels] != NULL) {
  25563. pDescriptorPlayback->channels += 1;
  25564. }
  25565. pDevice->jack.ppPortsPlayback = (ma_ptr*)ma_malloc(sizeof(*pDevice->jack.ppPortsPlayback) * pDescriptorPlayback->channels, &pDevice->pContext->allocationCallbacks);
  25566. if (pDevice->jack.ppPortsPlayback == NULL) {
  25567. ma_free(pDevice->jack.ppPortsCapture, &pDevice->pContext->allocationCallbacks);
  25568. return MA_OUT_OF_MEMORY;
  25569. }
  25570. for (iPort = 0; iPort < pDescriptorPlayback->channels; iPort += 1) {
  25571. char name[64];
  25572. ma_strcpy_s(name, sizeof(name), "playback");
  25573. ma_itoa_s((int)iPort, name+8, sizeof(name)-8, 10); /* 8 = length of "playback" */
  25574. 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);
  25575. if (pDevice->jack.ppPortsPlayback[iPort] == NULL) {
  25576. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  25577. ma_device_uninit__jack(pDevice);
  25578. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to register ports.");
  25579. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  25580. }
  25581. }
  25582. ((ma_jack_free_proc)pDevice->pContext->jack.jack_free)((void*)ppPorts);
  25583. pDescriptorPlayback->periodSizeInFrames = periodSizeInFrames;
  25584. pDescriptorPlayback->periodCount = 1; /* There's no notion of a period in JACK. Just set to 1. */
  25585. pDevice->jack.pIntermediaryBufferPlayback = (float*)ma_calloc(pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels), &pDevice->pContext->allocationCallbacks);
  25586. if (pDevice->jack.pIntermediaryBufferPlayback == NULL) {
  25587. ma_device_uninit__jack(pDevice);
  25588. return MA_OUT_OF_MEMORY;
  25589. }
  25590. }
  25591. return MA_SUCCESS;
  25592. }
  25593. static ma_result ma_device_start__jack(ma_device* pDevice)
  25594. {
  25595. ma_context* pContext = pDevice->pContext;
  25596. int resultJACK;
  25597. size_t i;
  25598. resultJACK = ((ma_jack_activate_proc)pContext->jack.jack_activate)((ma_jack_client_t*)pDevice->jack.pClient);
  25599. if (resultJACK != 0) {
  25600. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to activate the JACK client.");
  25601. return MA_FAILED_TO_START_BACKEND_DEVICE;
  25602. }
  25603. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  25604. 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);
  25605. if (ppServerPorts == NULL) {
  25606. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  25607. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  25608. return MA_ERROR;
  25609. }
  25610. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  25611. const char* pServerPort = ppServerPorts[i];
  25612. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsCapture[i]);
  25613. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pServerPort, pClientPort);
  25614. if (resultJACK != 0) {
  25615. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  25616. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  25617. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  25618. return MA_ERROR;
  25619. }
  25620. }
  25621. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  25622. }
  25623. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  25624. 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);
  25625. if (ppServerPorts == NULL) {
  25626. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  25627. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to retrieve physical ports.");
  25628. return MA_ERROR;
  25629. }
  25630. for (i = 0; ppServerPorts[i] != NULL; ++i) {
  25631. const char* pServerPort = ppServerPorts[i];
  25632. const char* pClientPort = ((ma_jack_port_name_proc)pContext->jack.jack_port_name)((ma_jack_port_t*)pDevice->jack.ppPortsPlayback[i]);
  25633. resultJACK = ((ma_jack_connect_proc)pContext->jack.jack_connect)((ma_jack_client_t*)pDevice->jack.pClient, pClientPort, pServerPort);
  25634. if (resultJACK != 0) {
  25635. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  25636. ((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient);
  25637. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] Failed to connect ports.");
  25638. return MA_ERROR;
  25639. }
  25640. }
  25641. ((ma_jack_free_proc)pContext->jack.jack_free)((void*)ppServerPorts);
  25642. }
  25643. return MA_SUCCESS;
  25644. }
  25645. static ma_result ma_device_stop__jack(ma_device* pDevice)
  25646. {
  25647. ma_context* pContext = pDevice->pContext;
  25648. if (((ma_jack_deactivate_proc)pContext->jack.jack_deactivate)((ma_jack_client_t*)pDevice->jack.pClient) != 0) {
  25649. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[JACK] An error occurred when deactivating the JACK client.");
  25650. return MA_ERROR;
  25651. }
  25652. ma_device__on_notification_stopped(pDevice);
  25653. return MA_SUCCESS;
  25654. }
  25655. static ma_result ma_context_uninit__jack(ma_context* pContext)
  25656. {
  25657. MA_ASSERT(pContext != NULL);
  25658. MA_ASSERT(pContext->backend == ma_backend_jack);
  25659. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  25660. pContext->jack.pClientName = NULL;
  25661. #ifndef MA_NO_RUNTIME_LINKING
  25662. ma_dlclose(pContext, pContext->jack.jackSO);
  25663. #endif
  25664. return MA_SUCCESS;
  25665. }
  25666. static ma_result ma_context_init__jack(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  25667. {
  25668. #ifndef MA_NO_RUNTIME_LINKING
  25669. const char* libjackNames[] = {
  25670. #ifdef MA_WIN32
  25671. "libjack.dll",
  25672. "libjack64.dll"
  25673. #else
  25674. "libjack.so",
  25675. "libjack.so.0"
  25676. #endif
  25677. };
  25678. size_t i;
  25679. for (i = 0; i < ma_countof(libjackNames); ++i) {
  25680. pContext->jack.jackSO = ma_dlopen(pContext, libjackNames[i]);
  25681. if (pContext->jack.jackSO != NULL) {
  25682. break;
  25683. }
  25684. }
  25685. if (pContext->jack.jackSO == NULL) {
  25686. return MA_NO_BACKEND;
  25687. }
  25688. pContext->jack.jack_client_open = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_open");
  25689. pContext->jack.jack_client_close = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_close");
  25690. pContext->jack.jack_client_name_size = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_client_name_size");
  25691. pContext->jack.jack_set_process_callback = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_set_process_callback");
  25692. pContext->jack.jack_set_buffer_size_callback = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_set_buffer_size_callback");
  25693. pContext->jack.jack_on_shutdown = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_on_shutdown");
  25694. pContext->jack.jack_get_sample_rate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_sample_rate");
  25695. pContext->jack.jack_get_buffer_size = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_buffer_size");
  25696. pContext->jack.jack_get_ports = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_get_ports");
  25697. pContext->jack.jack_activate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_activate");
  25698. pContext->jack.jack_deactivate = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_deactivate");
  25699. pContext->jack.jack_connect = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_connect");
  25700. pContext->jack.jack_port_register = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_register");
  25701. pContext->jack.jack_port_name = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_name");
  25702. pContext->jack.jack_port_get_buffer = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_port_get_buffer");
  25703. pContext->jack.jack_free = (ma_proc)ma_dlsym(pContext, pContext->jack.jackSO, "jack_free");
  25704. #else
  25705. /*
  25706. This strange assignment system is here just to ensure type safety of miniaudio's function pointer
  25707. types. If anything differs slightly the compiler should throw a warning.
  25708. */
  25709. ma_jack_client_open_proc _jack_client_open = jack_client_open;
  25710. ma_jack_client_close_proc _jack_client_close = jack_client_close;
  25711. ma_jack_client_name_size_proc _jack_client_name_size = jack_client_name_size;
  25712. ma_jack_set_process_callback_proc _jack_set_process_callback = jack_set_process_callback;
  25713. ma_jack_set_buffer_size_callback_proc _jack_set_buffer_size_callback = jack_set_buffer_size_callback;
  25714. ma_jack_on_shutdown_proc _jack_on_shutdown = jack_on_shutdown;
  25715. ma_jack_get_sample_rate_proc _jack_get_sample_rate = jack_get_sample_rate;
  25716. ma_jack_get_buffer_size_proc _jack_get_buffer_size = jack_get_buffer_size;
  25717. ma_jack_get_ports_proc _jack_get_ports = jack_get_ports;
  25718. ma_jack_activate_proc _jack_activate = jack_activate;
  25719. ma_jack_deactivate_proc _jack_deactivate = jack_deactivate;
  25720. ma_jack_connect_proc _jack_connect = jack_connect;
  25721. ma_jack_port_register_proc _jack_port_register = jack_port_register;
  25722. ma_jack_port_name_proc _jack_port_name = jack_port_name;
  25723. ma_jack_port_get_buffer_proc _jack_port_get_buffer = jack_port_get_buffer;
  25724. ma_jack_free_proc _jack_free = jack_free;
  25725. pContext->jack.jack_client_open = (ma_proc)_jack_client_open;
  25726. pContext->jack.jack_client_close = (ma_proc)_jack_client_close;
  25727. pContext->jack.jack_client_name_size = (ma_proc)_jack_client_name_size;
  25728. pContext->jack.jack_set_process_callback = (ma_proc)_jack_set_process_callback;
  25729. pContext->jack.jack_set_buffer_size_callback = (ma_proc)_jack_set_buffer_size_callback;
  25730. pContext->jack.jack_on_shutdown = (ma_proc)_jack_on_shutdown;
  25731. pContext->jack.jack_get_sample_rate = (ma_proc)_jack_get_sample_rate;
  25732. pContext->jack.jack_get_buffer_size = (ma_proc)_jack_get_buffer_size;
  25733. pContext->jack.jack_get_ports = (ma_proc)_jack_get_ports;
  25734. pContext->jack.jack_activate = (ma_proc)_jack_activate;
  25735. pContext->jack.jack_deactivate = (ma_proc)_jack_deactivate;
  25736. pContext->jack.jack_connect = (ma_proc)_jack_connect;
  25737. pContext->jack.jack_port_register = (ma_proc)_jack_port_register;
  25738. pContext->jack.jack_port_name = (ma_proc)_jack_port_name;
  25739. pContext->jack.jack_port_get_buffer = (ma_proc)_jack_port_get_buffer;
  25740. pContext->jack.jack_free = (ma_proc)_jack_free;
  25741. #endif
  25742. if (pConfig->jack.pClientName != NULL) {
  25743. pContext->jack.pClientName = ma_copy_string(pConfig->jack.pClientName, &pContext->allocationCallbacks);
  25744. }
  25745. pContext->jack.tryStartServer = pConfig->jack.tryStartServer;
  25746. /*
  25747. 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
  25748. a temporary client.
  25749. */
  25750. {
  25751. ma_jack_client_t* pDummyClient;
  25752. ma_result result = ma_context_open_client__jack(pContext, &pDummyClient);
  25753. if (result != MA_SUCCESS) {
  25754. ma_free(pContext->jack.pClientName, &pContext->allocationCallbacks);
  25755. #ifndef MA_NO_RUNTIME_LINKING
  25756. ma_dlclose(pContext, pContext->jack.jackSO);
  25757. #endif
  25758. return MA_NO_BACKEND;
  25759. }
  25760. ((ma_jack_client_close_proc)pContext->jack.jack_client_close)((ma_jack_client_t*)pDummyClient);
  25761. }
  25762. pCallbacks->onContextInit = ma_context_init__jack;
  25763. pCallbacks->onContextUninit = ma_context_uninit__jack;
  25764. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__jack;
  25765. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__jack;
  25766. pCallbacks->onDeviceInit = ma_device_init__jack;
  25767. pCallbacks->onDeviceUninit = ma_device_uninit__jack;
  25768. pCallbacks->onDeviceStart = ma_device_start__jack;
  25769. pCallbacks->onDeviceStop = ma_device_stop__jack;
  25770. pCallbacks->onDeviceRead = NULL; /* Not used because JACK is asynchronous. */
  25771. pCallbacks->onDeviceWrite = NULL; /* Not used because JACK is asynchronous. */
  25772. pCallbacks->onDeviceDataLoop = NULL; /* Not used because JACK is asynchronous. */
  25773. return MA_SUCCESS;
  25774. }
  25775. #endif /* JACK */
  25776. /******************************************************************************
  25777. Core Audio Backend
  25778. References
  25779. ==========
  25780. - Technical Note TN2091: Device input using the HAL Output Audio Unit
  25781. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  25782. ******************************************************************************/
  25783. #ifdef MA_HAS_COREAUDIO
  25784. #include <TargetConditionals.h>
  25785. #if defined(TARGET_OS_IPHONE) && TARGET_OS_IPHONE == 1
  25786. #define MA_APPLE_MOBILE
  25787. #if defined(TARGET_OS_TV) && TARGET_OS_TV == 1
  25788. #define MA_APPLE_TV
  25789. #endif
  25790. #if defined(TARGET_OS_WATCH) && TARGET_OS_WATCH == 1
  25791. #define MA_APPLE_WATCH
  25792. #endif
  25793. #if __has_feature(objc_arc)
  25794. #define MA_BRIDGE_TRANSFER __bridge_transfer
  25795. #define MA_BRIDGE_RETAINED __bridge_retained
  25796. #else
  25797. #define MA_BRIDGE_TRANSFER
  25798. #define MA_BRIDGE_RETAINED
  25799. #endif
  25800. #else
  25801. #define MA_APPLE_DESKTOP
  25802. #endif
  25803. #if defined(MA_APPLE_DESKTOP)
  25804. #include <CoreAudio/CoreAudio.h>
  25805. #else
  25806. #include <AVFoundation/AVFoundation.h>
  25807. #endif
  25808. #include <AudioToolbox/AudioToolbox.h>
  25809. /* CoreFoundation */
  25810. typedef Boolean (* ma_CFStringGetCString_proc)(CFStringRef theString, char* buffer, CFIndex bufferSize, CFStringEncoding encoding);
  25811. typedef void (* ma_CFRelease_proc)(CFTypeRef cf);
  25812. /* CoreAudio */
  25813. #if defined(MA_APPLE_DESKTOP)
  25814. typedef OSStatus (* ma_AudioObjectGetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* ioDataSize, void* outData);
  25815. typedef OSStatus (* ma_AudioObjectGetPropertyDataSize_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32* outDataSize);
  25816. typedef OSStatus (* ma_AudioObjectSetPropertyData_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, UInt32 inQualifierDataSize, const void* inQualifierData, UInt32 inDataSize, const void* inData);
  25817. typedef OSStatus (* ma_AudioObjectAddPropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  25818. typedef OSStatus (* ma_AudioObjectRemovePropertyListener_proc)(AudioObjectID inObjectID, const AudioObjectPropertyAddress* inAddress, AudioObjectPropertyListenerProc inListener, void* inClientData);
  25819. #endif
  25820. /* AudioToolbox */
  25821. typedef AudioComponent (* ma_AudioComponentFindNext_proc)(AudioComponent inComponent, const AudioComponentDescription* inDesc);
  25822. typedef OSStatus (* ma_AudioComponentInstanceDispose_proc)(AudioComponentInstance inInstance);
  25823. typedef OSStatus (* ma_AudioComponentInstanceNew_proc)(AudioComponent inComponent, AudioComponentInstance* outInstance);
  25824. typedef OSStatus (* ma_AudioOutputUnitStart_proc)(AudioUnit inUnit);
  25825. typedef OSStatus (* ma_AudioOutputUnitStop_proc)(AudioUnit inUnit);
  25826. typedef OSStatus (* ma_AudioUnitAddPropertyListener_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitPropertyListenerProc inProc, void* inProcUserData);
  25827. typedef OSStatus (* ma_AudioUnitGetPropertyInfo_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, UInt32* outDataSize, Boolean* outWriteable);
  25828. typedef OSStatus (* ma_AudioUnitGetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, void* outData, UInt32* ioDataSize);
  25829. typedef OSStatus (* ma_AudioUnitSetProperty_proc)(AudioUnit inUnit, AudioUnitPropertyID inID, AudioUnitScope inScope, AudioUnitElement inElement, const void* inData, UInt32 inDataSize);
  25830. typedef OSStatus (* ma_AudioUnitInitialize_proc)(AudioUnit inUnit);
  25831. typedef OSStatus (* ma_AudioUnitRender_proc)(AudioUnit inUnit, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inOutputBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData);
  25832. #define MA_COREAUDIO_OUTPUT_BUS 0
  25833. #define MA_COREAUDIO_INPUT_BUS 1
  25834. #if defined(MA_APPLE_DESKTOP)
  25835. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit);
  25836. #endif
  25837. /*
  25838. Core Audio
  25839. So far, Core Audio has been the worst backend to work with due to being both unintuitive and having almost no documentation
  25840. apart from comments in the headers (which admittedly are quite good). For my own purposes, and for anybody out there whose
  25841. needing to figure out how this darn thing works, I'm going to outline a few things here.
  25842. Since miniaudio is a fairly low-level API, one of the things it needs is control over specific devices, and it needs to be
  25843. 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
  25844. that supports this level of detail. There was some public domain sample code I stumbled across that used the AudioComponent
  25845. and AudioUnit APIs, but I couldn't see anything that gave low-level control over device selection and capabilities (the
  25846. distinction between playback and capture in particular). Therefore, miniaudio is using the AudioObject API.
  25847. Most (all?) functions in the AudioObject API take a AudioObjectID as it's input. This is the device identifier. When
  25848. retrieving global information, such as the device list, you use kAudioObjectSystemObject. When retrieving device-specific
  25849. data, you pass in the ID for that device. In order to retrieve device-specific IDs you need to enumerate over each of the
  25850. devices. This is done using the AudioObjectGetPropertyDataSize() and AudioObjectGetPropertyData() APIs which seem to be
  25851. the central APIs for retrieving information about the system and specific devices.
  25852. To use the AudioObjectGetPropertyData() API you need to use the notion of a property address. A property address is a
  25853. structure with three variables and is used to identify which property you are getting or setting. The first is the "selector"
  25854. which is basically the specific property that you're wanting to retrieve or set. The second is the "scope", which is
  25855. typically set to kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyScopeInput for input-specific properties and
  25856. kAudioObjectPropertyScopeOutput for output-specific properties. The last is the "element" which is always set to
  25857. kAudioObjectPropertyElementMain in miniaudio's case. I don't know of any cases where this would be set to anything different.
  25858. Back to the earlier issue of device retrieval, you first use the AudioObjectGetPropertyDataSize() API to retrieve the size
  25859. of the raw data which is just a list of AudioDeviceID's. You use the kAudioObjectSystemObject AudioObjectID, and a property
  25860. address with the kAudioHardwarePropertyDevices selector and the kAudioObjectPropertyScopeGlobal scope. Once you have the
  25861. size, allocate a block of memory of that size and then call AudioObjectGetPropertyData(). The data is just a list of
  25862. AudioDeviceID's so just do "dataSize/sizeof(AudioDeviceID)" to know the device count.
  25863. */
  25864. static ma_result ma_result_from_OSStatus(OSStatus status)
  25865. {
  25866. switch (status)
  25867. {
  25868. case noErr: return MA_SUCCESS;
  25869. #if defined(MA_APPLE_DESKTOP)
  25870. case kAudioHardwareNotRunningError: return MA_DEVICE_NOT_STARTED;
  25871. case kAudioHardwareUnspecifiedError: return MA_ERROR;
  25872. case kAudioHardwareUnknownPropertyError: return MA_INVALID_ARGS;
  25873. case kAudioHardwareBadPropertySizeError: return MA_INVALID_OPERATION;
  25874. case kAudioHardwareIllegalOperationError: return MA_INVALID_OPERATION;
  25875. case kAudioHardwareBadObjectError: return MA_INVALID_ARGS;
  25876. case kAudioHardwareBadDeviceError: return MA_INVALID_ARGS;
  25877. case kAudioHardwareBadStreamError: return MA_INVALID_ARGS;
  25878. case kAudioHardwareUnsupportedOperationError: return MA_INVALID_OPERATION;
  25879. case kAudioDeviceUnsupportedFormatError: return MA_FORMAT_NOT_SUPPORTED;
  25880. case kAudioDevicePermissionsError: return MA_ACCESS_DENIED;
  25881. #endif
  25882. default: return MA_ERROR;
  25883. }
  25884. }
  25885. #if 0
  25886. static ma_channel ma_channel_from_AudioChannelBitmap(AudioChannelBitmap bit)
  25887. {
  25888. switch (bit)
  25889. {
  25890. case kAudioChannelBit_Left: return MA_CHANNEL_LEFT;
  25891. case kAudioChannelBit_Right: return MA_CHANNEL_RIGHT;
  25892. case kAudioChannelBit_Center: return MA_CHANNEL_FRONT_CENTER;
  25893. case kAudioChannelBit_LFEScreen: return MA_CHANNEL_LFE;
  25894. case kAudioChannelBit_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  25895. case kAudioChannelBit_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  25896. case kAudioChannelBit_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  25897. case kAudioChannelBit_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  25898. case kAudioChannelBit_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  25899. case kAudioChannelBit_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  25900. case kAudioChannelBit_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  25901. case kAudioChannelBit_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  25902. case kAudioChannelBit_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  25903. case kAudioChannelBit_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  25904. case kAudioChannelBit_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  25905. case kAudioChannelBit_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  25906. case kAudioChannelBit_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  25907. case kAudioChannelBit_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  25908. default: return MA_CHANNEL_NONE;
  25909. }
  25910. }
  25911. #endif
  25912. static ma_result ma_format_from_AudioStreamBasicDescription(const AudioStreamBasicDescription* pDescription, ma_format* pFormatOut)
  25913. {
  25914. MA_ASSERT(pDescription != NULL);
  25915. MA_ASSERT(pFormatOut != NULL);
  25916. *pFormatOut = ma_format_unknown; /* Safety. */
  25917. /* There's a few things miniaudio doesn't support. */
  25918. if (pDescription->mFormatID != kAudioFormatLinearPCM) {
  25919. return MA_FORMAT_NOT_SUPPORTED;
  25920. }
  25921. /* We don't support any non-packed formats that are aligned high. */
  25922. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsAlignedHigh) != 0) {
  25923. return MA_FORMAT_NOT_SUPPORTED;
  25924. }
  25925. /* Only supporting native-endian. */
  25926. if ((ma_is_little_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) != 0) || (ma_is_big_endian() && (pDescription->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0)) {
  25927. return MA_FORMAT_NOT_SUPPORTED;
  25928. }
  25929. /* We are not currently supporting non-interleaved formats (this will be added in a future version of miniaudio). */
  25930. /*if ((pDescription->mFormatFlags & kAudioFormatFlagIsNonInterleaved) != 0) {
  25931. return MA_FORMAT_NOT_SUPPORTED;
  25932. }*/
  25933. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsFloat) != 0) {
  25934. if (pDescription->mBitsPerChannel == 32) {
  25935. *pFormatOut = ma_format_f32;
  25936. return MA_SUCCESS;
  25937. }
  25938. } else {
  25939. if ((pDescription->mFormatFlags & kLinearPCMFormatFlagIsSignedInteger) != 0) {
  25940. if (pDescription->mBitsPerChannel == 16) {
  25941. *pFormatOut = ma_format_s16;
  25942. return MA_SUCCESS;
  25943. } else if (pDescription->mBitsPerChannel == 24) {
  25944. if (pDescription->mBytesPerFrame == (pDescription->mBitsPerChannel/8 * pDescription->mChannelsPerFrame)) {
  25945. *pFormatOut = ma_format_s24;
  25946. return MA_SUCCESS;
  25947. } else {
  25948. if (pDescription->mBytesPerFrame/pDescription->mChannelsPerFrame == sizeof(ma_int32)) {
  25949. /* TODO: Implement ma_format_s24_32. */
  25950. /**pFormatOut = ma_format_s24_32;*/
  25951. /*return MA_SUCCESS;*/
  25952. return MA_FORMAT_NOT_SUPPORTED;
  25953. }
  25954. }
  25955. } else if (pDescription->mBitsPerChannel == 32) {
  25956. *pFormatOut = ma_format_s32;
  25957. return MA_SUCCESS;
  25958. }
  25959. } else {
  25960. if (pDescription->mBitsPerChannel == 8) {
  25961. *pFormatOut = ma_format_u8;
  25962. return MA_SUCCESS;
  25963. }
  25964. }
  25965. }
  25966. /* Getting here means the format is not supported. */
  25967. return MA_FORMAT_NOT_SUPPORTED;
  25968. }
  25969. #if defined(MA_APPLE_DESKTOP)
  25970. static ma_channel ma_channel_from_AudioChannelLabel(AudioChannelLabel label)
  25971. {
  25972. switch (label)
  25973. {
  25974. case kAudioChannelLabel_Unknown: return MA_CHANNEL_NONE;
  25975. case kAudioChannelLabel_Unused: return MA_CHANNEL_NONE;
  25976. case kAudioChannelLabel_UseCoordinates: return MA_CHANNEL_NONE;
  25977. case kAudioChannelLabel_Left: return MA_CHANNEL_LEFT;
  25978. case kAudioChannelLabel_Right: return MA_CHANNEL_RIGHT;
  25979. case kAudioChannelLabel_Center: return MA_CHANNEL_FRONT_CENTER;
  25980. case kAudioChannelLabel_LFEScreen: return MA_CHANNEL_LFE;
  25981. case kAudioChannelLabel_LeftSurround: return MA_CHANNEL_BACK_LEFT;
  25982. case kAudioChannelLabel_RightSurround: return MA_CHANNEL_BACK_RIGHT;
  25983. case kAudioChannelLabel_LeftCenter: return MA_CHANNEL_FRONT_LEFT_CENTER;
  25984. case kAudioChannelLabel_RightCenter: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  25985. case kAudioChannelLabel_CenterSurround: return MA_CHANNEL_BACK_CENTER;
  25986. case kAudioChannelLabel_LeftSurroundDirect: return MA_CHANNEL_SIDE_LEFT;
  25987. case kAudioChannelLabel_RightSurroundDirect: return MA_CHANNEL_SIDE_RIGHT;
  25988. case kAudioChannelLabel_TopCenterSurround: return MA_CHANNEL_TOP_CENTER;
  25989. case kAudioChannelLabel_VerticalHeightLeft: return MA_CHANNEL_TOP_FRONT_LEFT;
  25990. case kAudioChannelLabel_VerticalHeightCenter: return MA_CHANNEL_TOP_FRONT_CENTER;
  25991. case kAudioChannelLabel_VerticalHeightRight: return MA_CHANNEL_TOP_FRONT_RIGHT;
  25992. case kAudioChannelLabel_TopBackLeft: return MA_CHANNEL_TOP_BACK_LEFT;
  25993. case kAudioChannelLabel_TopBackCenter: return MA_CHANNEL_TOP_BACK_CENTER;
  25994. case kAudioChannelLabel_TopBackRight: return MA_CHANNEL_TOP_BACK_RIGHT;
  25995. case kAudioChannelLabel_RearSurroundLeft: return MA_CHANNEL_BACK_LEFT;
  25996. case kAudioChannelLabel_RearSurroundRight: return MA_CHANNEL_BACK_RIGHT;
  25997. case kAudioChannelLabel_LeftWide: return MA_CHANNEL_SIDE_LEFT;
  25998. case kAudioChannelLabel_RightWide: return MA_CHANNEL_SIDE_RIGHT;
  25999. case kAudioChannelLabel_LFE2: return MA_CHANNEL_LFE;
  26000. case kAudioChannelLabel_LeftTotal: return MA_CHANNEL_LEFT;
  26001. case kAudioChannelLabel_RightTotal: return MA_CHANNEL_RIGHT;
  26002. case kAudioChannelLabel_HearingImpaired: return MA_CHANNEL_NONE;
  26003. case kAudioChannelLabel_Narration: return MA_CHANNEL_MONO;
  26004. case kAudioChannelLabel_Mono: return MA_CHANNEL_MONO;
  26005. case kAudioChannelLabel_DialogCentricMix: return MA_CHANNEL_MONO;
  26006. case kAudioChannelLabel_CenterSurroundDirect: return MA_CHANNEL_BACK_CENTER;
  26007. case kAudioChannelLabel_Haptic: return MA_CHANNEL_NONE;
  26008. case kAudioChannelLabel_Ambisonic_W: return MA_CHANNEL_NONE;
  26009. case kAudioChannelLabel_Ambisonic_X: return MA_CHANNEL_NONE;
  26010. case kAudioChannelLabel_Ambisonic_Y: return MA_CHANNEL_NONE;
  26011. case kAudioChannelLabel_Ambisonic_Z: return MA_CHANNEL_NONE;
  26012. case kAudioChannelLabel_MS_Mid: return MA_CHANNEL_LEFT;
  26013. case kAudioChannelLabel_MS_Side: return MA_CHANNEL_RIGHT;
  26014. case kAudioChannelLabel_XY_X: return MA_CHANNEL_LEFT;
  26015. case kAudioChannelLabel_XY_Y: return MA_CHANNEL_RIGHT;
  26016. case kAudioChannelLabel_HeadphonesLeft: return MA_CHANNEL_LEFT;
  26017. case kAudioChannelLabel_HeadphonesRight: return MA_CHANNEL_RIGHT;
  26018. case kAudioChannelLabel_ClickTrack: return MA_CHANNEL_NONE;
  26019. case kAudioChannelLabel_ForeignLanguage: return MA_CHANNEL_NONE;
  26020. case kAudioChannelLabel_Discrete: return MA_CHANNEL_NONE;
  26021. case kAudioChannelLabel_Discrete_0: return MA_CHANNEL_AUX_0;
  26022. case kAudioChannelLabel_Discrete_1: return MA_CHANNEL_AUX_1;
  26023. case kAudioChannelLabel_Discrete_2: return MA_CHANNEL_AUX_2;
  26024. case kAudioChannelLabel_Discrete_3: return MA_CHANNEL_AUX_3;
  26025. case kAudioChannelLabel_Discrete_4: return MA_CHANNEL_AUX_4;
  26026. case kAudioChannelLabel_Discrete_5: return MA_CHANNEL_AUX_5;
  26027. case kAudioChannelLabel_Discrete_6: return MA_CHANNEL_AUX_6;
  26028. case kAudioChannelLabel_Discrete_7: return MA_CHANNEL_AUX_7;
  26029. case kAudioChannelLabel_Discrete_8: return MA_CHANNEL_AUX_8;
  26030. case kAudioChannelLabel_Discrete_9: return MA_CHANNEL_AUX_9;
  26031. case kAudioChannelLabel_Discrete_10: return MA_CHANNEL_AUX_10;
  26032. case kAudioChannelLabel_Discrete_11: return MA_CHANNEL_AUX_11;
  26033. case kAudioChannelLabel_Discrete_12: return MA_CHANNEL_AUX_12;
  26034. case kAudioChannelLabel_Discrete_13: return MA_CHANNEL_AUX_13;
  26035. case kAudioChannelLabel_Discrete_14: return MA_CHANNEL_AUX_14;
  26036. case kAudioChannelLabel_Discrete_15: return MA_CHANNEL_AUX_15;
  26037. case kAudioChannelLabel_Discrete_65535: return MA_CHANNEL_NONE;
  26038. #if 0 /* Introduced in a later version of macOS. */
  26039. case kAudioChannelLabel_HOA_ACN: return MA_CHANNEL_NONE;
  26040. case kAudioChannelLabel_HOA_ACN_0: return MA_CHANNEL_AUX_0;
  26041. case kAudioChannelLabel_HOA_ACN_1: return MA_CHANNEL_AUX_1;
  26042. case kAudioChannelLabel_HOA_ACN_2: return MA_CHANNEL_AUX_2;
  26043. case kAudioChannelLabel_HOA_ACN_3: return MA_CHANNEL_AUX_3;
  26044. case kAudioChannelLabel_HOA_ACN_4: return MA_CHANNEL_AUX_4;
  26045. case kAudioChannelLabel_HOA_ACN_5: return MA_CHANNEL_AUX_5;
  26046. case kAudioChannelLabel_HOA_ACN_6: return MA_CHANNEL_AUX_6;
  26047. case kAudioChannelLabel_HOA_ACN_7: return MA_CHANNEL_AUX_7;
  26048. case kAudioChannelLabel_HOA_ACN_8: return MA_CHANNEL_AUX_8;
  26049. case kAudioChannelLabel_HOA_ACN_9: return MA_CHANNEL_AUX_9;
  26050. case kAudioChannelLabel_HOA_ACN_10: return MA_CHANNEL_AUX_10;
  26051. case kAudioChannelLabel_HOA_ACN_11: return MA_CHANNEL_AUX_11;
  26052. case kAudioChannelLabel_HOA_ACN_12: return MA_CHANNEL_AUX_12;
  26053. case kAudioChannelLabel_HOA_ACN_13: return MA_CHANNEL_AUX_13;
  26054. case kAudioChannelLabel_HOA_ACN_14: return MA_CHANNEL_AUX_14;
  26055. case kAudioChannelLabel_HOA_ACN_15: return MA_CHANNEL_AUX_15;
  26056. case kAudioChannelLabel_HOA_ACN_65024: return MA_CHANNEL_NONE;
  26057. #endif
  26058. default: return MA_CHANNEL_NONE;
  26059. }
  26060. }
  26061. static ma_result ma_get_channel_map_from_AudioChannelLayout(AudioChannelLayout* pChannelLayout, ma_channel* pChannelMap, size_t channelMapCap)
  26062. {
  26063. MA_ASSERT(pChannelLayout != NULL);
  26064. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  26065. UInt32 iChannel;
  26066. for (iChannel = 0; iChannel < pChannelLayout->mNumberChannelDescriptions && iChannel < channelMapCap; ++iChannel) {
  26067. pChannelMap[iChannel] = ma_channel_from_AudioChannelLabel(pChannelLayout->mChannelDescriptions[iChannel].mChannelLabel);
  26068. }
  26069. } else
  26070. #if 0
  26071. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  26072. /* This is the same kind of system that's used by Windows audio APIs. */
  26073. UInt32 iChannel = 0;
  26074. UInt32 iBit;
  26075. AudioChannelBitmap bitmap = pChannelLayout->mChannelBitmap;
  26076. for (iBit = 0; iBit < 32 && iChannel < channelMapCap; ++iBit) {
  26077. AudioChannelBitmap bit = bitmap & (1 << iBit);
  26078. if (bit != 0) {
  26079. pChannelMap[iChannel++] = ma_channel_from_AudioChannelBit(bit);
  26080. }
  26081. }
  26082. } else
  26083. #endif
  26084. {
  26085. /*
  26086. 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
  26087. be updated to determine the mapping based on the tag.
  26088. */
  26089. UInt32 channelCount;
  26090. /* Our channel map retrieval APIs below take 32-bit integers, so we'll want to clamp the channel map capacity. */
  26091. if (channelMapCap > 0xFFFFFFFF) {
  26092. channelMapCap = 0xFFFFFFFF;
  26093. }
  26094. channelCount = ma_min(AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag), (UInt32)channelMapCap);
  26095. switch (pChannelLayout->mChannelLayoutTag)
  26096. {
  26097. case kAudioChannelLayoutTag_Mono:
  26098. case kAudioChannelLayoutTag_Stereo:
  26099. case kAudioChannelLayoutTag_StereoHeadphones:
  26100. case kAudioChannelLayoutTag_MatrixStereo:
  26101. case kAudioChannelLayoutTag_MidSide:
  26102. case kAudioChannelLayoutTag_XY:
  26103. case kAudioChannelLayoutTag_Binaural:
  26104. case kAudioChannelLayoutTag_Ambisonic_B_Format:
  26105. {
  26106. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  26107. } break;
  26108. case kAudioChannelLayoutTag_Octagonal:
  26109. {
  26110. pChannelMap[7] = MA_CHANNEL_SIDE_RIGHT;
  26111. pChannelMap[6] = MA_CHANNEL_SIDE_LEFT;
  26112. } /* Intentional fallthrough. */
  26113. case kAudioChannelLayoutTag_Hexagonal:
  26114. {
  26115. pChannelMap[5] = MA_CHANNEL_BACK_CENTER;
  26116. } /* Intentional fallthrough. */
  26117. case kAudioChannelLayoutTag_Pentagonal:
  26118. {
  26119. pChannelMap[4] = MA_CHANNEL_FRONT_CENTER;
  26120. } /* Intentional fallghrough. */
  26121. case kAudioChannelLayoutTag_Quadraphonic:
  26122. {
  26123. pChannelMap[3] = MA_CHANNEL_BACK_RIGHT;
  26124. pChannelMap[2] = MA_CHANNEL_BACK_LEFT;
  26125. pChannelMap[1] = MA_CHANNEL_RIGHT;
  26126. pChannelMap[0] = MA_CHANNEL_LEFT;
  26127. } break;
  26128. /* TODO: Add support for more tags here. */
  26129. default:
  26130. {
  26131. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  26132. } break;
  26133. }
  26134. }
  26135. return MA_SUCCESS;
  26136. }
  26137. #if (defined(MAC_OS_VERSION_12_0) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_VERSION_12_0) || \
  26138. (defined(__IPHONE_15_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_15_0)
  26139. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMain
  26140. #else
  26141. /* kAudioObjectPropertyElementMaster is deprecated. */
  26142. #define AUDIO_OBJECT_PROPERTY_ELEMENT kAudioObjectPropertyElementMaster
  26143. #endif
  26144. static ma_result ma_get_device_object_ids__coreaudio(ma_context* pContext, UInt32* pDeviceCount, AudioObjectID** ppDeviceObjectIDs) /* NOTE: Free the returned buffer with ma_free(). */
  26145. {
  26146. AudioObjectPropertyAddress propAddressDevices;
  26147. UInt32 deviceObjectsDataSize;
  26148. OSStatus status;
  26149. AudioObjectID* pDeviceObjectIDs;
  26150. MA_ASSERT(pContext != NULL);
  26151. MA_ASSERT(pDeviceCount != NULL);
  26152. MA_ASSERT(ppDeviceObjectIDs != NULL);
  26153. /* Safety. */
  26154. *pDeviceCount = 0;
  26155. *ppDeviceObjectIDs = NULL;
  26156. propAddressDevices.mSelector = kAudioHardwarePropertyDevices;
  26157. propAddressDevices.mScope = kAudioObjectPropertyScopeGlobal;
  26158. propAddressDevices.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26159. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize);
  26160. if (status != noErr) {
  26161. return ma_result_from_OSStatus(status);
  26162. }
  26163. pDeviceObjectIDs = (AudioObjectID*)ma_malloc(deviceObjectsDataSize, &pContext->allocationCallbacks);
  26164. if (pDeviceObjectIDs == NULL) {
  26165. return MA_OUT_OF_MEMORY;
  26166. }
  26167. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDevices, 0, NULL, &deviceObjectsDataSize, pDeviceObjectIDs);
  26168. if (status != noErr) {
  26169. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  26170. return ma_result_from_OSStatus(status);
  26171. }
  26172. *pDeviceCount = deviceObjectsDataSize / sizeof(AudioObjectID);
  26173. *ppDeviceObjectIDs = pDeviceObjectIDs;
  26174. return MA_SUCCESS;
  26175. }
  26176. static ma_result ma_get_AudioObject_uid_as_CFStringRef(ma_context* pContext, AudioObjectID objectID, CFStringRef* pUID)
  26177. {
  26178. AudioObjectPropertyAddress propAddress;
  26179. UInt32 dataSize;
  26180. OSStatus status;
  26181. MA_ASSERT(pContext != NULL);
  26182. propAddress.mSelector = kAudioDevicePropertyDeviceUID;
  26183. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  26184. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26185. dataSize = sizeof(*pUID);
  26186. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, pUID);
  26187. if (status != noErr) {
  26188. return ma_result_from_OSStatus(status);
  26189. }
  26190. return MA_SUCCESS;
  26191. }
  26192. static ma_result ma_get_AudioObject_uid(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  26193. {
  26194. CFStringRef uid;
  26195. ma_result result;
  26196. MA_ASSERT(pContext != NULL);
  26197. result = ma_get_AudioObject_uid_as_CFStringRef(pContext, objectID, &uid);
  26198. if (result != MA_SUCCESS) {
  26199. return result;
  26200. }
  26201. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(uid, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  26202. return MA_ERROR;
  26203. }
  26204. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(uid);
  26205. return MA_SUCCESS;
  26206. }
  26207. static ma_result ma_get_AudioObject_name(ma_context* pContext, AudioObjectID objectID, size_t bufferSize, char* bufferOut)
  26208. {
  26209. AudioObjectPropertyAddress propAddress;
  26210. CFStringRef deviceName = NULL;
  26211. UInt32 dataSize;
  26212. OSStatus status;
  26213. MA_ASSERT(pContext != NULL);
  26214. propAddress.mSelector = kAudioDevicePropertyDeviceNameCFString;
  26215. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  26216. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26217. dataSize = sizeof(deviceName);
  26218. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(objectID, &propAddress, 0, NULL, &dataSize, &deviceName);
  26219. if (status != noErr) {
  26220. return ma_result_from_OSStatus(status);
  26221. }
  26222. if (!((ma_CFStringGetCString_proc)pContext->coreaudio.CFStringGetCString)(deviceName, bufferOut, bufferSize, kCFStringEncodingUTF8)) {
  26223. return MA_ERROR;
  26224. }
  26225. ((ma_CFRelease_proc)pContext->coreaudio.CFRelease)(deviceName);
  26226. return MA_SUCCESS;
  26227. }
  26228. static ma_bool32 ma_does_AudioObject_support_scope(ma_context* pContext, AudioObjectID deviceObjectID, AudioObjectPropertyScope scope)
  26229. {
  26230. AudioObjectPropertyAddress propAddress;
  26231. UInt32 dataSize;
  26232. OSStatus status;
  26233. AudioBufferList* pBufferList;
  26234. ma_bool32 isSupported;
  26235. MA_ASSERT(pContext != NULL);
  26236. /* 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. */
  26237. propAddress.mSelector = kAudioDevicePropertyStreamConfiguration;
  26238. propAddress.mScope = scope;
  26239. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26240. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  26241. if (status != noErr) {
  26242. return MA_FALSE;
  26243. }
  26244. pBufferList = (AudioBufferList*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  26245. if (pBufferList == NULL) {
  26246. return MA_FALSE; /* Out of memory. */
  26247. }
  26248. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pBufferList);
  26249. if (status != noErr) {
  26250. ma_free(pBufferList, &pContext->allocationCallbacks);
  26251. return MA_FALSE;
  26252. }
  26253. isSupported = MA_FALSE;
  26254. if (pBufferList->mNumberBuffers > 0) {
  26255. isSupported = MA_TRUE;
  26256. }
  26257. ma_free(pBufferList, &pContext->allocationCallbacks);
  26258. return isSupported;
  26259. }
  26260. static ma_bool32 ma_does_AudioObject_support_playback(ma_context* pContext, AudioObjectID deviceObjectID)
  26261. {
  26262. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeOutput);
  26263. }
  26264. static ma_bool32 ma_does_AudioObject_support_capture(ma_context* pContext, AudioObjectID deviceObjectID)
  26265. {
  26266. return ma_does_AudioObject_support_scope(pContext, deviceObjectID, kAudioObjectPropertyScopeInput);
  26267. }
  26268. 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(). */
  26269. {
  26270. AudioObjectPropertyAddress propAddress;
  26271. UInt32 dataSize;
  26272. OSStatus status;
  26273. AudioStreamRangedDescription* pDescriptions;
  26274. MA_ASSERT(pContext != NULL);
  26275. MA_ASSERT(pDescriptionCount != NULL);
  26276. MA_ASSERT(ppDescriptions != NULL);
  26277. /*
  26278. TODO: Experiment with kAudioStreamPropertyAvailablePhysicalFormats instead of (or in addition to) kAudioStreamPropertyAvailableVirtualFormats. My
  26279. MacBook Pro uses s24/32 format, however, which miniaudio does not currently support.
  26280. */
  26281. propAddress.mSelector = kAudioStreamPropertyAvailableVirtualFormats; /*kAudioStreamPropertyAvailablePhysicalFormats;*/
  26282. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  26283. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26284. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  26285. if (status != noErr) {
  26286. return ma_result_from_OSStatus(status);
  26287. }
  26288. pDescriptions = (AudioStreamRangedDescription*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  26289. if (pDescriptions == NULL) {
  26290. return MA_OUT_OF_MEMORY;
  26291. }
  26292. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pDescriptions);
  26293. if (status != noErr) {
  26294. ma_free(pDescriptions, &pContext->allocationCallbacks);
  26295. return ma_result_from_OSStatus(status);
  26296. }
  26297. *pDescriptionCount = dataSize / sizeof(*pDescriptions);
  26298. *ppDescriptions = pDescriptions;
  26299. return MA_SUCCESS;
  26300. }
  26301. 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(). */
  26302. {
  26303. AudioObjectPropertyAddress propAddress;
  26304. UInt32 dataSize;
  26305. OSStatus status;
  26306. AudioChannelLayout* pChannelLayout;
  26307. MA_ASSERT(pContext != NULL);
  26308. MA_ASSERT(ppChannelLayout != NULL);
  26309. *ppChannelLayout = NULL; /* Safety. */
  26310. propAddress.mSelector = kAudioDevicePropertyPreferredChannelLayout;
  26311. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  26312. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26313. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  26314. if (status != noErr) {
  26315. return ma_result_from_OSStatus(status);
  26316. }
  26317. pChannelLayout = (AudioChannelLayout*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  26318. if (pChannelLayout == NULL) {
  26319. return MA_OUT_OF_MEMORY;
  26320. }
  26321. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pChannelLayout);
  26322. if (status != noErr) {
  26323. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26324. return ma_result_from_OSStatus(status);
  26325. }
  26326. *ppChannelLayout = pChannelLayout;
  26327. return MA_SUCCESS;
  26328. }
  26329. static ma_result ma_get_AudioObject_channel_count(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pChannelCount)
  26330. {
  26331. AudioChannelLayout* pChannelLayout;
  26332. ma_result result;
  26333. MA_ASSERT(pContext != NULL);
  26334. MA_ASSERT(pChannelCount != NULL);
  26335. *pChannelCount = 0; /* Safety. */
  26336. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  26337. if (result != MA_SUCCESS) {
  26338. return result;
  26339. }
  26340. if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelDescriptions) {
  26341. *pChannelCount = pChannelLayout->mNumberChannelDescriptions;
  26342. } else if (pChannelLayout->mChannelLayoutTag == kAudioChannelLayoutTag_UseChannelBitmap) {
  26343. *pChannelCount = ma_count_set_bits(pChannelLayout->mChannelBitmap);
  26344. } else {
  26345. *pChannelCount = AudioChannelLayoutTag_GetNumberOfChannels(pChannelLayout->mChannelLayoutTag);
  26346. }
  26347. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26348. return MA_SUCCESS;
  26349. }
  26350. #if 0
  26351. static ma_result ma_get_AudioObject_channel_map(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  26352. {
  26353. AudioChannelLayout* pChannelLayout;
  26354. ma_result result;
  26355. MA_ASSERT(pContext != NULL);
  26356. result = ma_get_AudioObject_channel_layout(pContext, deviceObjectID, deviceType, &pChannelLayout);
  26357. if (result != MA_SUCCESS) {
  26358. return result; /* Rather than always failing here, would it be more robust to simply assume a default? */
  26359. }
  26360. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  26361. if (result != MA_SUCCESS) {
  26362. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26363. return result;
  26364. }
  26365. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26366. return result;
  26367. }
  26368. #endif
  26369. 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(). */
  26370. {
  26371. AudioObjectPropertyAddress propAddress;
  26372. UInt32 dataSize;
  26373. OSStatus status;
  26374. AudioValueRange* pSampleRateRanges;
  26375. MA_ASSERT(pContext != NULL);
  26376. MA_ASSERT(pSampleRateRangesCount != NULL);
  26377. MA_ASSERT(ppSampleRateRanges != NULL);
  26378. /* Safety. */
  26379. *pSampleRateRangesCount = 0;
  26380. *ppSampleRateRanges = NULL;
  26381. propAddress.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  26382. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  26383. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26384. status = ((ma_AudioObjectGetPropertyDataSize_proc)pContext->coreaudio.AudioObjectGetPropertyDataSize)(deviceObjectID, &propAddress, 0, NULL, &dataSize);
  26385. if (status != noErr) {
  26386. return ma_result_from_OSStatus(status);
  26387. }
  26388. pSampleRateRanges = (AudioValueRange*)ma_malloc(dataSize, &pContext->allocationCallbacks);
  26389. if (pSampleRateRanges == NULL) {
  26390. return MA_OUT_OF_MEMORY;
  26391. }
  26392. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, pSampleRateRanges);
  26393. if (status != noErr) {
  26394. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26395. return ma_result_from_OSStatus(status);
  26396. }
  26397. *pSampleRateRangesCount = dataSize / sizeof(*pSampleRateRanges);
  26398. *ppSampleRateRanges = pSampleRateRanges;
  26399. return MA_SUCCESS;
  26400. }
  26401. #if 0
  26402. 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)
  26403. {
  26404. UInt32 sampleRateRangeCount;
  26405. AudioValueRange* pSampleRateRanges;
  26406. ma_result result;
  26407. MA_ASSERT(pContext != NULL);
  26408. MA_ASSERT(pSampleRateOut != NULL);
  26409. *pSampleRateOut = 0; /* Safety. */
  26410. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  26411. if (result != MA_SUCCESS) {
  26412. return result;
  26413. }
  26414. if (sampleRateRangeCount == 0) {
  26415. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26416. return MA_ERROR; /* Should never hit this case should we? */
  26417. }
  26418. if (sampleRateIn == 0) {
  26419. /* Search in order of miniaudio's preferred priority. */
  26420. UInt32 iMALSampleRate;
  26421. for (iMALSampleRate = 0; iMALSampleRate < ma_countof(g_maStandardSampleRatePriorities); ++iMALSampleRate) {
  26422. ma_uint32 malSampleRate = g_maStandardSampleRatePriorities[iMALSampleRate];
  26423. UInt32 iCASampleRate;
  26424. for (iCASampleRate = 0; iCASampleRate < sampleRateRangeCount; ++iCASampleRate) {
  26425. AudioValueRange caSampleRate = pSampleRateRanges[iCASampleRate];
  26426. if (caSampleRate.mMinimum <= malSampleRate && caSampleRate.mMaximum >= malSampleRate) {
  26427. *pSampleRateOut = malSampleRate;
  26428. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26429. return MA_SUCCESS;
  26430. }
  26431. }
  26432. }
  26433. /*
  26434. 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
  26435. case we just fall back to the first one reported by Core Audio.
  26436. */
  26437. MA_ASSERT(sampleRateRangeCount > 0);
  26438. *pSampleRateOut = pSampleRateRanges[0].mMinimum;
  26439. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26440. return MA_SUCCESS;
  26441. } else {
  26442. /* Find the closest match to this sample rate. */
  26443. UInt32 currentAbsoluteDifference = INT32_MAX;
  26444. UInt32 iCurrentClosestRange = (UInt32)-1;
  26445. UInt32 iRange;
  26446. for (iRange = 0; iRange < sampleRateRangeCount; ++iRange) {
  26447. if (pSampleRateRanges[iRange].mMinimum <= sampleRateIn && pSampleRateRanges[iRange].mMaximum >= sampleRateIn) {
  26448. *pSampleRateOut = sampleRateIn;
  26449. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26450. return MA_SUCCESS;
  26451. } else {
  26452. UInt32 absoluteDifference;
  26453. if (pSampleRateRanges[iRange].mMinimum > sampleRateIn) {
  26454. absoluteDifference = pSampleRateRanges[iRange].mMinimum - sampleRateIn;
  26455. } else {
  26456. absoluteDifference = sampleRateIn - pSampleRateRanges[iRange].mMaximum;
  26457. }
  26458. if (currentAbsoluteDifference > absoluteDifference) {
  26459. currentAbsoluteDifference = absoluteDifference;
  26460. iCurrentClosestRange = iRange;
  26461. }
  26462. }
  26463. }
  26464. MA_ASSERT(iCurrentClosestRange != (UInt32)-1);
  26465. *pSampleRateOut = pSampleRateRanges[iCurrentClosestRange].mMinimum;
  26466. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26467. return MA_SUCCESS;
  26468. }
  26469. /* Should never get here, but it would mean we weren't able to find any suitable sample rates. */
  26470. /*ma_free(pSampleRateRanges, &pContext->allocationCallbacks);*/
  26471. /*return MA_ERROR;*/
  26472. }
  26473. #endif
  26474. 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)
  26475. {
  26476. AudioObjectPropertyAddress propAddress;
  26477. AudioValueRange bufferSizeRange;
  26478. UInt32 dataSize;
  26479. OSStatus status;
  26480. MA_ASSERT(pContext != NULL);
  26481. MA_ASSERT(pBufferSizeInFramesOut != NULL);
  26482. *pBufferSizeInFramesOut = 0; /* Safety. */
  26483. propAddress.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  26484. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  26485. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26486. dataSize = sizeof(bufferSizeRange);
  26487. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &bufferSizeRange);
  26488. if (status != noErr) {
  26489. return ma_result_from_OSStatus(status);
  26490. }
  26491. /* This is just a clamp. */
  26492. if (bufferSizeInFramesIn < bufferSizeRange.mMinimum) {
  26493. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMinimum;
  26494. } else if (bufferSizeInFramesIn > bufferSizeRange.mMaximum) {
  26495. *pBufferSizeInFramesOut = (ma_uint32)bufferSizeRange.mMaximum;
  26496. } else {
  26497. *pBufferSizeInFramesOut = bufferSizeInFramesIn;
  26498. }
  26499. return MA_SUCCESS;
  26500. }
  26501. static ma_result ma_set_AudioObject_buffer_size_in_frames(ma_context* pContext, AudioObjectID deviceObjectID, ma_device_type deviceType, ma_uint32* pPeriodSizeInOut)
  26502. {
  26503. ma_result result;
  26504. ma_uint32 chosenBufferSizeInFrames;
  26505. AudioObjectPropertyAddress propAddress;
  26506. UInt32 dataSize;
  26507. OSStatus status;
  26508. MA_ASSERT(pContext != NULL);
  26509. result = ma_get_AudioObject_closest_buffer_size_in_frames(pContext, deviceObjectID, deviceType, *pPeriodSizeInOut, &chosenBufferSizeInFrames);
  26510. if (result != MA_SUCCESS) {
  26511. return result;
  26512. }
  26513. /* Try setting the size of the buffer... If this fails we just use whatever is currently set. */
  26514. propAddress.mSelector = kAudioDevicePropertyBufferFrameSize;
  26515. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  26516. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26517. ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(chosenBufferSizeInFrames), &chosenBufferSizeInFrames);
  26518. /* Get the actual size of the buffer. */
  26519. dataSize = sizeof(*pPeriodSizeInOut);
  26520. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(deviceObjectID, &propAddress, 0, NULL, &dataSize, &chosenBufferSizeInFrames);
  26521. if (status != noErr) {
  26522. return ma_result_from_OSStatus(status);
  26523. }
  26524. *pPeriodSizeInOut = chosenBufferSizeInFrames;
  26525. return MA_SUCCESS;
  26526. }
  26527. static ma_result ma_find_default_AudioObjectID(ma_context* pContext, ma_device_type deviceType, AudioObjectID* pDeviceObjectID)
  26528. {
  26529. AudioObjectPropertyAddress propAddressDefaultDevice;
  26530. UInt32 defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  26531. AudioObjectID defaultDeviceObjectID;
  26532. OSStatus status;
  26533. MA_ASSERT(pContext != NULL);
  26534. MA_ASSERT(pDeviceObjectID != NULL);
  26535. /* Safety. */
  26536. *pDeviceObjectID = 0;
  26537. propAddressDefaultDevice.mScope = kAudioObjectPropertyScopeGlobal;
  26538. propAddressDefaultDevice.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  26539. if (deviceType == ma_device_type_playback) {
  26540. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  26541. } else {
  26542. propAddressDefaultDevice.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  26543. }
  26544. defaultDeviceObjectIDSize = sizeof(AudioObjectID);
  26545. status = ((ma_AudioObjectGetPropertyData_proc)pContext->coreaudio.AudioObjectGetPropertyData)(kAudioObjectSystemObject, &propAddressDefaultDevice, 0, NULL, &defaultDeviceObjectIDSize, &defaultDeviceObjectID);
  26546. if (status == noErr) {
  26547. *pDeviceObjectID = defaultDeviceObjectID;
  26548. return MA_SUCCESS;
  26549. }
  26550. /* If we get here it means we couldn't find the device. */
  26551. return MA_NO_DEVICE;
  26552. }
  26553. static ma_result ma_find_AudioObjectID(ma_context* pContext, ma_device_type deviceType, const ma_device_id* pDeviceID, AudioObjectID* pDeviceObjectID)
  26554. {
  26555. MA_ASSERT(pContext != NULL);
  26556. MA_ASSERT(pDeviceObjectID != NULL);
  26557. /* Safety. */
  26558. *pDeviceObjectID = 0;
  26559. if (pDeviceID == NULL) {
  26560. /* Default device. */
  26561. return ma_find_default_AudioObjectID(pContext, deviceType, pDeviceObjectID);
  26562. } else {
  26563. /* Explicit device. */
  26564. UInt32 deviceCount;
  26565. AudioObjectID* pDeviceObjectIDs;
  26566. ma_result result;
  26567. UInt32 iDevice;
  26568. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  26569. if (result != MA_SUCCESS) {
  26570. return result;
  26571. }
  26572. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  26573. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  26574. char uid[256];
  26575. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(uid), uid) != MA_SUCCESS) {
  26576. continue;
  26577. }
  26578. if (deviceType == ma_device_type_playback) {
  26579. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  26580. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  26581. *pDeviceObjectID = deviceObjectID;
  26582. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  26583. return MA_SUCCESS;
  26584. }
  26585. }
  26586. } else {
  26587. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  26588. if (strcmp(uid, pDeviceID->coreaudio) == 0) {
  26589. *pDeviceObjectID = deviceObjectID;
  26590. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  26591. return MA_SUCCESS;
  26592. }
  26593. }
  26594. }
  26595. }
  26596. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  26597. }
  26598. /* If we get here it means we couldn't find the device. */
  26599. return MA_NO_DEVICE;
  26600. }
  26601. 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)
  26602. {
  26603. UInt32 deviceFormatDescriptionCount;
  26604. AudioStreamRangedDescription* pDeviceFormatDescriptions;
  26605. ma_result result;
  26606. ma_uint32 desiredSampleRate;
  26607. ma_uint32 desiredChannelCount;
  26608. ma_format desiredFormat;
  26609. AudioStreamBasicDescription bestDeviceFormatSoFar;
  26610. ma_bool32 hasSupportedFormat;
  26611. UInt32 iFormat;
  26612. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &deviceFormatDescriptionCount, &pDeviceFormatDescriptions);
  26613. if (result != MA_SUCCESS) {
  26614. return result;
  26615. }
  26616. desiredSampleRate = sampleRate;
  26617. if (desiredSampleRate == 0) {
  26618. desiredSampleRate = pOrigFormat->mSampleRate;
  26619. }
  26620. desiredChannelCount = channels;
  26621. if (desiredChannelCount == 0) {
  26622. desiredChannelCount = pOrigFormat->mChannelsPerFrame;
  26623. }
  26624. desiredFormat = format;
  26625. if (desiredFormat == ma_format_unknown) {
  26626. result = ma_format_from_AudioStreamBasicDescription(pOrigFormat, &desiredFormat);
  26627. if (result != MA_SUCCESS || desiredFormat == ma_format_unknown) {
  26628. desiredFormat = g_maFormatPriorities[0];
  26629. }
  26630. }
  26631. /*
  26632. 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
  26633. 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.
  26634. */
  26635. MA_ZERO_OBJECT(&bestDeviceFormatSoFar);
  26636. hasSupportedFormat = MA_FALSE;
  26637. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  26638. ma_format format;
  26639. ma_result formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &format);
  26640. if (formatResult == MA_SUCCESS && format != ma_format_unknown) {
  26641. hasSupportedFormat = MA_TRUE;
  26642. bestDeviceFormatSoFar = pDeviceFormatDescriptions[iFormat].mFormat;
  26643. break;
  26644. }
  26645. }
  26646. if (!hasSupportedFormat) {
  26647. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  26648. return MA_FORMAT_NOT_SUPPORTED;
  26649. }
  26650. for (iFormat = 0; iFormat < deviceFormatDescriptionCount; ++iFormat) {
  26651. AudioStreamBasicDescription thisDeviceFormat = pDeviceFormatDescriptions[iFormat].mFormat;
  26652. ma_format thisSampleFormat;
  26653. ma_result formatResult;
  26654. ma_format bestSampleFormatSoFar;
  26655. /* If the format is not supported by miniaudio we need to skip this one entirely. */
  26656. formatResult = ma_format_from_AudioStreamBasicDescription(&pDeviceFormatDescriptions[iFormat].mFormat, &thisSampleFormat);
  26657. if (formatResult != MA_SUCCESS || thisSampleFormat == ma_format_unknown) {
  26658. continue; /* The format is not supported by miniaudio. Skip. */
  26659. }
  26660. ma_format_from_AudioStreamBasicDescription(&bestDeviceFormatSoFar, &bestSampleFormatSoFar);
  26661. /* Getting here means the format is supported by miniaudio which makes this format a candidate. */
  26662. if (thisDeviceFormat.mSampleRate != desiredSampleRate) {
  26663. /*
  26664. The sample rate does not match, but this format could still be usable, although it's a very low priority. If the best format
  26665. so far has an equal sample rate we can just ignore this one.
  26666. */
  26667. if (bestDeviceFormatSoFar.mSampleRate == desiredSampleRate) {
  26668. 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. */
  26669. } else {
  26670. /* In this case, neither the best format so far nor this one have the same sample rate. Check the channel count next. */
  26671. if (thisDeviceFormat.mChannelsPerFrame != desiredChannelCount) {
  26672. /* This format has a different sample rate _and_ a different channel count. */
  26673. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  26674. continue; /* No change to the best format. */
  26675. } else {
  26676. /*
  26677. Both this format and the best so far have different sample rates and different channel counts. Whichever has the
  26678. best format is the new best.
  26679. */
  26680. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  26681. bestDeviceFormatSoFar = thisDeviceFormat;
  26682. continue;
  26683. } else {
  26684. continue; /* No change to the best format. */
  26685. }
  26686. }
  26687. } else {
  26688. /* This format has a different sample rate but the desired channel count. */
  26689. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  26690. /* Both this format and the best so far have the desired channel count. Whichever has the best format is the new best. */
  26691. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  26692. bestDeviceFormatSoFar = thisDeviceFormat;
  26693. continue;
  26694. } else {
  26695. continue; /* No change to the best format for now. */
  26696. }
  26697. } else {
  26698. /* This format has the desired channel count, but the best so far does not. We have a new best. */
  26699. bestDeviceFormatSoFar = thisDeviceFormat;
  26700. continue;
  26701. }
  26702. }
  26703. }
  26704. } else {
  26705. /*
  26706. The sample rates match which makes this format a very high priority contender. If the best format so far has a different
  26707. sample rate it needs to be replaced with this one.
  26708. */
  26709. if (bestDeviceFormatSoFar.mSampleRate != desiredSampleRate) {
  26710. bestDeviceFormatSoFar = thisDeviceFormat;
  26711. continue;
  26712. } else {
  26713. /* In this case both this format and the best format so far have the same sample rate. Check the channel count next. */
  26714. if (thisDeviceFormat.mChannelsPerFrame == desiredChannelCount) {
  26715. /*
  26716. In this case this format has the same channel count as what the client is requesting. If the best format so far has
  26717. a different count, this one becomes the new best.
  26718. */
  26719. if (bestDeviceFormatSoFar.mChannelsPerFrame != desiredChannelCount) {
  26720. bestDeviceFormatSoFar = thisDeviceFormat;
  26721. continue;
  26722. } else {
  26723. /* In this case both this format and the best so far have the ideal sample rate and channel count. Check the format. */
  26724. if (thisSampleFormat == desiredFormat) {
  26725. bestDeviceFormatSoFar = thisDeviceFormat;
  26726. break; /* Found the exact match. */
  26727. } else {
  26728. /* The formats are different. The new best format is the one with the highest priority format according to miniaudio. */
  26729. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  26730. bestDeviceFormatSoFar = thisDeviceFormat;
  26731. continue;
  26732. } else {
  26733. continue; /* No change to the best format for now. */
  26734. }
  26735. }
  26736. }
  26737. } else {
  26738. /*
  26739. In this case the channel count is different to what the client has requested. If the best so far has the same channel
  26740. count as the requested count then it remains the best.
  26741. */
  26742. if (bestDeviceFormatSoFar.mChannelsPerFrame == desiredChannelCount) {
  26743. continue;
  26744. } else {
  26745. /*
  26746. This is the case where both have the same sample rate (good) but different channel counts. Right now both have about
  26747. the same priority, but we need to compare the format now.
  26748. */
  26749. if (thisSampleFormat == bestSampleFormatSoFar) {
  26750. if (ma_get_format_priority_index(thisSampleFormat) < ma_get_format_priority_index(bestSampleFormatSoFar)) {
  26751. bestDeviceFormatSoFar = thisDeviceFormat;
  26752. continue;
  26753. } else {
  26754. continue; /* No change to the best format for now. */
  26755. }
  26756. }
  26757. }
  26758. }
  26759. }
  26760. }
  26761. }
  26762. *pFormat = bestDeviceFormatSoFar;
  26763. ma_free(pDeviceFormatDescriptions, &pContext->allocationCallbacks);
  26764. return MA_SUCCESS;
  26765. }
  26766. static ma_result ma_get_AudioUnit_channel_map(ma_context* pContext, AudioUnit audioUnit, ma_device_type deviceType, ma_channel* pChannelMap, size_t channelMapCap)
  26767. {
  26768. AudioUnitScope deviceScope;
  26769. AudioUnitElement deviceBus;
  26770. UInt32 channelLayoutSize;
  26771. OSStatus status;
  26772. AudioChannelLayout* pChannelLayout;
  26773. ma_result result;
  26774. MA_ASSERT(pContext != NULL);
  26775. if (deviceType == ma_device_type_playback) {
  26776. deviceScope = kAudioUnitScope_Input;
  26777. deviceBus = MA_COREAUDIO_OUTPUT_BUS;
  26778. } else {
  26779. deviceScope = kAudioUnitScope_Output;
  26780. deviceBus = MA_COREAUDIO_INPUT_BUS;
  26781. }
  26782. status = ((ma_AudioUnitGetPropertyInfo_proc)pContext->coreaudio.AudioUnitGetPropertyInfo)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, &channelLayoutSize, NULL);
  26783. if (status != noErr) {
  26784. return ma_result_from_OSStatus(status);
  26785. }
  26786. pChannelLayout = (AudioChannelLayout*)ma_malloc(channelLayoutSize, &pContext->allocationCallbacks);
  26787. if (pChannelLayout == NULL) {
  26788. return MA_OUT_OF_MEMORY;
  26789. }
  26790. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_AudioChannelLayout, deviceScope, deviceBus, pChannelLayout, &channelLayoutSize);
  26791. if (status != noErr) {
  26792. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26793. return ma_result_from_OSStatus(status);
  26794. }
  26795. result = ma_get_channel_map_from_AudioChannelLayout(pChannelLayout, pChannelMap, channelMapCap);
  26796. if (result != MA_SUCCESS) {
  26797. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26798. return result;
  26799. }
  26800. ma_free(pChannelLayout, &pContext->allocationCallbacks);
  26801. return MA_SUCCESS;
  26802. }
  26803. #endif /* MA_APPLE_DESKTOP */
  26804. #if !defined(MA_APPLE_DESKTOP)
  26805. static void ma_AVAudioSessionPortDescription_to_device_info(AVAudioSessionPortDescription* pPortDesc, ma_device_info* pInfo)
  26806. {
  26807. MA_ZERO_OBJECT(pInfo);
  26808. ma_strncpy_s(pInfo->name, sizeof(pInfo->name), [pPortDesc.portName UTF8String], (size_t)-1);
  26809. ma_strncpy_s(pInfo->id.coreaudio, sizeof(pInfo->id.coreaudio), [pPortDesc.UID UTF8String], (size_t)-1);
  26810. }
  26811. #endif
  26812. static ma_result ma_context_enumerate_devices__coreaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  26813. {
  26814. #if defined(MA_APPLE_DESKTOP)
  26815. UInt32 deviceCount;
  26816. AudioObjectID* pDeviceObjectIDs;
  26817. AudioObjectID defaultDeviceObjectIDPlayback;
  26818. AudioObjectID defaultDeviceObjectIDCapture;
  26819. ma_result result;
  26820. UInt32 iDevice;
  26821. ma_find_default_AudioObjectID(pContext, ma_device_type_playback, &defaultDeviceObjectIDPlayback); /* OK if this fails. */
  26822. ma_find_default_AudioObjectID(pContext, ma_device_type_capture, &defaultDeviceObjectIDCapture); /* OK if this fails. */
  26823. result = ma_get_device_object_ids__coreaudio(pContext, &deviceCount, &pDeviceObjectIDs);
  26824. if (result != MA_SUCCESS) {
  26825. return result;
  26826. }
  26827. for (iDevice = 0; iDevice < deviceCount; ++iDevice) {
  26828. AudioObjectID deviceObjectID = pDeviceObjectIDs[iDevice];
  26829. ma_device_info info;
  26830. MA_ZERO_OBJECT(&info);
  26831. if (ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(info.id.coreaudio), info.id.coreaudio) != MA_SUCCESS) {
  26832. continue;
  26833. }
  26834. if (ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(info.name), info.name) != MA_SUCCESS) {
  26835. continue;
  26836. }
  26837. if (ma_does_AudioObject_support_playback(pContext, deviceObjectID)) {
  26838. if (deviceObjectID == defaultDeviceObjectIDPlayback) {
  26839. info.isDefault = MA_TRUE;
  26840. }
  26841. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  26842. break;
  26843. }
  26844. }
  26845. if (ma_does_AudioObject_support_capture(pContext, deviceObjectID)) {
  26846. if (deviceObjectID == defaultDeviceObjectIDCapture) {
  26847. info.isDefault = MA_TRUE;
  26848. }
  26849. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  26850. break;
  26851. }
  26852. }
  26853. }
  26854. ma_free(pDeviceObjectIDs, &pContext->allocationCallbacks);
  26855. #else
  26856. ma_device_info info;
  26857. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  26858. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  26859. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  26860. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  26861. if (!callback(pContext, ma_device_type_playback, &info, pUserData)) {
  26862. return MA_SUCCESS;
  26863. }
  26864. }
  26865. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  26866. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, &info);
  26867. if (!callback(pContext, ma_device_type_capture, &info, pUserData)) {
  26868. return MA_SUCCESS;
  26869. }
  26870. }
  26871. #endif
  26872. return MA_SUCCESS;
  26873. }
  26874. 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)
  26875. {
  26876. ma_result result;
  26877. MA_ASSERT(pContext != NULL);
  26878. #if defined(MA_APPLE_DESKTOP)
  26879. /* Desktop */
  26880. {
  26881. AudioObjectID deviceObjectID;
  26882. AudioObjectID defaultDeviceObjectID;
  26883. UInt32 streamDescriptionCount;
  26884. AudioStreamRangedDescription* pStreamDescriptions;
  26885. UInt32 iStreamDescription;
  26886. UInt32 sampleRateRangeCount;
  26887. AudioValueRange* pSampleRateRanges;
  26888. ma_find_default_AudioObjectID(pContext, deviceType, &defaultDeviceObjectID); /* OK if this fails. */
  26889. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  26890. if (result != MA_SUCCESS) {
  26891. return result;
  26892. }
  26893. result = ma_get_AudioObject_uid(pContext, deviceObjectID, sizeof(pDeviceInfo->id.coreaudio), pDeviceInfo->id.coreaudio);
  26894. if (result != MA_SUCCESS) {
  26895. return result;
  26896. }
  26897. result = ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pDeviceInfo->name), pDeviceInfo->name);
  26898. if (result != MA_SUCCESS) {
  26899. return result;
  26900. }
  26901. if (deviceObjectID == defaultDeviceObjectID) {
  26902. pDeviceInfo->isDefault = MA_TRUE;
  26903. }
  26904. /*
  26905. There could be a large number of permutations here. Fortunately there is only a single channel count
  26906. being reported which reduces this quite a bit. For sample rates we're only reporting those that are
  26907. one of miniaudio's recognized "standard" rates. If there are still more formats than can fit into
  26908. our fixed sized array we'll just need to truncate them. This is unlikely and will probably only happen
  26909. if some driver performs software data conversion and therefore reports every possible format and
  26910. sample rate.
  26911. */
  26912. pDeviceInfo->nativeDataFormatCount = 0;
  26913. /* Formats. */
  26914. {
  26915. ma_format uniqueFormats[ma_format_count];
  26916. ma_uint32 uniqueFormatCount = 0;
  26917. ma_uint32 channels;
  26918. /* Channels. */
  26919. result = ma_get_AudioObject_channel_count(pContext, deviceObjectID, deviceType, &channels);
  26920. if (result != MA_SUCCESS) {
  26921. return result;
  26922. }
  26923. /* Formats. */
  26924. result = ma_get_AudioObject_stream_descriptions(pContext, deviceObjectID, deviceType, &streamDescriptionCount, &pStreamDescriptions);
  26925. if (result != MA_SUCCESS) {
  26926. return result;
  26927. }
  26928. for (iStreamDescription = 0; iStreamDescription < streamDescriptionCount; ++iStreamDescription) {
  26929. ma_format format;
  26930. ma_bool32 hasFormatBeenHandled = MA_FALSE;
  26931. ma_uint32 iOutputFormat;
  26932. ma_uint32 iSampleRate;
  26933. result = ma_format_from_AudioStreamBasicDescription(&pStreamDescriptions[iStreamDescription].mFormat, &format);
  26934. if (result != MA_SUCCESS) {
  26935. continue;
  26936. }
  26937. MA_ASSERT(format != ma_format_unknown);
  26938. /* Make sure the format isn't already in the output list. */
  26939. for (iOutputFormat = 0; iOutputFormat < uniqueFormatCount; ++iOutputFormat) {
  26940. if (uniqueFormats[iOutputFormat] == format) {
  26941. hasFormatBeenHandled = MA_TRUE;
  26942. break;
  26943. }
  26944. }
  26945. /* If we've already handled this format just skip it. */
  26946. if (hasFormatBeenHandled) {
  26947. continue;
  26948. }
  26949. uniqueFormats[uniqueFormatCount] = format;
  26950. uniqueFormatCount += 1;
  26951. /* Sample Rates */
  26952. result = ma_get_AudioObject_sample_rates(pContext, deviceObjectID, deviceType, &sampleRateRangeCount, &pSampleRateRanges);
  26953. if (result != MA_SUCCESS) {
  26954. return result;
  26955. }
  26956. /*
  26957. Annoyingly Core Audio reports a sample rate range. We just get all the standard rates that are
  26958. between this range.
  26959. */
  26960. for (iSampleRate = 0; iSampleRate < sampleRateRangeCount; ++iSampleRate) {
  26961. ma_uint32 iStandardSampleRate;
  26962. for (iStandardSampleRate = 0; iStandardSampleRate < ma_countof(g_maStandardSampleRatePriorities); iStandardSampleRate += 1) {
  26963. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iStandardSampleRate];
  26964. if (standardSampleRate >= pSampleRateRanges[iSampleRate].mMinimum && standardSampleRate <= pSampleRateRanges[iSampleRate].mMaximum) {
  26965. /* We have a new data format. Add it to the list. */
  26966. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  26967. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  26968. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = standardSampleRate;
  26969. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  26970. pDeviceInfo->nativeDataFormatCount += 1;
  26971. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  26972. break; /* No more room for any more formats. */
  26973. }
  26974. }
  26975. }
  26976. }
  26977. ma_free(pSampleRateRanges, &pContext->allocationCallbacks);
  26978. if (pDeviceInfo->nativeDataFormatCount >= ma_countof(pDeviceInfo->nativeDataFormats)) {
  26979. break; /* No more room for any more formats. */
  26980. }
  26981. }
  26982. ma_free(pStreamDescriptions, &pContext->allocationCallbacks);
  26983. }
  26984. }
  26985. #else
  26986. /* Mobile */
  26987. {
  26988. AudioComponentDescription desc;
  26989. AudioComponent component;
  26990. AudioUnit audioUnit;
  26991. OSStatus status;
  26992. AudioUnitScope formatScope;
  26993. AudioUnitElement formatElement;
  26994. AudioStreamBasicDescription bestFormat;
  26995. UInt32 propSize;
  26996. /* We want to ensure we use a consistent device name to device enumeration. */
  26997. if (pDeviceID != NULL && pDeviceID->coreaudio[0] != '\0') {
  26998. ma_bool32 found = MA_FALSE;
  26999. if (deviceType == ma_device_type_playback) {
  27000. NSArray *pOutputs = [[[AVAudioSession sharedInstance] currentRoute] outputs];
  27001. for (AVAudioSessionPortDescription* pPortDesc in pOutputs) {
  27002. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27003. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27004. found = MA_TRUE;
  27005. break;
  27006. }
  27007. }
  27008. } else {
  27009. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27010. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27011. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27012. ma_AVAudioSessionPortDescription_to_device_info(pPortDesc, pDeviceInfo);
  27013. found = MA_TRUE;
  27014. break;
  27015. }
  27016. }
  27017. }
  27018. if (!found) {
  27019. return MA_DOES_NOT_EXIST;
  27020. }
  27021. } else {
  27022. if (deviceType == ma_device_type_playback) {
  27023. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  27024. } else {
  27025. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  27026. }
  27027. }
  27028. /*
  27029. Retrieving device information is more annoying on mobile than desktop. For simplicity I'm locking this down to whatever format is
  27030. 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
  27031. retrieve from the AVAudioSession shared instance.
  27032. */
  27033. desc.componentType = kAudioUnitType_Output;
  27034. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  27035. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  27036. desc.componentFlags = 0;
  27037. desc.componentFlagsMask = 0;
  27038. component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  27039. if (component == NULL) {
  27040. return MA_FAILED_TO_INIT_BACKEND;
  27041. }
  27042. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)(component, &audioUnit);
  27043. if (status != noErr) {
  27044. return ma_result_from_OSStatus(status);
  27045. }
  27046. formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  27047. formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  27048. propSize = sizeof(bestFormat);
  27049. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, &propSize);
  27050. if (status != noErr) {
  27051. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27052. return ma_result_from_OSStatus(status);
  27053. }
  27054. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(audioUnit);
  27055. audioUnit = NULL;
  27056. /* Only a single format is being reported for iOS. */
  27057. pDeviceInfo->nativeDataFormatCount = 1;
  27058. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pDeviceInfo->nativeDataFormats[0].format);
  27059. if (result != MA_SUCCESS) {
  27060. return result;
  27061. }
  27062. pDeviceInfo->nativeDataFormats[0].channels = bestFormat.mChannelsPerFrame;
  27063. /*
  27064. It looks like Apple are wanting to push the whole AVAudioSession thing. Thus, we need to use that to determine device settings. To do
  27065. this we just get the shared instance and inspect.
  27066. */
  27067. @autoreleasepool {
  27068. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  27069. MA_ASSERT(pAudioSession != NULL);
  27070. pDeviceInfo->nativeDataFormats[0].sampleRate = (ma_uint32)pAudioSession.sampleRate;
  27071. }
  27072. }
  27073. #endif
  27074. (void)pDeviceInfo; /* Unused. */
  27075. return MA_SUCCESS;
  27076. }
  27077. static AudioBufferList* ma_allocate_AudioBufferList__coreaudio(ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout, const ma_allocation_callbacks* pAllocationCallbacks)
  27078. {
  27079. AudioBufferList* pBufferList;
  27080. UInt32 audioBufferSizeInBytes;
  27081. size_t allocationSize;
  27082. MA_ASSERT(sizeInFrames > 0);
  27083. MA_ASSERT(format != ma_format_unknown);
  27084. MA_ASSERT(channels > 0);
  27085. allocationSize = sizeof(AudioBufferList) - sizeof(AudioBuffer); /* Subtract sizeof(AudioBuffer) because that part is dynamically sized. */
  27086. if (layout == ma_stream_layout_interleaved) {
  27087. /* Interleaved case. This is the simple case because we just have one buffer. */
  27088. allocationSize += sizeof(AudioBuffer) * 1;
  27089. } else {
  27090. /* Non-interleaved case. This is the more complex case because there's more than one buffer. */
  27091. allocationSize += sizeof(AudioBuffer) * channels;
  27092. }
  27093. allocationSize += sizeInFrames * ma_get_bytes_per_frame(format, channels);
  27094. pBufferList = (AudioBufferList*)ma_malloc(allocationSize, pAllocationCallbacks);
  27095. if (pBufferList == NULL) {
  27096. return NULL;
  27097. }
  27098. audioBufferSizeInBytes = (UInt32)(sizeInFrames * ma_get_bytes_per_sample(format));
  27099. if (layout == ma_stream_layout_interleaved) {
  27100. pBufferList->mNumberBuffers = 1;
  27101. pBufferList->mBuffers[0].mNumberChannels = channels;
  27102. pBufferList->mBuffers[0].mDataByteSize = audioBufferSizeInBytes * channels;
  27103. pBufferList->mBuffers[0].mData = (ma_uint8*)pBufferList + sizeof(AudioBufferList);
  27104. } else {
  27105. ma_uint32 iBuffer;
  27106. pBufferList->mNumberBuffers = channels;
  27107. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  27108. pBufferList->mBuffers[iBuffer].mNumberChannels = 1;
  27109. pBufferList->mBuffers[iBuffer].mDataByteSize = audioBufferSizeInBytes;
  27110. pBufferList->mBuffers[iBuffer].mData = (ma_uint8*)pBufferList + ((sizeof(AudioBufferList) - sizeof(AudioBuffer)) + (sizeof(AudioBuffer) * channels)) + (audioBufferSizeInBytes * iBuffer);
  27111. }
  27112. }
  27113. return pBufferList;
  27114. }
  27115. static ma_result ma_device_realloc_AudioBufferList__coreaudio(ma_device* pDevice, ma_uint32 sizeInFrames, ma_format format, ma_uint32 channels, ma_stream_layout layout)
  27116. {
  27117. MA_ASSERT(pDevice != NULL);
  27118. MA_ASSERT(format != ma_format_unknown);
  27119. MA_ASSERT(channels > 0);
  27120. /* Only resize the buffer if necessary. */
  27121. if (pDevice->coreaudio.audioBufferCapInFrames < sizeInFrames) {
  27122. AudioBufferList* pNewAudioBufferList;
  27123. pNewAudioBufferList = ma_allocate_AudioBufferList__coreaudio(sizeInFrames, format, channels, layout, &pDevice->pContext->allocationCallbacks);
  27124. if (pNewAudioBufferList == NULL) {
  27125. return MA_OUT_OF_MEMORY;
  27126. }
  27127. /* At this point we'll have a new AudioBufferList and we can free the old one. */
  27128. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  27129. pDevice->coreaudio.pAudioBufferList = pNewAudioBufferList;
  27130. pDevice->coreaudio.audioBufferCapInFrames = sizeInFrames;
  27131. }
  27132. /* Getting here means the capacity of the audio is fine. */
  27133. return MA_SUCCESS;
  27134. }
  27135. static OSStatus ma_on_output__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pBufferList)
  27136. {
  27137. ma_device* pDevice = (ma_device*)pUserData;
  27138. ma_stream_layout layout;
  27139. MA_ASSERT(pDevice != NULL);
  27140. /*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);*/
  27141. /* 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. */
  27142. layout = ma_stream_layout_interleaved;
  27143. if (pBufferList->mBuffers[0].mNumberChannels != pDevice->playback.internalChannels) {
  27144. layout = ma_stream_layout_deinterleaved;
  27145. }
  27146. if (layout == ma_stream_layout_interleaved) {
  27147. /* For now we can assume everything is interleaved. */
  27148. UInt32 iBuffer;
  27149. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; ++iBuffer) {
  27150. if (pBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->playback.internalChannels) {
  27151. ma_uint32 frameCountForThisBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  27152. if (frameCountForThisBuffer > 0) {
  27153. ma_device_handle_backend_data_callback(pDevice, pBufferList->mBuffers[iBuffer].mData, NULL, frameCountForThisBuffer);
  27154. }
  27155. /*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);*/
  27156. } else {
  27157. /*
  27158. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  27159. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams. We just
  27160. output silence here.
  27161. */
  27162. MA_ZERO_MEMORY(pBufferList->mBuffers[iBuffer].mData, pBufferList->mBuffers[iBuffer].mDataByteSize);
  27163. /*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);*/
  27164. }
  27165. }
  27166. } else {
  27167. /* This is the deinterleaved case. We need to update each buffer in groups of internalChannels. This assumes each buffer is the same size. */
  27168. MA_ASSERT(pDevice->playback.internalChannels <= MA_MAX_CHANNELS); /* This should heve been validated at initialization time. */
  27169. /*
  27170. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  27171. very strange has happened and we're not going to support it.
  27172. */
  27173. if ((pBufferList->mNumberBuffers % pDevice->playback.internalChannels) == 0) {
  27174. ma_uint8 tempBuffer[4096];
  27175. UInt32 iBuffer;
  27176. for (iBuffer = 0; iBuffer < pBufferList->mNumberBuffers; iBuffer += pDevice->playback.internalChannels) {
  27177. ma_uint32 frameCountPerBuffer = pBufferList->mBuffers[iBuffer].mDataByteSize / ma_get_bytes_per_sample(pDevice->playback.internalFormat);
  27178. ma_uint32 framesRemaining = frameCountPerBuffer;
  27179. while (framesRemaining > 0) {
  27180. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  27181. ma_uint32 iChannel;
  27182. ma_uint32 framesToRead = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  27183. if (framesToRead > framesRemaining) {
  27184. framesToRead = framesRemaining;
  27185. }
  27186. ma_device_handle_backend_data_callback(pDevice, tempBuffer, NULL, framesToRead);
  27187. for (iChannel = 0; iChannel < pDevice->playback.internalChannels; ++iChannel) {
  27188. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pBufferList->mBuffers[iBuffer+iChannel].mData, (frameCountPerBuffer - framesRemaining) * ma_get_bytes_per_sample(pDevice->playback.internalFormat));
  27189. }
  27190. ma_deinterleave_pcm_frames(pDevice->playback.internalFormat, pDevice->playback.internalChannels, framesToRead, tempBuffer, ppDeinterleavedBuffers);
  27191. framesRemaining -= framesToRead;
  27192. }
  27193. }
  27194. }
  27195. }
  27196. (void)pActionFlags;
  27197. (void)pTimeStamp;
  27198. (void)busNumber;
  27199. (void)frameCount;
  27200. return noErr;
  27201. }
  27202. static OSStatus ma_on_input__coreaudio(void* pUserData, AudioUnitRenderActionFlags* pActionFlags, const AudioTimeStamp* pTimeStamp, UInt32 busNumber, UInt32 frameCount, AudioBufferList* pUnusedBufferList)
  27203. {
  27204. ma_device* pDevice = (ma_device*)pUserData;
  27205. AudioBufferList* pRenderedBufferList;
  27206. ma_result result;
  27207. ma_stream_layout layout;
  27208. ma_uint32 iBuffer;
  27209. OSStatus status;
  27210. MA_ASSERT(pDevice != NULL);
  27211. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  27212. MA_ASSERT(pRenderedBufferList);
  27213. /* 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. */
  27214. layout = ma_stream_layout_interleaved;
  27215. if (pRenderedBufferList->mBuffers[0].mNumberChannels != pDevice->capture.internalChannels) {
  27216. layout = ma_stream_layout_deinterleaved;
  27217. }
  27218. /*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);*/
  27219. /*
  27220. There has been a situation reported where frame count passed into this function is greater than the capacity of
  27221. our capture buffer. There doesn't seem to be a reliable way to determine what the maximum frame count will be,
  27222. so we need to instead resort to dynamically reallocating our buffer to ensure it's large enough to capture the
  27223. number of frames requested by this callback.
  27224. */
  27225. result = ma_device_realloc_AudioBufferList__coreaudio(pDevice, frameCount, pDevice->capture.internalFormat, pDevice->capture.internalChannels, layout);
  27226. if (result != MA_SUCCESS) {
  27227. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "Failed to allocate AudioBufferList for capture.\n");
  27228. return noErr;
  27229. }
  27230. pRenderedBufferList = (AudioBufferList*)pDevice->coreaudio.pAudioBufferList;
  27231. MA_ASSERT(pRenderedBufferList);
  27232. /*
  27233. When you call AudioUnitRender(), Core Audio tries to be helpful by setting the mDataByteSize to the number of bytes
  27234. that were actually rendered. The problem with this is that the next call can fail with -50 due to the size no longer
  27235. being set to the capacity of the buffer, but instead the size in bytes of the previous render. This will cause a
  27236. problem when a future call to this callback specifies a larger number of frames.
  27237. To work around this we need to explicitly set the size of each buffer to their respective size in bytes.
  27238. */
  27239. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  27240. pRenderedBufferList->mBuffers[iBuffer].mDataByteSize = pDevice->coreaudio.audioBufferCapInFrames * ma_get_bytes_per_sample(pDevice->capture.internalFormat) * pRenderedBufferList->mBuffers[iBuffer].mNumberChannels;
  27241. }
  27242. status = ((ma_AudioUnitRender_proc)pDevice->pContext->coreaudio.AudioUnitRender)((AudioUnit)pDevice->coreaudio.audioUnitCapture, pActionFlags, pTimeStamp, busNumber, frameCount, pRenderedBufferList);
  27243. if (status != noErr) {
  27244. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " ERROR: AudioUnitRender() failed with %d.\n", (int)status);
  27245. return status;
  27246. }
  27247. if (layout == ma_stream_layout_interleaved) {
  27248. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; ++iBuffer) {
  27249. if (pRenderedBufferList->mBuffers[iBuffer].mNumberChannels == pDevice->capture.internalChannels) {
  27250. ma_device_handle_backend_data_callback(pDevice, NULL, pRenderedBufferList->mBuffers[iBuffer].mData, frameCount);
  27251. /*ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, " mDataByteSize=%d.\n", (int)pRenderedBufferList->mBuffers[iBuffer].mDataByteSize);*/
  27252. } else {
  27253. /*
  27254. This case is where the number of channels in the output buffer do not match our internal channels. It could mean that it's
  27255. not interleaved, in which case we can't handle right now since miniaudio does not yet support non-interleaved streams.
  27256. */
  27257. ma_uint8 silentBuffer[4096];
  27258. ma_uint32 framesRemaining;
  27259. MA_ZERO_MEMORY(silentBuffer, sizeof(silentBuffer));
  27260. framesRemaining = frameCount;
  27261. while (framesRemaining > 0) {
  27262. ma_uint32 framesToSend = sizeof(silentBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  27263. if (framesToSend > framesRemaining) {
  27264. framesToSend = framesRemaining;
  27265. }
  27266. ma_device_handle_backend_data_callback(pDevice, NULL, silentBuffer, framesToSend);
  27267. framesRemaining -= framesToSend;
  27268. }
  27269. /*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);*/
  27270. }
  27271. }
  27272. } else {
  27273. /* 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. */
  27274. MA_ASSERT(pDevice->capture.internalChannels <= MA_MAX_CHANNELS); /* This should have been validated at initialization time. */
  27275. /*
  27276. For safety we'll check that the internal channels is a multiple of the buffer count. If it's not it means something
  27277. very strange has happened and we're not going to support it.
  27278. */
  27279. if ((pRenderedBufferList->mNumberBuffers % pDevice->capture.internalChannels) == 0) {
  27280. ma_uint8 tempBuffer[4096];
  27281. for (iBuffer = 0; iBuffer < pRenderedBufferList->mNumberBuffers; iBuffer += pDevice->capture.internalChannels) {
  27282. ma_uint32 framesRemaining = frameCount;
  27283. while (framesRemaining > 0) {
  27284. void* ppDeinterleavedBuffers[MA_MAX_CHANNELS];
  27285. ma_uint32 iChannel;
  27286. ma_uint32 framesToSend = sizeof(tempBuffer) / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  27287. if (framesToSend > framesRemaining) {
  27288. framesToSend = framesRemaining;
  27289. }
  27290. for (iChannel = 0; iChannel < pDevice->capture.internalChannels; ++iChannel) {
  27291. ppDeinterleavedBuffers[iChannel] = (void*)ma_offset_ptr(pRenderedBufferList->mBuffers[iBuffer+iChannel].mData, (frameCount - framesRemaining) * ma_get_bytes_per_sample(pDevice->capture.internalFormat));
  27292. }
  27293. ma_interleave_pcm_frames(pDevice->capture.internalFormat, pDevice->capture.internalChannels, framesToSend, (const void**)ppDeinterleavedBuffers, tempBuffer);
  27294. ma_device_handle_backend_data_callback(pDevice, NULL, tempBuffer, framesToSend);
  27295. framesRemaining -= framesToSend;
  27296. }
  27297. }
  27298. }
  27299. }
  27300. (void)pActionFlags;
  27301. (void)pTimeStamp;
  27302. (void)busNumber;
  27303. (void)frameCount;
  27304. (void)pUnusedBufferList;
  27305. return noErr;
  27306. }
  27307. static void on_start_stop__coreaudio(void* pUserData, AudioUnit audioUnit, AudioUnitPropertyID propertyID, AudioUnitScope scope, AudioUnitElement element)
  27308. {
  27309. ma_device* pDevice = (ma_device*)pUserData;
  27310. MA_ASSERT(pDevice != NULL);
  27311. /* Don't do anything if it looks like we're just reinitializing due to a device switch. */
  27312. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  27313. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  27314. return;
  27315. }
  27316. /*
  27317. There's been a report of a deadlock here when triggered by ma_device_uninit(). It looks like
  27318. AudioUnitGetProprty (called below) and AudioComponentInstanceDispose (called in ma_device_uninit)
  27319. can try waiting on the same lock. I'm going to try working around this by not calling any Core
  27320. Audio APIs in the callback when the device has been stopped or uninitialized.
  27321. */
  27322. 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) {
  27323. ma_device__on_notification_stopped(pDevice);
  27324. } else {
  27325. UInt32 isRunning;
  27326. UInt32 isRunningSize = sizeof(isRunning);
  27327. OSStatus status = ((ma_AudioUnitGetProperty_proc)pDevice->pContext->coreaudio.AudioUnitGetProperty)(audioUnit, kAudioOutputUnitProperty_IsRunning, scope, element, &isRunning, &isRunningSize);
  27328. if (status != noErr) {
  27329. goto done; /* Don't really know what to do in this case... just ignore it, I suppose... */
  27330. }
  27331. if (!isRunning) {
  27332. /*
  27333. 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:
  27334. 1) When the device is unplugged, this will be called _before_ the default device change notification.
  27335. 2) When the device is changed via the default device change notification, this will be called _after_ the switch.
  27336. 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.
  27337. */
  27338. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isDefaultPlaybackDevice) ||
  27339. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isDefaultCaptureDevice)) {
  27340. /*
  27341. It looks like the device is switching through an external event, such as the user unplugging the device or changing the default device
  27342. via the operating system's sound settings. If we're re-initializing the device, we just terminate because we want the stopping of the
  27343. 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
  27344. hasn't!).
  27345. */
  27346. if (((audioUnit == pDevice->coreaudio.audioUnitPlayback) && pDevice->coreaudio.isSwitchingPlaybackDevice) ||
  27347. ((audioUnit == pDevice->coreaudio.audioUnitCapture) && pDevice->coreaudio.isSwitchingCaptureDevice)) {
  27348. goto done;
  27349. }
  27350. /*
  27351. 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
  27352. 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
  27353. likely be successful in switching to the new device.
  27354. TODO: Try to predict if Core Audio will switch devices. If not, the stopped callback needs to be posted.
  27355. */
  27356. goto done;
  27357. }
  27358. /* Getting here means we need to stop the device. */
  27359. ma_device__on_notification_stopped(pDevice);
  27360. }
  27361. }
  27362. (void)propertyID; /* Unused. */
  27363. done:
  27364. /* Always signal the stop event. It's possible for the "else" case to get hit which can happen during an interruption. */
  27365. ma_event_signal(&pDevice->coreaudio.stopEvent);
  27366. }
  27367. #if defined(MA_APPLE_DESKTOP)
  27368. 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. */
  27369. static ma_uint32 g_DeviceTrackingInitCounter_CoreAudio = 0;
  27370. static ma_mutex g_DeviceTrackingMutex_CoreAudio;
  27371. static ma_device** g_ppTrackedDevices_CoreAudio = NULL;
  27372. static ma_uint32 g_TrackedDeviceCap_CoreAudio = 0;
  27373. static ma_uint32 g_TrackedDeviceCount_CoreAudio = 0;
  27374. static OSStatus ma_default_device_changed__coreaudio(AudioObjectID objectID, UInt32 addressCount, const AudioObjectPropertyAddress* pAddresses, void* pUserData)
  27375. {
  27376. ma_device_type deviceType;
  27377. /* Not sure if I really need to check this, but it makes me feel better. */
  27378. if (addressCount == 0) {
  27379. return noErr;
  27380. }
  27381. if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultOutputDevice) {
  27382. deviceType = ma_device_type_playback;
  27383. } else if (pAddresses[0].mSelector == kAudioHardwarePropertyDefaultInputDevice) {
  27384. deviceType = ma_device_type_capture;
  27385. } else {
  27386. return noErr; /* Should never hit this. */
  27387. }
  27388. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  27389. {
  27390. ma_uint32 iDevice;
  27391. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  27392. ma_result reinitResult;
  27393. ma_device* pDevice;
  27394. pDevice = g_ppTrackedDevices_CoreAudio[iDevice];
  27395. if (pDevice->type == deviceType || pDevice->type == ma_device_type_duplex) {
  27396. if (deviceType == ma_device_type_playback) {
  27397. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_TRUE;
  27398. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  27399. pDevice->coreaudio.isSwitchingPlaybackDevice = MA_FALSE;
  27400. } else {
  27401. pDevice->coreaudio.isSwitchingCaptureDevice = MA_TRUE;
  27402. reinitResult = ma_device_reinit_internal__coreaudio(pDevice, deviceType, MA_TRUE);
  27403. pDevice->coreaudio.isSwitchingCaptureDevice = MA_FALSE;
  27404. }
  27405. if (reinitResult == MA_SUCCESS) {
  27406. ma_device__post_init_setup(pDevice, deviceType);
  27407. /* Restart the device if required. If this fails we need to stop the device entirely. */
  27408. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  27409. OSStatus status;
  27410. if (deviceType == ma_device_type_playback) {
  27411. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  27412. if (status != noErr) {
  27413. if (pDevice->type == ma_device_type_duplex) {
  27414. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  27415. }
  27416. ma_device__set_state(pDevice, ma_device_state_stopped);
  27417. }
  27418. } else if (deviceType == ma_device_type_capture) {
  27419. status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  27420. if (status != noErr) {
  27421. if (pDevice->type == ma_device_type_duplex) {
  27422. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  27423. }
  27424. ma_device__set_state(pDevice, ma_device_state_stopped);
  27425. }
  27426. }
  27427. }
  27428. ma_device__on_notification_rerouted(pDevice);
  27429. }
  27430. }
  27431. }
  27432. }
  27433. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  27434. /* Unused parameters. */
  27435. (void)objectID;
  27436. (void)pUserData;
  27437. return noErr;
  27438. }
  27439. static ma_result ma_context__init_device_tracking__coreaudio(ma_context* pContext)
  27440. {
  27441. MA_ASSERT(pContext != NULL);
  27442. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  27443. {
  27444. /* Don't do anything if we've already initializd device tracking. */
  27445. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  27446. AudioObjectPropertyAddress propAddress;
  27447. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27448. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27449. ma_mutex_init(&g_DeviceTrackingMutex_CoreAudio);
  27450. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  27451. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  27452. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  27453. ((ma_AudioObjectAddPropertyListener_proc)pContext->coreaudio.AudioObjectAddPropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  27454. }
  27455. g_DeviceTrackingInitCounter_CoreAudio += 1;
  27456. }
  27457. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  27458. return MA_SUCCESS;
  27459. }
  27460. static ma_result ma_context__uninit_device_tracking__coreaudio(ma_context* pContext)
  27461. {
  27462. MA_ASSERT(pContext != NULL);
  27463. ma_spinlock_lock(&g_DeviceTrackingInitLock_CoreAudio);
  27464. {
  27465. if (g_DeviceTrackingInitCounter_CoreAudio > 0)
  27466. g_DeviceTrackingInitCounter_CoreAudio -= 1;
  27467. if (g_DeviceTrackingInitCounter_CoreAudio == 0) {
  27468. AudioObjectPropertyAddress propAddress;
  27469. propAddress.mScope = kAudioObjectPropertyScopeGlobal;
  27470. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27471. propAddress.mSelector = kAudioHardwarePropertyDefaultInputDevice;
  27472. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  27473. propAddress.mSelector = kAudioHardwarePropertyDefaultOutputDevice;
  27474. ((ma_AudioObjectRemovePropertyListener_proc)pContext->coreaudio.AudioObjectRemovePropertyListener)(kAudioObjectSystemObject, &propAddress, &ma_default_device_changed__coreaudio, NULL);
  27475. /* At this point there should be no tracked devices. If not there's an error somewhere. */
  27476. if (g_ppTrackedDevices_CoreAudio != NULL) {
  27477. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "You have uninitialized all contexts while an associated device is still active.");
  27478. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  27479. return MA_INVALID_OPERATION;
  27480. }
  27481. ma_mutex_uninit(&g_DeviceTrackingMutex_CoreAudio);
  27482. }
  27483. }
  27484. ma_spinlock_unlock(&g_DeviceTrackingInitLock_CoreAudio);
  27485. return MA_SUCCESS;
  27486. }
  27487. static ma_result ma_device__track__coreaudio(ma_device* pDevice)
  27488. {
  27489. MA_ASSERT(pDevice != NULL);
  27490. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  27491. {
  27492. /* Allocate memory if required. */
  27493. if (g_TrackedDeviceCap_CoreAudio <= g_TrackedDeviceCount_CoreAudio) {
  27494. ma_uint32 newCap;
  27495. ma_device** ppNewDevices;
  27496. newCap = g_TrackedDeviceCap_CoreAudio * 2;
  27497. if (newCap == 0) {
  27498. newCap = 1;
  27499. }
  27500. ppNewDevices = (ma_device**)ma_realloc(g_ppTrackedDevices_CoreAudio, sizeof(*g_ppTrackedDevices_CoreAudio)*newCap, &pDevice->pContext->allocationCallbacks);
  27501. if (ppNewDevices == NULL) {
  27502. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  27503. return MA_OUT_OF_MEMORY;
  27504. }
  27505. g_ppTrackedDevices_CoreAudio = ppNewDevices;
  27506. g_TrackedDeviceCap_CoreAudio = newCap;
  27507. }
  27508. g_ppTrackedDevices_CoreAudio[g_TrackedDeviceCount_CoreAudio] = pDevice;
  27509. g_TrackedDeviceCount_CoreAudio += 1;
  27510. }
  27511. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  27512. return MA_SUCCESS;
  27513. }
  27514. static ma_result ma_device__untrack__coreaudio(ma_device* pDevice)
  27515. {
  27516. MA_ASSERT(pDevice != NULL);
  27517. ma_mutex_lock(&g_DeviceTrackingMutex_CoreAudio);
  27518. {
  27519. ma_uint32 iDevice;
  27520. for (iDevice = 0; iDevice < g_TrackedDeviceCount_CoreAudio; iDevice += 1) {
  27521. if (g_ppTrackedDevices_CoreAudio[iDevice] == pDevice) {
  27522. /* We've found the device. We now need to remove it from the list. */
  27523. ma_uint32 jDevice;
  27524. for (jDevice = iDevice; jDevice < g_TrackedDeviceCount_CoreAudio-1; jDevice += 1) {
  27525. g_ppTrackedDevices_CoreAudio[jDevice] = g_ppTrackedDevices_CoreAudio[jDevice+1];
  27526. }
  27527. g_TrackedDeviceCount_CoreAudio -= 1;
  27528. /* If there's nothing else in the list we need to free memory. */
  27529. if (g_TrackedDeviceCount_CoreAudio == 0) {
  27530. ma_free(g_ppTrackedDevices_CoreAudio, &pDevice->pContext->allocationCallbacks);
  27531. g_ppTrackedDevices_CoreAudio = NULL;
  27532. g_TrackedDeviceCap_CoreAudio = 0;
  27533. }
  27534. break;
  27535. }
  27536. }
  27537. }
  27538. ma_mutex_unlock(&g_DeviceTrackingMutex_CoreAudio);
  27539. return MA_SUCCESS;
  27540. }
  27541. #endif
  27542. #if defined(MA_APPLE_MOBILE)
  27543. @interface ma_ios_notification_handler:NSObject {
  27544. ma_device* m_pDevice;
  27545. }
  27546. @end
  27547. @implementation ma_ios_notification_handler
  27548. -(id)init:(ma_device*)pDevice
  27549. {
  27550. self = [super init];
  27551. m_pDevice = pDevice;
  27552. /* For route changes. */
  27553. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_route_change:) name:AVAudioSessionRouteChangeNotification object:[AVAudioSession sharedInstance]];
  27554. /* For interruptions. */
  27555. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handle_interruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
  27556. return self;
  27557. }
  27558. -(void)dealloc
  27559. {
  27560. [self remove_handler];
  27561. #if defined(__has_feature)
  27562. #if !__has_feature(objc_arc)
  27563. [super dealloc];
  27564. #endif
  27565. #endif
  27566. }
  27567. -(void)remove_handler
  27568. {
  27569. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionRouteChangeNotification object:nil];
  27570. [[NSNotificationCenter defaultCenter] removeObserver:self name:AVAudioSessionInterruptionNotification object:nil];
  27571. }
  27572. -(void)handle_interruption:(NSNotification*)pNotification
  27573. {
  27574. NSInteger type = [[[pNotification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] integerValue];
  27575. switch (type)
  27576. {
  27577. case AVAudioSessionInterruptionTypeBegan:
  27578. {
  27579. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeBegan\n");
  27580. /*
  27581. Core Audio will have stopped the internal device automatically, but we need explicitly
  27582. stop it at a higher level to ensure miniaudio-specific state is updated for consistency.
  27583. */
  27584. ma_device_stop(m_pDevice);
  27585. /*
  27586. Fire the notification after the device has been stopped to ensure it's in the correct
  27587. state when the notification handler is invoked.
  27588. */
  27589. ma_device__on_notification_interruption_began(m_pDevice);
  27590. } break;
  27591. case AVAudioSessionInterruptionTypeEnded:
  27592. {
  27593. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Interruption: AVAudioSessionInterruptionTypeEnded\n");
  27594. ma_device__on_notification_interruption_ended(m_pDevice);
  27595. } break;
  27596. }
  27597. }
  27598. -(void)handle_route_change:(NSNotification*)pNotification
  27599. {
  27600. AVAudioSession* pSession = [AVAudioSession sharedInstance];
  27601. NSInteger reason = [[[pNotification userInfo] objectForKey:AVAudioSessionRouteChangeReasonKey] integerValue];
  27602. switch (reason)
  27603. {
  27604. case AVAudioSessionRouteChangeReasonOldDeviceUnavailable:
  27605. {
  27606. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOldDeviceUnavailable\n");
  27607. } break;
  27608. case AVAudioSessionRouteChangeReasonNewDeviceAvailable:
  27609. {
  27610. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNewDeviceAvailable\n");
  27611. } break;
  27612. case AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory:
  27613. {
  27614. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory\n");
  27615. } break;
  27616. case AVAudioSessionRouteChangeReasonWakeFromSleep:
  27617. {
  27618. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonWakeFromSleep\n");
  27619. } break;
  27620. case AVAudioSessionRouteChangeReasonOverride:
  27621. {
  27622. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonOverride\n");
  27623. } break;
  27624. case AVAudioSessionRouteChangeReasonCategoryChange:
  27625. {
  27626. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonCategoryChange\n");
  27627. } break;
  27628. case AVAudioSessionRouteChangeReasonUnknown:
  27629. default:
  27630. {
  27631. ma_log_postf(ma_device_get_log(m_pDevice), MA_LOG_LEVEL_INFO, "[Core Audio] Route Changed: AVAudioSessionRouteChangeReasonUnknown\n");
  27632. } break;
  27633. }
  27634. 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);
  27635. /* Let the application know about the route change. */
  27636. ma_device__on_notification_rerouted(m_pDevice);
  27637. }
  27638. @end
  27639. #endif
  27640. static ma_result ma_device_uninit__coreaudio(ma_device* pDevice)
  27641. {
  27642. MA_ASSERT(pDevice != NULL);
  27643. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_uninitialized);
  27644. #if defined(MA_APPLE_DESKTOP)
  27645. /*
  27646. 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
  27647. just gracefully ignore it.
  27648. */
  27649. ma_device__untrack__coreaudio(pDevice);
  27650. #endif
  27651. #if defined(MA_APPLE_MOBILE)
  27652. if (pDevice->coreaudio.pNotificationHandler != NULL) {
  27653. ma_ios_notification_handler* pNotificationHandler = (MA_BRIDGE_TRANSFER ma_ios_notification_handler*)pDevice->coreaudio.pNotificationHandler;
  27654. [pNotificationHandler remove_handler];
  27655. }
  27656. #endif
  27657. if (pDevice->coreaudio.audioUnitCapture != NULL) {
  27658. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  27659. }
  27660. if (pDevice->coreaudio.audioUnitPlayback != NULL) {
  27661. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  27662. }
  27663. if (pDevice->coreaudio.pAudioBufferList) {
  27664. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  27665. }
  27666. return MA_SUCCESS;
  27667. }
  27668. typedef struct
  27669. {
  27670. ma_bool32 allowNominalSampleRateChange;
  27671. /* Input. */
  27672. ma_format formatIn;
  27673. ma_uint32 channelsIn;
  27674. ma_uint32 sampleRateIn;
  27675. ma_channel channelMapIn[MA_MAX_CHANNELS];
  27676. ma_uint32 periodSizeInFramesIn;
  27677. ma_uint32 periodSizeInMillisecondsIn;
  27678. ma_uint32 periodsIn;
  27679. ma_share_mode shareMode;
  27680. ma_performance_profile performanceProfile;
  27681. ma_bool32 registerStopEvent;
  27682. /* Output. */
  27683. #if defined(MA_APPLE_DESKTOP)
  27684. AudioObjectID deviceObjectID;
  27685. #endif
  27686. AudioComponent component;
  27687. AudioUnit audioUnit;
  27688. AudioBufferList* pAudioBufferList; /* Only used for input devices. */
  27689. ma_format formatOut;
  27690. ma_uint32 channelsOut;
  27691. ma_uint32 sampleRateOut;
  27692. ma_channel channelMapOut[MA_MAX_CHANNELS];
  27693. ma_uint32 periodSizeInFramesOut;
  27694. ma_uint32 periodsOut;
  27695. char deviceName[256];
  27696. } ma_device_init_internal_data__coreaudio;
  27697. 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. */
  27698. {
  27699. ma_result result;
  27700. OSStatus status;
  27701. UInt32 enableIOFlag;
  27702. AudioStreamBasicDescription bestFormat;
  27703. UInt32 actualPeriodSizeInFrames;
  27704. AURenderCallbackStruct callbackInfo;
  27705. #if defined(MA_APPLE_DESKTOP)
  27706. AudioObjectID deviceObjectID;
  27707. #endif
  27708. /* This API should only be used for a single device type: playback or capture. No full-duplex mode. */
  27709. if (deviceType == ma_device_type_duplex) {
  27710. return MA_INVALID_ARGS;
  27711. }
  27712. MA_ASSERT(pContext != NULL);
  27713. MA_ASSERT(deviceType == ma_device_type_playback || deviceType == ma_device_type_capture);
  27714. #if defined(MA_APPLE_DESKTOP)
  27715. pData->deviceObjectID = 0;
  27716. #endif
  27717. pData->component = NULL;
  27718. pData->audioUnit = NULL;
  27719. pData->pAudioBufferList = NULL;
  27720. #if defined(MA_APPLE_DESKTOP)
  27721. result = ma_find_AudioObjectID(pContext, deviceType, pDeviceID, &deviceObjectID);
  27722. if (result != MA_SUCCESS) {
  27723. return result;
  27724. }
  27725. pData->deviceObjectID = deviceObjectID;
  27726. #endif
  27727. /* Core audio doesn't really use the notion of a period so we can leave this unmodified, but not too over the top. */
  27728. pData->periodsOut = pData->periodsIn;
  27729. if (pData->periodsOut == 0) {
  27730. pData->periodsOut = MA_DEFAULT_PERIODS;
  27731. }
  27732. if (pData->periodsOut > 16) {
  27733. pData->periodsOut = 16;
  27734. }
  27735. /* Audio unit. */
  27736. status = ((ma_AudioComponentInstanceNew_proc)pContext->coreaudio.AudioComponentInstanceNew)((AudioComponent)pContext->coreaudio.component, (AudioUnit*)&pData->audioUnit);
  27737. if (status != noErr) {
  27738. return ma_result_from_OSStatus(status);
  27739. }
  27740. /* 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. */
  27741. enableIOFlag = 1;
  27742. if (deviceType == ma_device_type_capture) {
  27743. enableIOFlag = 0;
  27744. }
  27745. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  27746. if (status != noErr) {
  27747. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27748. return ma_result_from_OSStatus(status);
  27749. }
  27750. enableIOFlag = (enableIOFlag == 0) ? 1 : 0;
  27751. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &enableIOFlag, sizeof(enableIOFlag));
  27752. if (status != noErr) {
  27753. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27754. return ma_result_from_OSStatus(status);
  27755. }
  27756. /* Set the device to use with this audio unit. This is only used on desktop since we are using defaults on mobile. */
  27757. #if defined(MA_APPLE_DESKTOP)
  27758. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_CurrentDevice, kAudioUnitScope_Global, 0, &deviceObjectID, sizeof(deviceObjectID));
  27759. if (status != noErr) {
  27760. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27761. return ma_result_from_OSStatus(result);
  27762. }
  27763. #else
  27764. /*
  27765. 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
  27766. 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.
  27767. */
  27768. if (pDeviceID != NULL) {
  27769. if (deviceType == ma_device_type_capture) {
  27770. ma_bool32 found = MA_FALSE;
  27771. NSArray *pInputs = [[[AVAudioSession sharedInstance] currentRoute] inputs];
  27772. for (AVAudioSessionPortDescription* pPortDesc in pInputs) {
  27773. if (strcmp(pDeviceID->coreaudio, [pPortDesc.UID UTF8String]) == 0) {
  27774. [[AVAudioSession sharedInstance] setPreferredInput:pPortDesc error:nil];
  27775. found = MA_TRUE;
  27776. break;
  27777. }
  27778. }
  27779. if (found == MA_FALSE) {
  27780. return MA_DOES_NOT_EXIST;
  27781. }
  27782. }
  27783. }
  27784. #endif
  27785. /*
  27786. Format. This is the hardest part of initialization because there's a few variables to take into account.
  27787. 1) The format must be supported by the device.
  27788. 2) The format must be supported miniaudio.
  27789. 3) There's a priority that miniaudio prefers.
  27790. 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
  27791. most important property is the sample rate. miniaudio can do format conversion for any sample rate and channel count, but cannot do the same
  27792. for the sample data format. If the sample data format is not supported by miniaudio it must be ignored completely.
  27793. On mobile platforms this is a bit different. We just force the use of whatever the audio unit's current format is set to.
  27794. */
  27795. {
  27796. AudioStreamBasicDescription origFormat;
  27797. UInt32 origFormatSize = sizeof(origFormat);
  27798. AudioUnitScope formatScope = (deviceType == ma_device_type_playback) ? kAudioUnitScope_Input : kAudioUnitScope_Output;
  27799. AudioUnitElement formatElement = (deviceType == ma_device_type_playback) ? MA_COREAUDIO_OUTPUT_BUS : MA_COREAUDIO_INPUT_BUS;
  27800. if (deviceType == ma_device_type_playback) {
  27801. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, MA_COREAUDIO_OUTPUT_BUS, &origFormat, &origFormatSize);
  27802. } else {
  27803. status = ((ma_AudioUnitGetProperty_proc)pContext->coreaudio.AudioUnitGetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, MA_COREAUDIO_INPUT_BUS, &origFormat, &origFormatSize);
  27804. }
  27805. if (status != noErr) {
  27806. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27807. return ma_result_from_OSStatus(status);
  27808. }
  27809. #if defined(MA_APPLE_DESKTOP)
  27810. result = ma_find_best_format__coreaudio(pContext, deviceObjectID, deviceType, pData->formatIn, pData->channelsIn, pData->sampleRateIn, &origFormat, &bestFormat);
  27811. if (result != MA_SUCCESS) {
  27812. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27813. return result;
  27814. }
  27815. /*
  27816. Technical Note TN2091: Device input using the HAL Output Audio Unit
  27817. https://developer.apple.com/library/archive/technotes/tn2091/_index.html
  27818. This documentation says the following:
  27819. The internal AudioConverter can handle any *simple* conversion. Typically, this means that a client can specify ANY
  27820. variant of the PCM formats. Consequently, the device's sample rate should match the desired sample rate. If sample rate
  27821. conversion is needed, it can be accomplished by buffering the input and converting the data on a separate thread with
  27822. another AudioConverter.
  27823. The important part here is the mention that it can handle *simple* conversions, which does *not* include sample rate. We
  27824. therefore want to ensure the sample rate stays consistent. This document is specifically for input, but I'm going to play it
  27825. safe and apply the same rule to output as well.
  27826. I have tried going against the documentation by setting the sample rate anyway, but this just results in AudioUnitRender()
  27827. returning a result code of -10863. I have also tried changing the format directly on the input scope on the input bus, but
  27828. this just results in `ca_require: IsStreamFormatWritable(inScope, inElement) NotWritable` when trying to set the format.
  27829. Something that does seem to work, however, has been setting the nominal sample rate on the deivce object. The problem with
  27830. this, however, is that it actually changes the sample rate at the operating system level and not just the application. This
  27831. 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
  27832. configuration option. When the `coreaudio.allowNominalSampleRateChange` config option is set to true, changing the sample
  27833. rate will be allowed. Otherwise it'll be fixed to the current sample rate. To check the system-defined sample rate, run
  27834. the Audio MIDI Setup program that comes installed on macOS and observe how the sample rate changes as the sample rate is
  27835. changed by miniaudio.
  27836. */
  27837. if (pData->allowNominalSampleRateChange) {
  27838. AudioValueRange sampleRateRange;
  27839. AudioObjectPropertyAddress propAddress;
  27840. sampleRateRange.mMinimum = bestFormat.mSampleRate;
  27841. sampleRateRange.mMaximum = bestFormat.mSampleRate;
  27842. propAddress.mSelector = kAudioDevicePropertyNominalSampleRate;
  27843. propAddress.mScope = (deviceType == ma_device_type_playback) ? kAudioObjectPropertyScopeOutput : kAudioObjectPropertyScopeInput;
  27844. propAddress.mElement = AUDIO_OBJECT_PROPERTY_ELEMENT;
  27845. status = ((ma_AudioObjectSetPropertyData_proc)pContext->coreaudio.AudioObjectSetPropertyData)(deviceObjectID, &propAddress, 0, NULL, sizeof(sampleRateRange), &sampleRateRange);
  27846. if (status != noErr) {
  27847. bestFormat.mSampleRate = origFormat.mSampleRate;
  27848. }
  27849. } else {
  27850. bestFormat.mSampleRate = origFormat.mSampleRate;
  27851. }
  27852. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  27853. if (status != noErr) {
  27854. /* We failed to set the format, so fall back to the current format of the audio unit. */
  27855. bestFormat = origFormat;
  27856. }
  27857. #else
  27858. bestFormat = origFormat;
  27859. /*
  27860. Sample rate is a little different here because for some reason kAudioUnitProperty_StreamFormat returns 0... Oh well. We need to instead try
  27861. 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
  27862. 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
  27863. can tell, it looks like the sample rate is shared between playback and capture for everything.
  27864. */
  27865. @autoreleasepool {
  27866. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  27867. MA_ASSERT(pAudioSession != NULL);
  27868. [pAudioSession setPreferredSampleRate:(double)pData->sampleRateIn error:nil];
  27869. bestFormat.mSampleRate = pAudioSession.sampleRate;
  27870. /*
  27871. I've had a report that the channel count returned by AudioUnitGetProperty above is inconsistent with
  27872. AVAudioSession outputNumberOfChannels. I'm going to try using the AVAudioSession values instead.
  27873. */
  27874. if (deviceType == ma_device_type_playback) {
  27875. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.outputNumberOfChannels;
  27876. }
  27877. if (deviceType == ma_device_type_capture) {
  27878. bestFormat.mChannelsPerFrame = (UInt32)pAudioSession.inputNumberOfChannels;
  27879. }
  27880. }
  27881. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_StreamFormat, formatScope, formatElement, &bestFormat, sizeof(bestFormat));
  27882. if (status != noErr) {
  27883. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27884. return ma_result_from_OSStatus(status);
  27885. }
  27886. #endif
  27887. result = ma_format_from_AudioStreamBasicDescription(&bestFormat, &pData->formatOut);
  27888. if (result != MA_SUCCESS) {
  27889. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27890. return result;
  27891. }
  27892. if (pData->formatOut == ma_format_unknown) {
  27893. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27894. return MA_FORMAT_NOT_SUPPORTED;
  27895. }
  27896. pData->channelsOut = bestFormat.mChannelsPerFrame;
  27897. pData->sampleRateOut = bestFormat.mSampleRate;
  27898. }
  27899. /* Clamp the channel count for safety. */
  27900. if (pData->channelsOut > MA_MAX_CHANNELS) {
  27901. pData->channelsOut = MA_MAX_CHANNELS;
  27902. }
  27903. /*
  27904. Internal channel map. This is weird in my testing. If I use the AudioObject to get the
  27905. channel map, the channel descriptions are set to "Unknown" for some reason. To work around
  27906. this it looks like retrieving it from the AudioUnit will work. However, and this is where
  27907. it gets weird, it doesn't seem to work with capture devices, nor at all on iOS... Therefore
  27908. I'm going to fall back to a default assumption in these cases.
  27909. */
  27910. #if defined(MA_APPLE_DESKTOP)
  27911. result = ma_get_AudioUnit_channel_map(pContext, pData->audioUnit, deviceType, pData->channelMapOut, pData->channelsOut);
  27912. if (result != MA_SUCCESS) {
  27913. #if 0
  27914. /* Try falling back to the channel map from the AudioObject. */
  27915. result = ma_get_AudioObject_channel_map(pContext, deviceObjectID, deviceType, pData->channelMapOut, pData->channelsOut);
  27916. if (result != MA_SUCCESS) {
  27917. return result;
  27918. }
  27919. #else
  27920. /* Fall back to default assumptions. */
  27921. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  27922. #endif
  27923. }
  27924. #else
  27925. /* TODO: Figure out how to get the channel map using AVAudioSession. */
  27926. ma_channel_map_init_standard(ma_standard_channel_map_default, pData->channelMapOut, ma_countof(pData->channelMapOut), pData->channelsOut);
  27927. #endif
  27928. /* Buffer size. Not allowing this to be configurable on iOS. */
  27929. if (pData->periodSizeInFramesIn == 0) {
  27930. if (pData->periodSizeInMillisecondsIn == 0) {
  27931. if (pData->performanceProfile == ma_performance_profile_low_latency) {
  27932. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, pData->sampleRateOut);
  27933. } else {
  27934. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, pData->sampleRateOut);
  27935. }
  27936. } else {
  27937. actualPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pData->periodSizeInMillisecondsIn, pData->sampleRateOut);
  27938. }
  27939. } else {
  27940. actualPeriodSizeInFrames = pData->periodSizeInFramesIn;
  27941. }
  27942. #if defined(MA_APPLE_DESKTOP)
  27943. result = ma_set_AudioObject_buffer_size_in_frames(pContext, deviceObjectID, deviceType, &actualPeriodSizeInFrames);
  27944. if (result != MA_SUCCESS) {
  27945. return result;
  27946. }
  27947. #else
  27948. /*
  27949. On iOS, the size of the IO buffer needs to be specified in seconds and is a floating point
  27950. number. I don't trust any potential truncation errors due to converting from float to integer
  27951. so I'm going to explicitly set the actual period size to the next power of 2.
  27952. */
  27953. @autoreleasepool {
  27954. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  27955. MA_ASSERT(pAudioSession != NULL);
  27956. [pAudioSession setPreferredIOBufferDuration:((float)actualPeriodSizeInFrames / pAudioSession.sampleRate) error:nil];
  27957. actualPeriodSizeInFrames = ma_next_power_of_2((ma_uint32)(pAudioSession.IOBufferDuration * pAudioSession.sampleRate));
  27958. }
  27959. #endif
  27960. /*
  27961. During testing I discovered that the buffer size can be too big. You'll get an error like this:
  27962. kAudioUnitErr_TooManyFramesToProcess : inFramesToProcess=4096, mMaxFramesPerSlice=512
  27963. Note how inFramesToProcess is smaller than mMaxFramesPerSlice. To fix, we need to set kAudioUnitProperty_MaximumFramesPerSlice to that
  27964. of the size of our buffer, or do it the other way around and set our buffer size to the kAudioUnitProperty_MaximumFramesPerSlice.
  27965. */
  27966. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_MaximumFramesPerSlice, kAudioUnitScope_Global, 0, &actualPeriodSizeInFrames, sizeof(actualPeriodSizeInFrames));
  27967. if (status != noErr) {
  27968. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27969. return ma_result_from_OSStatus(status);
  27970. }
  27971. pData->periodSizeInFramesOut = (ma_uint32)actualPeriodSizeInFrames;
  27972. /* We need a buffer list if this is an input device. We render into this in the input callback. */
  27973. if (deviceType == ma_device_type_capture) {
  27974. ma_bool32 isInterleaved = (bestFormat.mFormatFlags & kAudioFormatFlagIsNonInterleaved) == 0;
  27975. AudioBufferList* pBufferList;
  27976. pBufferList = ma_allocate_AudioBufferList__coreaudio(pData->periodSizeInFramesOut, pData->formatOut, pData->channelsOut, (isInterleaved) ? ma_stream_layout_interleaved : ma_stream_layout_deinterleaved, &pContext->allocationCallbacks);
  27977. if (pBufferList == NULL) {
  27978. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27979. return MA_OUT_OF_MEMORY;
  27980. }
  27981. pData->pAudioBufferList = pBufferList;
  27982. }
  27983. /* Callbacks. */
  27984. callbackInfo.inputProcRefCon = pDevice_DoNotReference;
  27985. if (deviceType == ma_device_type_playback) {
  27986. callbackInfo.inputProc = ma_on_output__coreaudio;
  27987. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  27988. if (status != noErr) {
  27989. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27990. return ma_result_from_OSStatus(status);
  27991. }
  27992. } else {
  27993. callbackInfo.inputProc = ma_on_input__coreaudio;
  27994. status = ((ma_AudioUnitSetProperty_proc)pContext->coreaudio.AudioUnitSetProperty)(pData->audioUnit, kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, 0, &callbackInfo, sizeof(callbackInfo));
  27995. if (status != noErr) {
  27996. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  27997. return ma_result_from_OSStatus(status);
  27998. }
  27999. }
  28000. /* We need to listen for stop events. */
  28001. if (pData->registerStopEvent) {
  28002. status = ((ma_AudioUnitAddPropertyListener_proc)pContext->coreaudio.AudioUnitAddPropertyListener)(pData->audioUnit, kAudioOutputUnitProperty_IsRunning, on_start_stop__coreaudio, pDevice_DoNotReference);
  28003. if (status != noErr) {
  28004. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28005. return ma_result_from_OSStatus(status);
  28006. }
  28007. }
  28008. /* Initialize the audio unit. */
  28009. status = ((ma_AudioUnitInitialize_proc)pContext->coreaudio.AudioUnitInitialize)(pData->audioUnit);
  28010. if (status != noErr) {
  28011. ma_free(pData->pAudioBufferList, &pContext->allocationCallbacks);
  28012. pData->pAudioBufferList = NULL;
  28013. ((ma_AudioComponentInstanceDispose_proc)pContext->coreaudio.AudioComponentInstanceDispose)(pData->audioUnit);
  28014. return ma_result_from_OSStatus(status);
  28015. }
  28016. /* Grab the name. */
  28017. #if defined(MA_APPLE_DESKTOP)
  28018. ma_get_AudioObject_name(pContext, deviceObjectID, sizeof(pData->deviceName), pData->deviceName);
  28019. #else
  28020. if (deviceType == ma_device_type_playback) {
  28021. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  28022. } else {
  28023. ma_strcpy_s(pData->deviceName, sizeof(pData->deviceName), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  28024. }
  28025. #endif
  28026. return result;
  28027. }
  28028. #if defined(MA_APPLE_DESKTOP)
  28029. static ma_result ma_device_reinit_internal__coreaudio(ma_device* pDevice, ma_device_type deviceType, ma_bool32 disposePreviousAudioUnit)
  28030. {
  28031. ma_device_init_internal_data__coreaudio data;
  28032. ma_result result;
  28033. /* This should only be called for playback or capture, not duplex. */
  28034. if (deviceType == ma_device_type_duplex) {
  28035. return MA_INVALID_ARGS;
  28036. }
  28037. data.allowNominalSampleRateChange = MA_FALSE; /* Don't change the nominal sample rate when switching devices. */
  28038. if (deviceType == ma_device_type_capture) {
  28039. data.formatIn = pDevice->capture.format;
  28040. data.channelsIn = pDevice->capture.channels;
  28041. data.sampleRateIn = pDevice->sampleRate;
  28042. MA_COPY_MEMORY(data.channelMapIn, pDevice->capture.channelMap, sizeof(pDevice->capture.channelMap));
  28043. data.shareMode = pDevice->capture.shareMode;
  28044. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28045. data.registerStopEvent = MA_TRUE;
  28046. if (disposePreviousAudioUnit) {
  28047. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28048. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28049. }
  28050. if (pDevice->coreaudio.pAudioBufferList) {
  28051. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28052. }
  28053. } else if (deviceType == ma_device_type_playback) {
  28054. data.formatIn = pDevice->playback.format;
  28055. data.channelsIn = pDevice->playback.channels;
  28056. data.sampleRateIn = pDevice->sampleRate;
  28057. MA_COPY_MEMORY(data.channelMapIn, pDevice->playback.channelMap, sizeof(pDevice->playback.channelMap));
  28058. data.shareMode = pDevice->playback.shareMode;
  28059. data.performanceProfile = pDevice->coreaudio.originalPerformanceProfile;
  28060. data.registerStopEvent = (pDevice->type != ma_device_type_duplex);
  28061. if (disposePreviousAudioUnit) {
  28062. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28063. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28064. }
  28065. }
  28066. data.periodSizeInFramesIn = pDevice->coreaudio.originalPeriodSizeInFrames;
  28067. data.periodSizeInMillisecondsIn = pDevice->coreaudio.originalPeriodSizeInMilliseconds;
  28068. data.periodsIn = pDevice->coreaudio.originalPeriods;
  28069. /* Need at least 3 periods for duplex. */
  28070. if (data.periodsIn < 3 && pDevice->type == ma_device_type_duplex) {
  28071. data.periodsIn = 3;
  28072. }
  28073. result = ma_device_init_internal__coreaudio(pDevice->pContext, deviceType, NULL, &data, (void*)pDevice);
  28074. if (result != MA_SUCCESS) {
  28075. return result;
  28076. }
  28077. if (deviceType == ma_device_type_capture) {
  28078. #if defined(MA_APPLE_DESKTOP)
  28079. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  28080. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  28081. #endif
  28082. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  28083. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  28084. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  28085. pDevice->capture.internalFormat = data.formatOut;
  28086. pDevice->capture.internalChannels = data.channelsOut;
  28087. pDevice->capture.internalSampleRate = data.sampleRateOut;
  28088. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28089. pDevice->capture.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  28090. pDevice->capture.internalPeriods = data.periodsOut;
  28091. } else if (deviceType == ma_device_type_playback) {
  28092. #if defined(MA_APPLE_DESKTOP)
  28093. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  28094. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  28095. #endif
  28096. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  28097. pDevice->playback.internalFormat = data.formatOut;
  28098. pDevice->playback.internalChannels = data.channelsOut;
  28099. pDevice->playback.internalSampleRate = data.sampleRateOut;
  28100. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28101. pDevice->playback.internalPeriodSizeInFrames = data.periodSizeInFramesOut;
  28102. pDevice->playback.internalPeriods = data.periodsOut;
  28103. }
  28104. return MA_SUCCESS;
  28105. }
  28106. #endif /* MA_APPLE_DESKTOP */
  28107. static ma_result ma_device_init__coreaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  28108. {
  28109. ma_result result;
  28110. MA_ASSERT(pDevice != NULL);
  28111. MA_ASSERT(pConfig != NULL);
  28112. if (pConfig->deviceType == ma_device_type_loopback) {
  28113. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  28114. }
  28115. /* No exclusive mode with the Core Audio backend for now. */
  28116. if (((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive) ||
  28117. ((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive)) {
  28118. return MA_SHARE_MODE_NOT_SUPPORTED;
  28119. }
  28120. /* Capture needs to be initialized first. */
  28121. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  28122. ma_device_init_internal_data__coreaudio data;
  28123. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  28124. data.formatIn = pDescriptorCapture->format;
  28125. data.channelsIn = pDescriptorCapture->channels;
  28126. data.sampleRateIn = pDescriptorCapture->sampleRate;
  28127. MA_COPY_MEMORY(data.channelMapIn, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  28128. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  28129. data.periodSizeInMillisecondsIn = pDescriptorCapture->periodSizeInMilliseconds;
  28130. data.periodsIn = pDescriptorCapture->periodCount;
  28131. data.shareMode = pDescriptorCapture->shareMode;
  28132. data.performanceProfile = pConfig->performanceProfile;
  28133. data.registerStopEvent = MA_TRUE;
  28134. /* Need at least 3 periods for duplex. */
  28135. if (data.periodsIn < 3 && pConfig->deviceType == ma_device_type_duplex) {
  28136. data.periodsIn = 3;
  28137. }
  28138. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_capture, pDescriptorCapture->pDeviceID, &data, (void*)pDevice);
  28139. if (result != MA_SUCCESS) {
  28140. return result;
  28141. }
  28142. pDevice->coreaudio.isDefaultCaptureDevice = (pConfig->capture.pDeviceID == NULL);
  28143. #if defined(MA_APPLE_DESKTOP)
  28144. pDevice->coreaudio.deviceObjectIDCapture = (ma_uint32)data.deviceObjectID;
  28145. #endif
  28146. pDevice->coreaudio.audioUnitCapture = (ma_ptr)data.audioUnit;
  28147. pDevice->coreaudio.pAudioBufferList = (ma_ptr)data.pAudioBufferList;
  28148. pDevice->coreaudio.audioBufferCapInFrames = data.periodSizeInFramesOut;
  28149. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  28150. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorCapture->periodSizeInMilliseconds;
  28151. pDevice->coreaudio.originalPeriods = pDescriptorCapture->periodCount;
  28152. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  28153. pDescriptorCapture->format = data.formatOut;
  28154. pDescriptorCapture->channels = data.channelsOut;
  28155. pDescriptorCapture->sampleRate = data.sampleRateOut;
  28156. MA_COPY_MEMORY(pDescriptorCapture->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28157. pDescriptorCapture->periodSizeInFrames = data.periodSizeInFramesOut;
  28158. pDescriptorCapture->periodCount = data.periodsOut;
  28159. #if defined(MA_APPLE_DESKTOP)
  28160. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDCapture, sizeof(pDevice->capture.id.coreaudio), pDevice->capture.id.coreaudio);
  28161. /*
  28162. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  28163. switch the device in the background.
  28164. */
  28165. if (pConfig->capture.pDeviceID == NULL) {
  28166. ma_device__track__coreaudio(pDevice);
  28167. }
  28168. #endif
  28169. }
  28170. /* Playback. */
  28171. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  28172. ma_device_init_internal_data__coreaudio data;
  28173. data.allowNominalSampleRateChange = pConfig->coreaudio.allowNominalSampleRateChange;
  28174. data.formatIn = pDescriptorPlayback->format;
  28175. data.channelsIn = pDescriptorPlayback->channels;
  28176. data.sampleRateIn = pDescriptorPlayback->sampleRate;
  28177. MA_COPY_MEMORY(data.channelMapIn, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  28178. data.shareMode = pDescriptorPlayback->shareMode;
  28179. data.performanceProfile = pConfig->performanceProfile;
  28180. /* In full-duplex mode we want the playback buffer to be the same size as the capture buffer. */
  28181. if (pConfig->deviceType == ma_device_type_duplex) {
  28182. data.periodSizeInFramesIn = pDescriptorCapture->periodSizeInFrames;
  28183. data.periodsIn = pDescriptorCapture->periodCount;
  28184. data.registerStopEvent = MA_FALSE;
  28185. } else {
  28186. data.periodSizeInFramesIn = pDescriptorPlayback->periodSizeInFrames;
  28187. data.periodSizeInMillisecondsIn = pDescriptorPlayback->periodSizeInMilliseconds;
  28188. data.periodsIn = pDescriptorPlayback->periodCount;
  28189. data.registerStopEvent = MA_TRUE;
  28190. }
  28191. result = ma_device_init_internal__coreaudio(pDevice->pContext, ma_device_type_playback, pDescriptorPlayback->pDeviceID, &data, (void*)pDevice);
  28192. if (result != MA_SUCCESS) {
  28193. if (pConfig->deviceType == ma_device_type_duplex) {
  28194. ((ma_AudioComponentInstanceDispose_proc)pDevice->pContext->coreaudio.AudioComponentInstanceDispose)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28195. if (pDevice->coreaudio.pAudioBufferList) {
  28196. ma_free(pDevice->coreaudio.pAudioBufferList, &pDevice->pContext->allocationCallbacks);
  28197. }
  28198. }
  28199. return result;
  28200. }
  28201. pDevice->coreaudio.isDefaultPlaybackDevice = (pConfig->playback.pDeviceID == NULL);
  28202. #if defined(MA_APPLE_DESKTOP)
  28203. pDevice->coreaudio.deviceObjectIDPlayback = (ma_uint32)data.deviceObjectID;
  28204. #endif
  28205. pDevice->coreaudio.audioUnitPlayback = (ma_ptr)data.audioUnit;
  28206. pDevice->coreaudio.originalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  28207. pDevice->coreaudio.originalPeriodSizeInMilliseconds = pDescriptorPlayback->periodSizeInMilliseconds;
  28208. pDevice->coreaudio.originalPeriods = pDescriptorPlayback->periodCount;
  28209. pDevice->coreaudio.originalPerformanceProfile = pConfig->performanceProfile;
  28210. pDescriptorPlayback->format = data.formatOut;
  28211. pDescriptorPlayback->channels = data.channelsOut;
  28212. pDescriptorPlayback->sampleRate = data.sampleRateOut;
  28213. MA_COPY_MEMORY(pDescriptorPlayback->channelMap, data.channelMapOut, sizeof(data.channelMapOut));
  28214. pDescriptorPlayback->periodSizeInFrames = data.periodSizeInFramesOut;
  28215. pDescriptorPlayback->periodCount = data.periodsOut;
  28216. #if defined(MA_APPLE_DESKTOP)
  28217. ma_get_AudioObject_uid(pDevice->pContext, pDevice->coreaudio.deviceObjectIDPlayback, sizeof(pDevice->playback.id.coreaudio), pDevice->playback.id.coreaudio);
  28218. /*
  28219. If we are using the default device we'll need to listen for changes to the system's default device so we can seemlessly
  28220. switch the device in the background.
  28221. */
  28222. if (pDescriptorPlayback->pDeviceID == NULL && (pConfig->deviceType != ma_device_type_duplex || pDescriptorCapture->pDeviceID != NULL)) {
  28223. ma_device__track__coreaudio(pDevice);
  28224. }
  28225. #endif
  28226. }
  28227. /*
  28228. When stopping the device, a callback is called on another thread. We need to wait for this callback
  28229. before returning from ma_device_stop(). This event is used for this.
  28230. */
  28231. ma_event_init(&pDevice->coreaudio.stopEvent);
  28232. /*
  28233. We need to detect when a route has changed so we can update the data conversion pipeline accordingly. This is done
  28234. differently on non-Desktop Apple platforms.
  28235. */
  28236. #if defined(MA_APPLE_MOBILE)
  28237. pDevice->coreaudio.pNotificationHandler = (MA_BRIDGE_RETAINED void*)[[ma_ios_notification_handler alloc] init:pDevice];
  28238. #endif
  28239. return MA_SUCCESS;
  28240. }
  28241. static ma_result ma_device_start__coreaudio(ma_device* pDevice)
  28242. {
  28243. MA_ASSERT(pDevice != NULL);
  28244. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  28245. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28246. if (status != noErr) {
  28247. return ma_result_from_OSStatus(status);
  28248. }
  28249. }
  28250. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  28251. OSStatus status = ((ma_AudioOutputUnitStart_proc)pDevice->pContext->coreaudio.AudioOutputUnitStart)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28252. if (status != noErr) {
  28253. if (pDevice->type == ma_device_type_duplex) {
  28254. ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28255. }
  28256. return ma_result_from_OSStatus(status);
  28257. }
  28258. }
  28259. return MA_SUCCESS;
  28260. }
  28261. static ma_result ma_device_stop__coreaudio(ma_device* pDevice)
  28262. {
  28263. MA_ASSERT(pDevice != NULL);
  28264. /* It's not clear from the documentation whether or not AudioOutputUnitStop() actually drains the device or not. */
  28265. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  28266. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitCapture);
  28267. if (status != noErr) {
  28268. return ma_result_from_OSStatus(status);
  28269. }
  28270. }
  28271. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  28272. OSStatus status = ((ma_AudioOutputUnitStop_proc)pDevice->pContext->coreaudio.AudioOutputUnitStop)((AudioUnit)pDevice->coreaudio.audioUnitPlayback);
  28273. if (status != noErr) {
  28274. return ma_result_from_OSStatus(status);
  28275. }
  28276. }
  28277. /* We need to wait for the callback to finish before returning. */
  28278. ma_event_wait(&pDevice->coreaudio.stopEvent);
  28279. return MA_SUCCESS;
  28280. }
  28281. static ma_result ma_context_uninit__coreaudio(ma_context* pContext)
  28282. {
  28283. MA_ASSERT(pContext != NULL);
  28284. MA_ASSERT(pContext->backend == ma_backend_coreaudio);
  28285. #if defined(MA_APPLE_MOBILE)
  28286. if (!pContext->coreaudio.noAudioSessionDeactivate) {
  28287. if (![[AVAudioSession sharedInstance] setActive:false error:nil]) {
  28288. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to deactivate audio session.");
  28289. return MA_FAILED_TO_INIT_BACKEND;
  28290. }
  28291. }
  28292. #endif
  28293. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  28294. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  28295. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  28296. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28297. #endif
  28298. #if !defined(MA_APPLE_MOBILE)
  28299. ma_context__uninit_device_tracking__coreaudio(pContext);
  28300. #endif
  28301. (void)pContext;
  28302. return MA_SUCCESS;
  28303. }
  28304. #if defined(MA_APPLE_MOBILE) && defined(__IPHONE_12_0)
  28305. static AVAudioSessionCategory ma_to_AVAudioSessionCategory(ma_ios_session_category category)
  28306. {
  28307. /* The "default" and "none" categories are treated different and should not be used as an input into this function. */
  28308. MA_ASSERT(category != ma_ios_session_category_default);
  28309. MA_ASSERT(category != ma_ios_session_category_none);
  28310. switch (category) {
  28311. case ma_ios_session_category_ambient: return AVAudioSessionCategoryAmbient;
  28312. case ma_ios_session_category_solo_ambient: return AVAudioSessionCategorySoloAmbient;
  28313. case ma_ios_session_category_playback: return AVAudioSessionCategoryPlayback;
  28314. case ma_ios_session_category_record: return AVAudioSessionCategoryRecord;
  28315. case ma_ios_session_category_play_and_record: return AVAudioSessionCategoryPlayAndRecord;
  28316. case ma_ios_session_category_multi_route: return AVAudioSessionCategoryMultiRoute;
  28317. case ma_ios_session_category_none: return AVAudioSessionCategoryAmbient;
  28318. case ma_ios_session_category_default: return AVAudioSessionCategoryAmbient;
  28319. default: return AVAudioSessionCategoryAmbient;
  28320. }
  28321. }
  28322. #endif
  28323. static ma_result ma_context_init__coreaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  28324. {
  28325. #if !defined(MA_APPLE_MOBILE)
  28326. ma_result result;
  28327. #endif
  28328. MA_ASSERT(pConfig != NULL);
  28329. MA_ASSERT(pContext != NULL);
  28330. #if defined(MA_APPLE_MOBILE)
  28331. @autoreleasepool {
  28332. AVAudioSession* pAudioSession = [AVAudioSession sharedInstance];
  28333. AVAudioSessionCategoryOptions options = pConfig->coreaudio.sessionCategoryOptions;
  28334. MA_ASSERT(pAudioSession != NULL);
  28335. if (pConfig->coreaudio.sessionCategory == ma_ios_session_category_default) {
  28336. /*
  28337. I'm going to use trial and error to determine our default session category. First we'll try PlayAndRecord. If that fails
  28338. we'll try Playback and if that fails we'll try record. If all of these fail we'll just not set the category.
  28339. */
  28340. #if !defined(MA_APPLE_TV) && !defined(MA_APPLE_WATCH)
  28341. options |= AVAudioSessionCategoryOptionDefaultToSpeaker;
  28342. #endif
  28343. if ([pAudioSession setCategory: AVAudioSessionCategoryPlayAndRecord withOptions:options error:nil]) {
  28344. /* Using PlayAndRecord */
  28345. } else if ([pAudioSession setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) {
  28346. /* Using Playback */
  28347. } else if ([pAudioSession setCategory: AVAudioSessionCategoryRecord withOptions:options error:nil]) {
  28348. /* Using Record */
  28349. } else {
  28350. /* Leave as default? */
  28351. }
  28352. } else {
  28353. if (pConfig->coreaudio.sessionCategory != ma_ios_session_category_none) {
  28354. #if defined(__IPHONE_12_0)
  28355. if (![pAudioSession setCategory: ma_to_AVAudioSessionCategory(pConfig->coreaudio.sessionCategory) withOptions:options error:nil]) {
  28356. return MA_INVALID_OPERATION; /* Failed to set session category. */
  28357. }
  28358. #else
  28359. /* Ignore the session category on version 11 and older, but post a warning. */
  28360. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_WARNING, "Session category only supported in iOS 12 and newer.");
  28361. #endif
  28362. }
  28363. }
  28364. if (!pConfig->coreaudio.noAudioSessionActivate) {
  28365. if (![pAudioSession setActive:true error:nil]) {
  28366. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "Failed to activate audio session.");
  28367. return MA_FAILED_TO_INIT_BACKEND;
  28368. }
  28369. }
  28370. }
  28371. #endif
  28372. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  28373. pContext->coreaudio.hCoreFoundation = ma_dlopen(pContext, "CoreFoundation.framework/CoreFoundation");
  28374. if (pContext->coreaudio.hCoreFoundation == NULL) {
  28375. return MA_API_NOT_FOUND;
  28376. }
  28377. pContext->coreaudio.CFStringGetCString = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFStringGetCString");
  28378. pContext->coreaudio.CFRelease = ma_dlsym(pContext, pContext->coreaudio.hCoreFoundation, "CFRelease");
  28379. pContext->coreaudio.hCoreAudio = ma_dlopen(pContext, "CoreAudio.framework/CoreAudio");
  28380. if (pContext->coreaudio.hCoreAudio == NULL) {
  28381. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28382. return MA_API_NOT_FOUND;
  28383. }
  28384. pContext->coreaudio.AudioObjectGetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyData");
  28385. pContext->coreaudio.AudioObjectGetPropertyDataSize = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectGetPropertyDataSize");
  28386. pContext->coreaudio.AudioObjectSetPropertyData = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectSetPropertyData");
  28387. pContext->coreaudio.AudioObjectAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectAddPropertyListener");
  28388. pContext->coreaudio.AudioObjectRemovePropertyListener = ma_dlsym(pContext, pContext->coreaudio.hCoreAudio, "AudioObjectRemovePropertyListener");
  28389. /*
  28390. It looks like Apple has moved some APIs from AudioUnit into AudioToolbox on more recent versions of macOS. They are still
  28391. defined in AudioUnit, but just in case they decide to remove them from there entirely I'm going to implement a fallback.
  28392. 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
  28393. AudioToolbox.
  28394. */
  28395. pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioUnit.framework/AudioUnit");
  28396. if (pContext->coreaudio.hAudioUnit == NULL) {
  28397. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  28398. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28399. return MA_API_NOT_FOUND;
  28400. }
  28401. if (ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext") == NULL) {
  28402. /* Couldn't find the required symbols in AudioUnit, so fall back to AudioToolbox. */
  28403. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  28404. pContext->coreaudio.hAudioUnit = ma_dlopen(pContext, "AudioToolbox.framework/AudioToolbox");
  28405. if (pContext->coreaudio.hAudioUnit == NULL) {
  28406. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  28407. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28408. return MA_API_NOT_FOUND;
  28409. }
  28410. }
  28411. pContext->coreaudio.AudioComponentFindNext = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentFindNext");
  28412. pContext->coreaudio.AudioComponentInstanceDispose = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceDispose");
  28413. pContext->coreaudio.AudioComponentInstanceNew = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioComponentInstanceNew");
  28414. pContext->coreaudio.AudioOutputUnitStart = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStart");
  28415. pContext->coreaudio.AudioOutputUnitStop = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioOutputUnitStop");
  28416. pContext->coreaudio.AudioUnitAddPropertyListener = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitAddPropertyListener");
  28417. pContext->coreaudio.AudioUnitGetPropertyInfo = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetPropertyInfo");
  28418. pContext->coreaudio.AudioUnitGetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitGetProperty");
  28419. pContext->coreaudio.AudioUnitSetProperty = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitSetProperty");
  28420. pContext->coreaudio.AudioUnitInitialize = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitInitialize");
  28421. pContext->coreaudio.AudioUnitRender = ma_dlsym(pContext, pContext->coreaudio.hAudioUnit, "AudioUnitRender");
  28422. #else
  28423. pContext->coreaudio.CFStringGetCString = (ma_proc)CFStringGetCString;
  28424. pContext->coreaudio.CFRelease = (ma_proc)CFRelease;
  28425. #if defined(MA_APPLE_DESKTOP)
  28426. pContext->coreaudio.AudioObjectGetPropertyData = (ma_proc)AudioObjectGetPropertyData;
  28427. pContext->coreaudio.AudioObjectGetPropertyDataSize = (ma_proc)AudioObjectGetPropertyDataSize;
  28428. pContext->coreaudio.AudioObjectSetPropertyData = (ma_proc)AudioObjectSetPropertyData;
  28429. pContext->coreaudio.AudioObjectAddPropertyListener = (ma_proc)AudioObjectAddPropertyListener;
  28430. pContext->coreaudio.AudioObjectRemovePropertyListener = (ma_proc)AudioObjectRemovePropertyListener;
  28431. #endif
  28432. pContext->coreaudio.AudioComponentFindNext = (ma_proc)AudioComponentFindNext;
  28433. pContext->coreaudio.AudioComponentInstanceDispose = (ma_proc)AudioComponentInstanceDispose;
  28434. pContext->coreaudio.AudioComponentInstanceNew = (ma_proc)AudioComponentInstanceNew;
  28435. pContext->coreaudio.AudioOutputUnitStart = (ma_proc)AudioOutputUnitStart;
  28436. pContext->coreaudio.AudioOutputUnitStop = (ma_proc)AudioOutputUnitStop;
  28437. pContext->coreaudio.AudioUnitAddPropertyListener = (ma_proc)AudioUnitAddPropertyListener;
  28438. pContext->coreaudio.AudioUnitGetPropertyInfo = (ma_proc)AudioUnitGetPropertyInfo;
  28439. pContext->coreaudio.AudioUnitGetProperty = (ma_proc)AudioUnitGetProperty;
  28440. pContext->coreaudio.AudioUnitSetProperty = (ma_proc)AudioUnitSetProperty;
  28441. pContext->coreaudio.AudioUnitInitialize = (ma_proc)AudioUnitInitialize;
  28442. pContext->coreaudio.AudioUnitRender = (ma_proc)AudioUnitRender;
  28443. #endif
  28444. /* Audio component. */
  28445. {
  28446. AudioComponentDescription desc;
  28447. desc.componentType = kAudioUnitType_Output;
  28448. #if defined(MA_APPLE_DESKTOP)
  28449. desc.componentSubType = kAudioUnitSubType_HALOutput;
  28450. #else
  28451. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  28452. #endif
  28453. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  28454. desc.componentFlags = 0;
  28455. desc.componentFlagsMask = 0;
  28456. pContext->coreaudio.component = ((ma_AudioComponentFindNext_proc)pContext->coreaudio.AudioComponentFindNext)(NULL, &desc);
  28457. if (pContext->coreaudio.component == NULL) {
  28458. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  28459. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  28460. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  28461. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28462. #endif
  28463. return MA_FAILED_TO_INIT_BACKEND;
  28464. }
  28465. }
  28466. #if !defined(MA_APPLE_MOBILE)
  28467. result = ma_context__init_device_tracking__coreaudio(pContext);
  28468. if (result != MA_SUCCESS) {
  28469. #if !defined(MA_NO_RUNTIME_LINKING) && !defined(MA_APPLE_MOBILE)
  28470. ma_dlclose(pContext, pContext->coreaudio.hAudioUnit);
  28471. ma_dlclose(pContext, pContext->coreaudio.hCoreAudio);
  28472. ma_dlclose(pContext, pContext->coreaudio.hCoreFoundation);
  28473. #endif
  28474. return result;
  28475. }
  28476. #endif
  28477. pContext->coreaudio.noAudioSessionDeactivate = pConfig->coreaudio.noAudioSessionDeactivate;
  28478. pCallbacks->onContextInit = ma_context_init__coreaudio;
  28479. pCallbacks->onContextUninit = ma_context_uninit__coreaudio;
  28480. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__coreaudio;
  28481. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__coreaudio;
  28482. pCallbacks->onDeviceInit = ma_device_init__coreaudio;
  28483. pCallbacks->onDeviceUninit = ma_device_uninit__coreaudio;
  28484. pCallbacks->onDeviceStart = ma_device_start__coreaudio;
  28485. pCallbacks->onDeviceStop = ma_device_stop__coreaudio;
  28486. pCallbacks->onDeviceRead = NULL;
  28487. pCallbacks->onDeviceWrite = NULL;
  28488. pCallbacks->onDeviceDataLoop = NULL;
  28489. return MA_SUCCESS;
  28490. }
  28491. #endif /* Core Audio */
  28492. /******************************************************************************
  28493. sndio Backend
  28494. ******************************************************************************/
  28495. #ifdef MA_HAS_SNDIO
  28496. #include <fcntl.h>
  28497. /*
  28498. Only supporting OpenBSD. This did not work very well at all on FreeBSD when I tried it. Not sure if this is due
  28499. to miniaudio's implementation or if it's some kind of system configuration issue, but basically the default device
  28500. just doesn't emit any sound, or at times you'll hear tiny pieces. I will consider enabling this when there's
  28501. demand for it or if I can get it tested and debugged more thoroughly.
  28502. */
  28503. #if 0
  28504. #if defined(__NetBSD__) || defined(__OpenBSD__)
  28505. #include <sys/audioio.h>
  28506. #endif
  28507. #if defined(__FreeBSD__) || defined(__DragonFly__)
  28508. #include <sys/soundcard.h>
  28509. #endif
  28510. #endif
  28511. #define MA_SIO_DEVANY "default"
  28512. #define MA_SIO_PLAY 1
  28513. #define MA_SIO_REC 2
  28514. #define MA_SIO_NENC 8
  28515. #define MA_SIO_NCHAN 8
  28516. #define MA_SIO_NRATE 16
  28517. #define MA_SIO_NCONF 4
  28518. struct ma_sio_hdl; /* <-- Opaque */
  28519. struct ma_sio_par
  28520. {
  28521. unsigned int bits;
  28522. unsigned int bps;
  28523. unsigned int sig;
  28524. unsigned int le;
  28525. unsigned int msb;
  28526. unsigned int rchan;
  28527. unsigned int pchan;
  28528. unsigned int rate;
  28529. unsigned int bufsz;
  28530. unsigned int xrun;
  28531. unsigned int round;
  28532. unsigned int appbufsz;
  28533. int __pad[3];
  28534. unsigned int __magic;
  28535. };
  28536. struct ma_sio_enc
  28537. {
  28538. unsigned int bits;
  28539. unsigned int bps;
  28540. unsigned int sig;
  28541. unsigned int le;
  28542. unsigned int msb;
  28543. };
  28544. struct ma_sio_conf
  28545. {
  28546. unsigned int enc;
  28547. unsigned int rchan;
  28548. unsigned int pchan;
  28549. unsigned int rate;
  28550. };
  28551. struct ma_sio_cap
  28552. {
  28553. struct ma_sio_enc enc[MA_SIO_NENC];
  28554. unsigned int rchan[MA_SIO_NCHAN];
  28555. unsigned int pchan[MA_SIO_NCHAN];
  28556. unsigned int rate[MA_SIO_NRATE];
  28557. int __pad[7];
  28558. unsigned int nconf;
  28559. struct ma_sio_conf confs[MA_SIO_NCONF];
  28560. };
  28561. typedef struct ma_sio_hdl* (* ma_sio_open_proc) (const char*, unsigned int, int);
  28562. typedef void (* ma_sio_close_proc) (struct ma_sio_hdl*);
  28563. typedef int (* ma_sio_setpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  28564. typedef int (* ma_sio_getpar_proc) (struct ma_sio_hdl*, struct ma_sio_par*);
  28565. typedef int (* ma_sio_getcap_proc) (struct ma_sio_hdl*, struct ma_sio_cap*);
  28566. typedef size_t (* ma_sio_write_proc) (struct ma_sio_hdl*, const void*, size_t);
  28567. typedef size_t (* ma_sio_read_proc) (struct ma_sio_hdl*, void*, size_t);
  28568. typedef int (* ma_sio_start_proc) (struct ma_sio_hdl*);
  28569. typedef int (* ma_sio_stop_proc) (struct ma_sio_hdl*);
  28570. typedef int (* ma_sio_initpar_proc)(struct ma_sio_par*);
  28571. static ma_uint32 ma_get_standard_sample_rate_priority_index__sndio(ma_uint32 sampleRate) /* Lower = higher priority */
  28572. {
  28573. ma_uint32 i;
  28574. for (i = 0; i < ma_countof(g_maStandardSampleRatePriorities); ++i) {
  28575. if (g_maStandardSampleRatePriorities[i] == sampleRate) {
  28576. return i;
  28577. }
  28578. }
  28579. return (ma_uint32)-1;
  28580. }
  28581. static ma_format ma_format_from_sio_enc__sndio(unsigned int bits, unsigned int bps, unsigned int sig, unsigned int le, unsigned int msb)
  28582. {
  28583. /* We only support native-endian right now. */
  28584. if ((ma_is_little_endian() && le == 0) || (ma_is_big_endian() && le == 1)) {
  28585. return ma_format_unknown;
  28586. }
  28587. if (bits == 8 && bps == 1 && sig == 0) {
  28588. return ma_format_u8;
  28589. }
  28590. if (bits == 16 && bps == 2 && sig == 1) {
  28591. return ma_format_s16;
  28592. }
  28593. if (bits == 24 && bps == 3 && sig == 1) {
  28594. return ma_format_s24;
  28595. }
  28596. if (bits == 24 && bps == 4 && sig == 1 && msb == 0) {
  28597. /*return ma_format_s24_32;*/
  28598. }
  28599. if (bits == 32 && bps == 4 && sig == 1) {
  28600. return ma_format_s32;
  28601. }
  28602. return ma_format_unknown;
  28603. }
  28604. static ma_format ma_find_best_format_from_sio_cap__sndio(struct ma_sio_cap* caps)
  28605. {
  28606. ma_format bestFormat;
  28607. unsigned int iConfig;
  28608. MA_ASSERT(caps != NULL);
  28609. bestFormat = ma_format_unknown;
  28610. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  28611. unsigned int iEncoding;
  28612. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  28613. unsigned int bits;
  28614. unsigned int bps;
  28615. unsigned int sig;
  28616. unsigned int le;
  28617. unsigned int msb;
  28618. ma_format format;
  28619. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  28620. continue;
  28621. }
  28622. bits = caps->enc[iEncoding].bits;
  28623. bps = caps->enc[iEncoding].bps;
  28624. sig = caps->enc[iEncoding].sig;
  28625. le = caps->enc[iEncoding].le;
  28626. msb = caps->enc[iEncoding].msb;
  28627. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  28628. if (format == ma_format_unknown) {
  28629. continue; /* Format not supported. */
  28630. }
  28631. if (bestFormat == ma_format_unknown) {
  28632. bestFormat = format;
  28633. } else {
  28634. if (ma_get_format_priority_index(bestFormat) > ma_get_format_priority_index(format)) { /* <-- Lower = better. */
  28635. bestFormat = format;
  28636. }
  28637. }
  28638. }
  28639. }
  28640. return bestFormat;
  28641. }
  28642. static ma_uint32 ma_find_best_channels_from_sio_cap__sndio(struct ma_sio_cap* caps, ma_device_type deviceType, ma_format requiredFormat)
  28643. {
  28644. ma_uint32 maxChannels;
  28645. unsigned int iConfig;
  28646. MA_ASSERT(caps != NULL);
  28647. MA_ASSERT(requiredFormat != ma_format_unknown);
  28648. /* Just pick whatever configuration has the most channels. */
  28649. maxChannels = 0;
  28650. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  28651. /* The encoding should be of requiredFormat. */
  28652. unsigned int iEncoding;
  28653. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  28654. unsigned int iChannel;
  28655. unsigned int bits;
  28656. unsigned int bps;
  28657. unsigned int sig;
  28658. unsigned int le;
  28659. unsigned int msb;
  28660. ma_format format;
  28661. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  28662. continue;
  28663. }
  28664. bits = caps->enc[iEncoding].bits;
  28665. bps = caps->enc[iEncoding].bps;
  28666. sig = caps->enc[iEncoding].sig;
  28667. le = caps->enc[iEncoding].le;
  28668. msb = caps->enc[iEncoding].msb;
  28669. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  28670. if (format != requiredFormat) {
  28671. continue;
  28672. }
  28673. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  28674. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  28675. unsigned int chan = 0;
  28676. unsigned int channels;
  28677. if (deviceType == ma_device_type_playback) {
  28678. chan = caps->confs[iConfig].pchan;
  28679. } else {
  28680. chan = caps->confs[iConfig].rchan;
  28681. }
  28682. if ((chan & (1UL << iChannel)) == 0) {
  28683. continue;
  28684. }
  28685. if (deviceType == ma_device_type_playback) {
  28686. channels = caps->pchan[iChannel];
  28687. } else {
  28688. channels = caps->rchan[iChannel];
  28689. }
  28690. if (maxChannels < channels) {
  28691. maxChannels = channels;
  28692. }
  28693. }
  28694. }
  28695. }
  28696. return maxChannels;
  28697. }
  28698. 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)
  28699. {
  28700. ma_uint32 firstSampleRate;
  28701. ma_uint32 bestSampleRate;
  28702. unsigned int iConfig;
  28703. MA_ASSERT(caps != NULL);
  28704. MA_ASSERT(requiredFormat != ma_format_unknown);
  28705. MA_ASSERT(requiredChannels > 0);
  28706. MA_ASSERT(requiredChannels <= MA_MAX_CHANNELS);
  28707. firstSampleRate = 0; /* <-- If the device does not support a standard rate we'll fall back to the first one that's found. */
  28708. bestSampleRate = 0;
  28709. for (iConfig = 0; iConfig < caps->nconf; iConfig += 1) {
  28710. /* The encoding should be of requiredFormat. */
  28711. unsigned int iEncoding;
  28712. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  28713. unsigned int iChannel;
  28714. unsigned int bits;
  28715. unsigned int bps;
  28716. unsigned int sig;
  28717. unsigned int le;
  28718. unsigned int msb;
  28719. ma_format format;
  28720. if ((caps->confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  28721. continue;
  28722. }
  28723. bits = caps->enc[iEncoding].bits;
  28724. bps = caps->enc[iEncoding].bps;
  28725. sig = caps->enc[iEncoding].sig;
  28726. le = caps->enc[iEncoding].le;
  28727. msb = caps->enc[iEncoding].msb;
  28728. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  28729. if (format != requiredFormat) {
  28730. continue;
  28731. }
  28732. /* Getting here means the format is supported. Iterate over each channel count and grab the biggest one. */
  28733. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  28734. unsigned int chan = 0;
  28735. unsigned int channels;
  28736. unsigned int iRate;
  28737. if (deviceType == ma_device_type_playback) {
  28738. chan = caps->confs[iConfig].pchan;
  28739. } else {
  28740. chan = caps->confs[iConfig].rchan;
  28741. }
  28742. if ((chan & (1UL << iChannel)) == 0) {
  28743. continue;
  28744. }
  28745. if (deviceType == ma_device_type_playback) {
  28746. channels = caps->pchan[iChannel];
  28747. } else {
  28748. channels = caps->rchan[iChannel];
  28749. }
  28750. if (channels != requiredChannels) {
  28751. continue;
  28752. }
  28753. /* Getting here means we have found a compatible encoding/channel pair. */
  28754. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  28755. ma_uint32 rate = (ma_uint32)caps->rate[iRate];
  28756. ma_uint32 ratePriority;
  28757. if (firstSampleRate == 0) {
  28758. firstSampleRate = rate;
  28759. }
  28760. /* Disregard this rate if it's not a standard one. */
  28761. ratePriority = ma_get_standard_sample_rate_priority_index__sndio(rate);
  28762. if (ratePriority == (ma_uint32)-1) {
  28763. continue;
  28764. }
  28765. if (ma_get_standard_sample_rate_priority_index__sndio(bestSampleRate) > ratePriority) { /* Lower = better. */
  28766. bestSampleRate = rate;
  28767. }
  28768. }
  28769. }
  28770. }
  28771. }
  28772. /* If a standard sample rate was not found just fall back to the first one that was iterated. */
  28773. if (bestSampleRate == 0) {
  28774. bestSampleRate = firstSampleRate;
  28775. }
  28776. return bestSampleRate;
  28777. }
  28778. static ma_result ma_context_enumerate_devices__sndio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  28779. {
  28780. ma_bool32 isTerminating = MA_FALSE;
  28781. struct ma_sio_hdl* handle;
  28782. MA_ASSERT(pContext != NULL);
  28783. MA_ASSERT(callback != NULL);
  28784. /* sndio doesn't seem to have a good device enumeration API, so I'm therefore only enumerating over default devices for now. */
  28785. /* Playback. */
  28786. if (!isTerminating) {
  28787. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_PLAY, 0);
  28788. if (handle != NULL) {
  28789. /* Supports playback. */
  28790. ma_device_info deviceInfo;
  28791. MA_ZERO_OBJECT(&deviceInfo);
  28792. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), MA_SIO_DEVANY);
  28793. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME);
  28794. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  28795. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  28796. }
  28797. }
  28798. /* Capture. */
  28799. if (!isTerminating) {
  28800. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(MA_SIO_DEVANY, MA_SIO_REC, 0);
  28801. if (handle != NULL) {
  28802. /* Supports capture. */
  28803. ma_device_info deviceInfo;
  28804. MA_ZERO_OBJECT(&deviceInfo);
  28805. ma_strcpy_s(deviceInfo.id.sndio, sizeof(deviceInfo.id.sndio), "default");
  28806. ma_strcpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME);
  28807. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  28808. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  28809. }
  28810. }
  28811. return MA_SUCCESS;
  28812. }
  28813. 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)
  28814. {
  28815. char devid[256];
  28816. struct ma_sio_hdl* handle;
  28817. struct ma_sio_cap caps;
  28818. unsigned int iConfig;
  28819. MA_ASSERT(pContext != NULL);
  28820. /* We need to open the device before we can get information about it. */
  28821. if (pDeviceID == NULL) {
  28822. ma_strcpy_s(devid, sizeof(devid), MA_SIO_DEVANY);
  28823. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (deviceType == ma_device_type_playback) ? MA_DEFAULT_PLAYBACK_DEVICE_NAME : MA_DEFAULT_CAPTURE_DEVICE_NAME);
  28824. } else {
  28825. ma_strcpy_s(devid, sizeof(devid), pDeviceID->sndio);
  28826. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), devid);
  28827. }
  28828. handle = ((ma_sio_open_proc)pContext->sndio.sio_open)(devid, (deviceType == ma_device_type_playback) ? MA_SIO_PLAY : MA_SIO_REC, 0);
  28829. if (handle == NULL) {
  28830. return MA_NO_DEVICE;
  28831. }
  28832. if (((ma_sio_getcap_proc)pContext->sndio.sio_getcap)(handle, &caps) == 0) {
  28833. return MA_ERROR;
  28834. }
  28835. pDeviceInfo->nativeDataFormatCount = 0;
  28836. for (iConfig = 0; iConfig < caps.nconf; iConfig += 1) {
  28837. /*
  28838. The main thing we care about is that the encoding is supported by miniaudio. If it is, we want to give
  28839. preference to some formats over others.
  28840. */
  28841. unsigned int iEncoding;
  28842. unsigned int iChannel;
  28843. unsigned int iRate;
  28844. for (iEncoding = 0; iEncoding < MA_SIO_NENC; iEncoding += 1) {
  28845. unsigned int bits;
  28846. unsigned int bps;
  28847. unsigned int sig;
  28848. unsigned int le;
  28849. unsigned int msb;
  28850. ma_format format;
  28851. if ((caps.confs[iConfig].enc & (1UL << iEncoding)) == 0) {
  28852. continue;
  28853. }
  28854. bits = caps.enc[iEncoding].bits;
  28855. bps = caps.enc[iEncoding].bps;
  28856. sig = caps.enc[iEncoding].sig;
  28857. le = caps.enc[iEncoding].le;
  28858. msb = caps.enc[iEncoding].msb;
  28859. format = ma_format_from_sio_enc__sndio(bits, bps, sig, le, msb);
  28860. if (format == ma_format_unknown) {
  28861. continue; /* Format not supported. */
  28862. }
  28863. /* Channels. */
  28864. for (iChannel = 0; iChannel < MA_SIO_NCHAN; iChannel += 1) {
  28865. unsigned int chan = 0;
  28866. unsigned int channels;
  28867. if (deviceType == ma_device_type_playback) {
  28868. chan = caps.confs[iConfig].pchan;
  28869. } else {
  28870. chan = caps.confs[iConfig].rchan;
  28871. }
  28872. if ((chan & (1UL << iChannel)) == 0) {
  28873. continue;
  28874. }
  28875. if (deviceType == ma_device_type_playback) {
  28876. channels = caps.pchan[iChannel];
  28877. } else {
  28878. channels = caps.rchan[iChannel];
  28879. }
  28880. /* Sample Rates. */
  28881. for (iRate = 0; iRate < MA_SIO_NRATE; iRate += 1) {
  28882. if ((caps.confs[iConfig].rate & (1UL << iRate)) != 0) {
  28883. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, caps.rate[iRate], 0);
  28884. }
  28885. }
  28886. }
  28887. }
  28888. }
  28889. ((ma_sio_close_proc)pContext->sndio.sio_close)(handle);
  28890. return MA_SUCCESS;
  28891. }
  28892. static ma_result ma_device_uninit__sndio(ma_device* pDevice)
  28893. {
  28894. MA_ASSERT(pDevice != NULL);
  28895. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  28896. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  28897. }
  28898. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  28899. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  28900. }
  28901. return MA_SUCCESS;
  28902. }
  28903. static ma_result ma_device_init_handle__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  28904. {
  28905. const char* pDeviceName;
  28906. ma_ptr handle;
  28907. int openFlags = 0;
  28908. struct ma_sio_cap caps;
  28909. struct ma_sio_par par;
  28910. const ma_device_id* pDeviceID;
  28911. ma_format format;
  28912. ma_uint32 channels;
  28913. ma_uint32 sampleRate;
  28914. ma_format internalFormat;
  28915. ma_uint32 internalChannels;
  28916. ma_uint32 internalSampleRate;
  28917. ma_uint32 internalPeriodSizeInFrames;
  28918. ma_uint32 internalPeriods;
  28919. MA_ASSERT(pConfig != NULL);
  28920. MA_ASSERT(deviceType != ma_device_type_duplex);
  28921. MA_ASSERT(pDevice != NULL);
  28922. if (deviceType == ma_device_type_capture) {
  28923. openFlags = MA_SIO_REC;
  28924. } else {
  28925. openFlags = MA_SIO_PLAY;
  28926. }
  28927. pDeviceID = pDescriptor->pDeviceID;
  28928. format = pDescriptor->format;
  28929. channels = pDescriptor->channels;
  28930. sampleRate = pDescriptor->sampleRate;
  28931. pDeviceName = MA_SIO_DEVANY;
  28932. if (pDeviceID != NULL) {
  28933. pDeviceName = pDeviceID->sndio;
  28934. }
  28935. handle = (ma_ptr)((ma_sio_open_proc)pDevice->pContext->sndio.sio_open)(pDeviceName, openFlags, 0);
  28936. if (handle == NULL) {
  28937. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to open device.");
  28938. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  28939. }
  28940. /* We need to retrieve the device caps to determine the most appropriate format to use. */
  28941. if (((ma_sio_getcap_proc)pDevice->pContext->sndio.sio_getcap)((struct ma_sio_hdl*)handle, &caps) == 0) {
  28942. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  28943. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve device caps.");
  28944. return MA_ERROR;
  28945. }
  28946. /*
  28947. Note: sndio reports a huge range of available channels. This is inconvenient for us because there's no real
  28948. way, as far as I can tell, to get the _actual_ channel count of the device. I'm therefore restricting this
  28949. to the requested channels, regardless of whether or not the default channel count is requested.
  28950. For hardware devices, I'm suspecting only a single channel count will be reported and we can safely use the
  28951. value returned by ma_find_best_channels_from_sio_cap__sndio().
  28952. */
  28953. if (deviceType == ma_device_type_capture) {
  28954. if (format == ma_format_unknown) {
  28955. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  28956. }
  28957. if (channels == 0) {
  28958. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  28959. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  28960. } else {
  28961. channels = MA_DEFAULT_CHANNELS;
  28962. }
  28963. }
  28964. } else {
  28965. if (format == ma_format_unknown) {
  28966. format = ma_find_best_format_from_sio_cap__sndio(&caps);
  28967. }
  28968. if (channels == 0) {
  28969. if (strlen(pDeviceName) > strlen("rsnd/") && strncmp(pDeviceName, "rsnd/", strlen("rsnd/")) == 0) {
  28970. channels = ma_find_best_channels_from_sio_cap__sndio(&caps, deviceType, format);
  28971. } else {
  28972. channels = MA_DEFAULT_CHANNELS;
  28973. }
  28974. }
  28975. }
  28976. if (sampleRate == 0) {
  28977. sampleRate = ma_find_best_sample_rate_from_sio_cap__sndio(&caps, pConfig->deviceType, format, channels);
  28978. }
  28979. ((ma_sio_initpar_proc)pDevice->pContext->sndio.sio_initpar)(&par);
  28980. par.msb = 0;
  28981. par.le = ma_is_little_endian();
  28982. switch (format) {
  28983. case ma_format_u8:
  28984. {
  28985. par.bits = 8;
  28986. par.bps = 1;
  28987. par.sig = 0;
  28988. } break;
  28989. case ma_format_s24:
  28990. {
  28991. par.bits = 24;
  28992. par.bps = 3;
  28993. par.sig = 1;
  28994. } break;
  28995. case ma_format_s32:
  28996. {
  28997. par.bits = 32;
  28998. par.bps = 4;
  28999. par.sig = 1;
  29000. } break;
  29001. case ma_format_s16:
  29002. case ma_format_f32:
  29003. case ma_format_unknown:
  29004. default:
  29005. {
  29006. par.bits = 16;
  29007. par.bps = 2;
  29008. par.sig = 1;
  29009. } break;
  29010. }
  29011. if (deviceType == ma_device_type_capture) {
  29012. par.rchan = channels;
  29013. } else {
  29014. par.pchan = channels;
  29015. }
  29016. par.rate = sampleRate;
  29017. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, par.rate, pConfig->performanceProfile);
  29018. par.round = internalPeriodSizeInFrames;
  29019. par.appbufsz = par.round * pDescriptor->periodCount;
  29020. if (((ma_sio_setpar_proc)pDevice->pContext->sndio.sio_setpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29021. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29022. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to set buffer size.");
  29023. return MA_ERROR;
  29024. }
  29025. if (((ma_sio_getpar_proc)pDevice->pContext->sndio.sio_getpar)((struct ma_sio_hdl*)handle, &par) == 0) {
  29026. ((ma_sio_close_proc)pDevice->pContext->sndio.sio_close)((struct ma_sio_hdl*)handle);
  29027. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to retrieve buffer size.");
  29028. return MA_ERROR;
  29029. }
  29030. internalFormat = ma_format_from_sio_enc__sndio(par.bits, par.bps, par.sig, par.le, par.msb);
  29031. internalChannels = (deviceType == ma_device_type_capture) ? par.rchan : par.pchan;
  29032. internalSampleRate = par.rate;
  29033. internalPeriods = par.appbufsz / par.round;
  29034. internalPeriodSizeInFrames = par.round;
  29035. if (deviceType == ma_device_type_capture) {
  29036. pDevice->sndio.handleCapture = handle;
  29037. } else {
  29038. pDevice->sndio.handlePlayback = handle;
  29039. }
  29040. pDescriptor->format = internalFormat;
  29041. pDescriptor->channels = internalChannels;
  29042. pDescriptor->sampleRate = internalSampleRate;
  29043. ma_channel_map_init_standard(ma_standard_channel_map_sndio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  29044. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  29045. pDescriptor->periodCount = internalPeriods;
  29046. return MA_SUCCESS;
  29047. }
  29048. static ma_result ma_device_init__sndio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  29049. {
  29050. MA_ASSERT(pDevice != NULL);
  29051. MA_ZERO_OBJECT(&pDevice->sndio);
  29052. if (pConfig->deviceType == ma_device_type_loopback) {
  29053. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29054. }
  29055. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29056. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  29057. if (result != MA_SUCCESS) {
  29058. return result;
  29059. }
  29060. }
  29061. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29062. ma_result result = ma_device_init_handle__sndio(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  29063. if (result != MA_SUCCESS) {
  29064. return result;
  29065. }
  29066. }
  29067. return MA_SUCCESS;
  29068. }
  29069. static ma_result ma_device_start__sndio(ma_device* pDevice)
  29070. {
  29071. MA_ASSERT(pDevice != NULL);
  29072. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29073. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29074. }
  29075. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29076. ((ma_sio_start_proc)pDevice->pContext->sndio.sio_start)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback); /* <-- Doesn't actually playback until data is written. */
  29077. }
  29078. return MA_SUCCESS;
  29079. }
  29080. static ma_result ma_device_stop__sndio(ma_device* pDevice)
  29081. {
  29082. MA_ASSERT(pDevice != NULL);
  29083. /*
  29084. From the documentation:
  29085. 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
  29086. 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
  29087. buffer is drained. In no case are samples in the play buffer discarded.
  29088. Therefore, sio_stop() performs all of the necessary draining for us.
  29089. */
  29090. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29091. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handleCapture);
  29092. }
  29093. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29094. ((ma_sio_stop_proc)pDevice->pContext->sndio.sio_stop)((struct ma_sio_hdl*)pDevice->sndio.handlePlayback);
  29095. }
  29096. return MA_SUCCESS;
  29097. }
  29098. static ma_result ma_device_write__sndio(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  29099. {
  29100. int result;
  29101. if (pFramesWritten != NULL) {
  29102. *pFramesWritten = 0;
  29103. }
  29104. 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));
  29105. if (result == 0) {
  29106. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[sndio] Failed to send data from the client to the device.");
  29107. return MA_IO_ERROR;
  29108. }
  29109. if (pFramesWritten != NULL) {
  29110. *pFramesWritten = frameCount;
  29111. }
  29112. return MA_SUCCESS;
  29113. }
  29114. static ma_result ma_device_read__sndio(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  29115. {
  29116. int result;
  29117. if (pFramesRead != NULL) {
  29118. *pFramesRead = 0;
  29119. }
  29120. 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));
  29121. if (result == 0) {
  29122. 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.");
  29123. return MA_IO_ERROR;
  29124. }
  29125. if (pFramesRead != NULL) {
  29126. *pFramesRead = frameCount;
  29127. }
  29128. return MA_SUCCESS;
  29129. }
  29130. static ma_result ma_context_uninit__sndio(ma_context* pContext)
  29131. {
  29132. MA_ASSERT(pContext != NULL);
  29133. MA_ASSERT(pContext->backend == ma_backend_sndio);
  29134. (void)pContext;
  29135. return MA_SUCCESS;
  29136. }
  29137. static ma_result ma_context_init__sndio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  29138. {
  29139. #ifndef MA_NO_RUNTIME_LINKING
  29140. const char* libsndioNames[] = {
  29141. "libsndio.so"
  29142. };
  29143. size_t i;
  29144. for (i = 0; i < ma_countof(libsndioNames); ++i) {
  29145. pContext->sndio.sndioSO = ma_dlopen(pContext, libsndioNames[i]);
  29146. if (pContext->sndio.sndioSO != NULL) {
  29147. break;
  29148. }
  29149. }
  29150. if (pContext->sndio.sndioSO == NULL) {
  29151. return MA_NO_BACKEND;
  29152. }
  29153. pContext->sndio.sio_open = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_open");
  29154. pContext->sndio.sio_close = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_close");
  29155. pContext->sndio.sio_setpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_setpar");
  29156. pContext->sndio.sio_getpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getpar");
  29157. pContext->sndio.sio_getcap = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_getcap");
  29158. pContext->sndio.sio_write = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_write");
  29159. pContext->sndio.sio_read = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_read");
  29160. pContext->sndio.sio_start = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_start");
  29161. pContext->sndio.sio_stop = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_stop");
  29162. pContext->sndio.sio_initpar = (ma_proc)ma_dlsym(pContext, pContext->sndio.sndioSO, "sio_initpar");
  29163. #else
  29164. pContext->sndio.sio_open = sio_open;
  29165. pContext->sndio.sio_close = sio_close;
  29166. pContext->sndio.sio_setpar = sio_setpar;
  29167. pContext->sndio.sio_getpar = sio_getpar;
  29168. pContext->sndio.sio_getcap = sio_getcap;
  29169. pContext->sndio.sio_write = sio_write;
  29170. pContext->sndio.sio_read = sio_read;
  29171. pContext->sndio.sio_start = sio_start;
  29172. pContext->sndio.sio_stop = sio_stop;
  29173. pContext->sndio.sio_initpar = sio_initpar;
  29174. #endif
  29175. pCallbacks->onContextInit = ma_context_init__sndio;
  29176. pCallbacks->onContextUninit = ma_context_uninit__sndio;
  29177. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__sndio;
  29178. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__sndio;
  29179. pCallbacks->onDeviceInit = ma_device_init__sndio;
  29180. pCallbacks->onDeviceUninit = ma_device_uninit__sndio;
  29181. pCallbacks->onDeviceStart = ma_device_start__sndio;
  29182. pCallbacks->onDeviceStop = ma_device_stop__sndio;
  29183. pCallbacks->onDeviceRead = ma_device_read__sndio;
  29184. pCallbacks->onDeviceWrite = ma_device_write__sndio;
  29185. pCallbacks->onDeviceDataLoop = NULL;
  29186. (void)pConfig;
  29187. return MA_SUCCESS;
  29188. }
  29189. #endif /* sndio */
  29190. /******************************************************************************
  29191. audio(4) Backend
  29192. ******************************************************************************/
  29193. #ifdef MA_HAS_AUDIO4
  29194. #include <fcntl.h>
  29195. #include <poll.h>
  29196. #include <errno.h>
  29197. #include <sys/stat.h>
  29198. #include <sys/types.h>
  29199. #include <sys/ioctl.h>
  29200. #include <sys/audioio.h>
  29201. #if defined(__OpenBSD__)
  29202. #include <sys/param.h>
  29203. #if defined(OpenBSD) && OpenBSD >= 201709
  29204. #define MA_AUDIO4_USE_NEW_API
  29205. #endif
  29206. #endif
  29207. static void ma_construct_device_id__audio4(char* id, size_t idSize, const char* base, int deviceIndex)
  29208. {
  29209. size_t baseLen;
  29210. MA_ASSERT(id != NULL);
  29211. MA_ASSERT(idSize > 0);
  29212. MA_ASSERT(deviceIndex >= 0);
  29213. baseLen = strlen(base);
  29214. MA_ASSERT(idSize > baseLen);
  29215. ma_strcpy_s(id, idSize, base);
  29216. ma_itoa_s(deviceIndex, id+baseLen, idSize-baseLen, 10);
  29217. }
  29218. static ma_result ma_extract_device_index_from_id__audio4(const char* id, const char* base, int* pIndexOut)
  29219. {
  29220. size_t idLen;
  29221. size_t baseLen;
  29222. const char* deviceIndexStr;
  29223. MA_ASSERT(id != NULL);
  29224. MA_ASSERT(base != NULL);
  29225. MA_ASSERT(pIndexOut != NULL);
  29226. idLen = strlen(id);
  29227. baseLen = strlen(base);
  29228. if (idLen <= baseLen) {
  29229. return MA_ERROR; /* Doesn't look like the id starts with the base. */
  29230. }
  29231. if (strncmp(id, base, baseLen) != 0) {
  29232. return MA_ERROR; /* ID does not begin with base. */
  29233. }
  29234. deviceIndexStr = id + baseLen;
  29235. if (deviceIndexStr[0] == '\0') {
  29236. return MA_ERROR; /* No index specified in the ID. */
  29237. }
  29238. if (pIndexOut) {
  29239. *pIndexOut = atoi(deviceIndexStr);
  29240. }
  29241. return MA_SUCCESS;
  29242. }
  29243. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  29244. static ma_format ma_format_from_encoding__audio4(unsigned int encoding, unsigned int precision)
  29245. {
  29246. if (precision == 8 && (encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR || encoding == AUDIO_ENCODING_ULINEAR_LE || encoding == AUDIO_ENCODING_ULINEAR_BE)) {
  29247. return ma_format_u8;
  29248. } else {
  29249. if (ma_is_little_endian() && encoding == AUDIO_ENCODING_SLINEAR_LE) {
  29250. if (precision == 16) {
  29251. return ma_format_s16;
  29252. } else if (precision == 24) {
  29253. return ma_format_s24;
  29254. } else if (precision == 32) {
  29255. return ma_format_s32;
  29256. }
  29257. } else if (ma_is_big_endian() && encoding == AUDIO_ENCODING_SLINEAR_BE) {
  29258. if (precision == 16) {
  29259. return ma_format_s16;
  29260. } else if (precision == 24) {
  29261. return ma_format_s24;
  29262. } else if (precision == 32) {
  29263. return ma_format_s32;
  29264. }
  29265. }
  29266. }
  29267. return ma_format_unknown; /* Encoding not supported. */
  29268. }
  29269. static void ma_encoding_from_format__audio4(ma_format format, unsigned int* pEncoding, unsigned int* pPrecision)
  29270. {
  29271. MA_ASSERT(pEncoding != NULL);
  29272. MA_ASSERT(pPrecision != NULL);
  29273. switch (format)
  29274. {
  29275. case ma_format_u8:
  29276. {
  29277. *pEncoding = AUDIO_ENCODING_ULINEAR;
  29278. *pPrecision = 8;
  29279. } break;
  29280. case ma_format_s24:
  29281. {
  29282. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  29283. *pPrecision = 24;
  29284. } break;
  29285. case ma_format_s32:
  29286. {
  29287. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  29288. *pPrecision = 32;
  29289. } break;
  29290. case ma_format_s16:
  29291. case ma_format_f32:
  29292. case ma_format_unknown:
  29293. default:
  29294. {
  29295. *pEncoding = (ma_is_little_endian()) ? AUDIO_ENCODING_SLINEAR_LE : AUDIO_ENCODING_SLINEAR_BE;
  29296. *pPrecision = 16;
  29297. } break;
  29298. }
  29299. }
  29300. static ma_format ma_format_from_prinfo__audio4(struct audio_prinfo* prinfo)
  29301. {
  29302. return ma_format_from_encoding__audio4(prinfo->encoding, prinfo->precision);
  29303. }
  29304. static ma_format ma_best_format_from_fd__audio4(int fd, ma_format preferredFormat)
  29305. {
  29306. audio_encoding_t encoding;
  29307. ma_uint32 iFormat;
  29308. int counter = 0;
  29309. /* First check to see if the preferred format is supported. */
  29310. if (preferredFormat != ma_format_unknown) {
  29311. counter = 0;
  29312. for (;;) {
  29313. MA_ZERO_OBJECT(&encoding);
  29314. encoding.index = counter;
  29315. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  29316. break;
  29317. }
  29318. if (preferredFormat == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  29319. return preferredFormat; /* Found the preferred format. */
  29320. }
  29321. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  29322. counter += 1;
  29323. }
  29324. }
  29325. /* Getting here means our preferred format is not supported, so fall back to our standard priorities. */
  29326. for (iFormat = 0; iFormat < ma_countof(g_maFormatPriorities); iFormat += 1) {
  29327. ma_format format = g_maFormatPriorities[iFormat];
  29328. counter = 0;
  29329. for (;;) {
  29330. MA_ZERO_OBJECT(&encoding);
  29331. encoding.index = counter;
  29332. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  29333. break;
  29334. }
  29335. if (format == ma_format_from_encoding__audio4(encoding.encoding, encoding.precision)) {
  29336. return format; /* Found a workable format. */
  29337. }
  29338. /* Getting here means this encoding does not match our preferred format so we need to more on to the next encoding. */
  29339. counter += 1;
  29340. }
  29341. }
  29342. /* Getting here means not appropriate format was found. */
  29343. return ma_format_unknown;
  29344. }
  29345. #else
  29346. static ma_format ma_format_from_swpar__audio4(struct audio_swpar* par)
  29347. {
  29348. if (par->bits == 8 && par->bps == 1 && par->sig == 0) {
  29349. return ma_format_u8;
  29350. }
  29351. if (par->bits == 16 && par->bps == 2 && par->sig == 1 && par->le == ma_is_little_endian()) {
  29352. return ma_format_s16;
  29353. }
  29354. if (par->bits == 24 && par->bps == 3 && par->sig == 1 && par->le == ma_is_little_endian()) {
  29355. return ma_format_s24;
  29356. }
  29357. if (par->bits == 32 && par->bps == 4 && par->sig == 1 && par->le == ma_is_little_endian()) {
  29358. return ma_format_f32;
  29359. }
  29360. /* Format not supported. */
  29361. return ma_format_unknown;
  29362. }
  29363. #endif
  29364. static ma_result ma_context_get_device_info_from_fd__audio4(ma_context* pContext, ma_device_type deviceType, int fd, ma_device_info* pDeviceInfo)
  29365. {
  29366. audio_device_t fdDevice;
  29367. MA_ASSERT(pContext != NULL);
  29368. MA_ASSERT(fd >= 0);
  29369. MA_ASSERT(pDeviceInfo != NULL);
  29370. (void)pContext;
  29371. (void)deviceType;
  29372. if (ioctl(fd, AUDIO_GETDEV, &fdDevice) < 0) {
  29373. return MA_ERROR; /* Failed to retrieve device info. */
  29374. }
  29375. /* Name. */
  29376. ma_strcpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), fdDevice.name);
  29377. #if !defined(MA_AUDIO4_USE_NEW_API)
  29378. {
  29379. audio_info_t fdInfo;
  29380. int counter = 0;
  29381. ma_uint32 channels;
  29382. ma_uint32 sampleRate;
  29383. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  29384. return MA_ERROR;
  29385. }
  29386. if (deviceType == ma_device_type_playback) {
  29387. channels = fdInfo.play.channels;
  29388. sampleRate = fdInfo.play.sample_rate;
  29389. } else {
  29390. channels = fdInfo.record.channels;
  29391. sampleRate = fdInfo.record.sample_rate;
  29392. }
  29393. /* Supported formats. We get this by looking at the encodings. */
  29394. pDeviceInfo->nativeDataFormatCount = 0;
  29395. for (;;) {
  29396. audio_encoding_t encoding;
  29397. ma_format format;
  29398. MA_ZERO_OBJECT(&encoding);
  29399. encoding.index = counter;
  29400. if (ioctl(fd, AUDIO_GETENC, &encoding) < 0) {
  29401. break;
  29402. }
  29403. format = ma_format_from_encoding__audio4(encoding.encoding, encoding.precision);
  29404. if (format != ma_format_unknown) {
  29405. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  29406. }
  29407. counter += 1;
  29408. }
  29409. }
  29410. #else
  29411. {
  29412. struct audio_swpar fdPar;
  29413. ma_format format;
  29414. ma_uint32 channels;
  29415. ma_uint32 sampleRate;
  29416. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  29417. return MA_ERROR;
  29418. }
  29419. format = ma_format_from_swpar__audio4(&fdPar);
  29420. if (format == ma_format_unknown) {
  29421. return MA_FORMAT_NOT_SUPPORTED;
  29422. }
  29423. if (deviceType == ma_device_type_playback) {
  29424. channels = fdPar.pchan;
  29425. } else {
  29426. channels = fdPar.rchan;
  29427. }
  29428. sampleRate = fdPar.rate;
  29429. pDeviceInfo->nativeDataFormatCount = 0;
  29430. ma_device_info_add_native_data_format(pDeviceInfo, format, channels, sampleRate, 0);
  29431. }
  29432. #endif
  29433. return MA_SUCCESS;
  29434. }
  29435. static ma_result ma_context_enumerate_devices__audio4(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  29436. {
  29437. const int maxDevices = 64;
  29438. char devpath[256];
  29439. int iDevice;
  29440. MA_ASSERT(pContext != NULL);
  29441. MA_ASSERT(callback != NULL);
  29442. /*
  29443. Every device will be named "/dev/audioN", with a "/dev/audioctlN" equivalent. We use the "/dev/audioctlN"
  29444. version here since we can open it even when another process has control of the "/dev/audioN" device.
  29445. */
  29446. for (iDevice = 0; iDevice < maxDevices; ++iDevice) {
  29447. struct stat st;
  29448. int fd;
  29449. ma_bool32 isTerminating = MA_FALSE;
  29450. ma_strcpy_s(devpath, sizeof(devpath), "/dev/audioctl");
  29451. ma_itoa_s(iDevice, devpath+strlen(devpath), sizeof(devpath)-strlen(devpath), 10);
  29452. if (stat(devpath, &st) < 0) {
  29453. break;
  29454. }
  29455. /* The device exists, but we need to check if it's usable as playback and/or capture. */
  29456. /* Playback. */
  29457. if (!isTerminating) {
  29458. fd = open(devpath, O_RDONLY, 0);
  29459. if (fd >= 0) {
  29460. /* Supports playback. */
  29461. ma_device_info deviceInfo;
  29462. MA_ZERO_OBJECT(&deviceInfo);
  29463. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  29464. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_playback, fd, &deviceInfo) == MA_SUCCESS) {
  29465. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  29466. }
  29467. close(fd);
  29468. }
  29469. }
  29470. /* Capture. */
  29471. if (!isTerminating) {
  29472. fd = open(devpath, O_WRONLY, 0);
  29473. if (fd >= 0) {
  29474. /* Supports capture. */
  29475. ma_device_info deviceInfo;
  29476. MA_ZERO_OBJECT(&deviceInfo);
  29477. ma_construct_device_id__audio4(deviceInfo.id.audio4, sizeof(deviceInfo.id.audio4), "/dev/audio", iDevice);
  29478. if (ma_context_get_device_info_from_fd__audio4(pContext, ma_device_type_capture, fd, &deviceInfo) == MA_SUCCESS) {
  29479. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  29480. }
  29481. close(fd);
  29482. }
  29483. }
  29484. if (isTerminating) {
  29485. break;
  29486. }
  29487. }
  29488. return MA_SUCCESS;
  29489. }
  29490. 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)
  29491. {
  29492. int fd = -1;
  29493. int deviceIndex = -1;
  29494. char ctlid[256];
  29495. ma_result result;
  29496. MA_ASSERT(pContext != NULL);
  29497. /*
  29498. We need to open the "/dev/audioctlN" device to get the info. To do this we need to extract the number
  29499. from the device ID which will be in "/dev/audioN" format.
  29500. */
  29501. if (pDeviceID == NULL) {
  29502. /* Default device. */
  29503. ma_strcpy_s(ctlid, sizeof(ctlid), "/dev/audioctl");
  29504. } else {
  29505. /* Specific device. We need to convert from "/dev/audioN" to "/dev/audioctlN". */
  29506. result = ma_extract_device_index_from_id__audio4(pDeviceID->audio4, "/dev/audio", &deviceIndex);
  29507. if (result != MA_SUCCESS) {
  29508. return result;
  29509. }
  29510. ma_construct_device_id__audio4(ctlid, sizeof(ctlid), "/dev/audioctl", deviceIndex);
  29511. }
  29512. fd = open(ctlid, (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY, 0);
  29513. if (fd == -1) {
  29514. return MA_NO_DEVICE;
  29515. }
  29516. if (deviceIndex == -1) {
  29517. ma_strcpy_s(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio");
  29518. } else {
  29519. ma_construct_device_id__audio4(pDeviceInfo->id.audio4, sizeof(pDeviceInfo->id.audio4), "/dev/audio", deviceIndex);
  29520. }
  29521. result = ma_context_get_device_info_from_fd__audio4(pContext, deviceType, fd, pDeviceInfo);
  29522. close(fd);
  29523. return result;
  29524. }
  29525. static ma_result ma_device_uninit__audio4(ma_device* pDevice)
  29526. {
  29527. MA_ASSERT(pDevice != NULL);
  29528. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29529. close(pDevice->audio4.fdCapture);
  29530. }
  29531. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29532. close(pDevice->audio4.fdPlayback);
  29533. }
  29534. return MA_SUCCESS;
  29535. }
  29536. static ma_result ma_device_init_fd__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  29537. {
  29538. const char* pDefaultDeviceNames[] = {
  29539. "/dev/audio",
  29540. "/dev/audio0"
  29541. };
  29542. int fd;
  29543. int fdFlags = 0;
  29544. ma_format internalFormat;
  29545. ma_uint32 internalChannels;
  29546. ma_uint32 internalSampleRate;
  29547. ma_uint32 internalPeriodSizeInFrames;
  29548. ma_uint32 internalPeriods;
  29549. MA_ASSERT(pConfig != NULL);
  29550. MA_ASSERT(deviceType != ma_device_type_duplex);
  29551. MA_ASSERT(pDevice != NULL);
  29552. /* The first thing to do is open the file. */
  29553. if (deviceType == ma_device_type_capture) {
  29554. fdFlags = O_RDONLY;
  29555. } else {
  29556. fdFlags = O_WRONLY;
  29557. }
  29558. /*fdFlags |= O_NONBLOCK;*/
  29559. if (pDescriptor->pDeviceID == NULL) {
  29560. /* Default device. */
  29561. size_t iDevice;
  29562. for (iDevice = 0; iDevice < ma_countof(pDefaultDeviceNames); ++iDevice) {
  29563. fd = open(pDefaultDeviceNames[iDevice], fdFlags, 0);
  29564. if (fd != -1) {
  29565. break;
  29566. }
  29567. }
  29568. } else {
  29569. /* Specific device. */
  29570. fd = open(pDescriptor->pDeviceID->audio4, fdFlags, 0);
  29571. }
  29572. if (fd == -1) {
  29573. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to open device.");
  29574. return ma_result_from_errno(errno);
  29575. }
  29576. #if !defined(MA_AUDIO4_USE_NEW_API) /* Old API */
  29577. {
  29578. audio_info_t fdInfo;
  29579. /*
  29580. The documentation is a little bit unclear to me as to how it handles formats. It says the
  29581. following:
  29582. Regardless of formats supported by underlying driver, the audio driver accepts the
  29583. following formats.
  29584. By then the next sentence says this:
  29585. `encoding` and `precision` are one of the values obtained by AUDIO_GETENC.
  29586. It sounds like a direct contradiction to me. I'm going to play this safe any only use the
  29587. best sample format returned by AUDIO_GETENC. If the requested format is supported we'll
  29588. use that, but otherwise we'll just use our standard format priorities to pick an
  29589. appropriate one.
  29590. */
  29591. AUDIO_INITINFO(&fdInfo);
  29592. /* We get the driver to do as much of the data conversion as possible. */
  29593. if (deviceType == ma_device_type_capture) {
  29594. fdInfo.mode = AUMODE_RECORD;
  29595. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.record.encoding, &fdInfo.record.precision);
  29596. if (pDescriptor->channels != 0) {
  29597. fdInfo.record.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  29598. }
  29599. if (pDescriptor->sampleRate != 0) {
  29600. 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`.) */
  29601. }
  29602. } else {
  29603. fdInfo.mode = AUMODE_PLAY;
  29604. ma_encoding_from_format__audio4(ma_best_format_from_fd__audio4(fd, pDescriptor->format), &fdInfo.play.encoding, &fdInfo.play.precision);
  29605. if (pDescriptor->channels != 0) {
  29606. fdInfo.play.channels = ma_clamp(pDescriptor->channels, 1, 12); /* From the documentation: `channels` ranges from 1 to 12. */
  29607. }
  29608. if (pDescriptor->sampleRate != 0) {
  29609. 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`.) */
  29610. }
  29611. }
  29612. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  29613. close(fd);
  29614. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device format. AUDIO_SETINFO failed.");
  29615. return ma_result_from_errno(errno);
  29616. }
  29617. if (ioctl(fd, AUDIO_GETINFO, &fdInfo) < 0) {
  29618. close(fd);
  29619. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] AUDIO_GETINFO failed.");
  29620. return ma_result_from_errno(errno);
  29621. }
  29622. if (deviceType == ma_device_type_capture) {
  29623. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.record);
  29624. internalChannels = fdInfo.record.channels;
  29625. internalSampleRate = fdInfo.record.sample_rate;
  29626. } else {
  29627. internalFormat = ma_format_from_prinfo__audio4(&fdInfo.play);
  29628. internalChannels = fdInfo.play.channels;
  29629. internalSampleRate = fdInfo.play.sample_rate;
  29630. }
  29631. if (internalFormat == ma_format_unknown) {
  29632. close(fd);
  29633. 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.");
  29634. return MA_FORMAT_NOT_SUPPORTED;
  29635. }
  29636. /* Buffer. */
  29637. {
  29638. ma_uint32 internalPeriodSizeInBytes;
  29639. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  29640. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  29641. if (internalPeriodSizeInBytes < 16) {
  29642. internalPeriodSizeInBytes = 16;
  29643. }
  29644. internalPeriods = pDescriptor->periodCount;
  29645. if (internalPeriods < 2) {
  29646. internalPeriods = 2;
  29647. }
  29648. /* What miniaudio calls a period, audio4 calls a block. */
  29649. AUDIO_INITINFO(&fdInfo);
  29650. fdInfo.hiwat = internalPeriods;
  29651. fdInfo.lowat = internalPeriods-1;
  29652. fdInfo.blocksize = internalPeriodSizeInBytes;
  29653. if (ioctl(fd, AUDIO_SETINFO, &fdInfo) < 0) {
  29654. close(fd);
  29655. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set internal buffer size. AUDIO_SETINFO failed.");
  29656. return ma_result_from_errno(errno);
  29657. }
  29658. internalPeriods = fdInfo.hiwat;
  29659. internalPeriodSizeInFrames = fdInfo.blocksize / ma_get_bytes_per_frame(internalFormat, internalChannels);
  29660. }
  29661. }
  29662. #else
  29663. {
  29664. struct audio_swpar fdPar;
  29665. /* 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. */
  29666. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  29667. close(fd);
  29668. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve initial device parameters.");
  29669. return ma_result_from_errno(errno);
  29670. }
  29671. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  29672. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  29673. internalSampleRate = fdPar.rate;
  29674. if (internalFormat == ma_format_unknown) {
  29675. close(fd);
  29676. 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.");
  29677. return MA_FORMAT_NOT_SUPPORTED;
  29678. }
  29679. /* Buffer. */
  29680. {
  29681. ma_uint32 internalPeriodSizeInBytes;
  29682. internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, internalSampleRate, pConfig->performanceProfile);
  29683. /* What miniaudio calls a period, audio4 calls a block. */
  29684. internalPeriodSizeInBytes = internalPeriodSizeInFrames * ma_get_bytes_per_frame(internalFormat, internalChannels);
  29685. if (internalPeriodSizeInBytes < 16) {
  29686. internalPeriodSizeInBytes = 16;
  29687. }
  29688. fdPar.nblks = pDescriptor->periodCount;
  29689. fdPar.round = internalPeriodSizeInBytes;
  29690. if (ioctl(fd, AUDIO_SETPAR, &fdPar) < 0) {
  29691. close(fd);
  29692. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to set device parameters.");
  29693. return ma_result_from_errno(errno);
  29694. }
  29695. if (ioctl(fd, AUDIO_GETPAR, &fdPar) < 0) {
  29696. close(fd);
  29697. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to retrieve actual device parameters.");
  29698. return ma_result_from_errno(errno);
  29699. }
  29700. }
  29701. internalFormat = ma_format_from_swpar__audio4(&fdPar);
  29702. internalChannels = (deviceType == ma_device_type_capture) ? fdPar.rchan : fdPar.pchan;
  29703. internalSampleRate = fdPar.rate;
  29704. internalPeriods = fdPar.nblks;
  29705. internalPeriodSizeInFrames = fdPar.round / ma_get_bytes_per_frame(internalFormat, internalChannels);
  29706. }
  29707. #endif
  29708. if (internalFormat == ma_format_unknown) {
  29709. close(fd);
  29710. 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.");
  29711. return MA_FORMAT_NOT_SUPPORTED;
  29712. }
  29713. if (deviceType == ma_device_type_capture) {
  29714. pDevice->audio4.fdCapture = fd;
  29715. } else {
  29716. pDevice->audio4.fdPlayback = fd;
  29717. }
  29718. pDescriptor->format = internalFormat;
  29719. pDescriptor->channels = internalChannels;
  29720. pDescriptor->sampleRate = internalSampleRate;
  29721. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), internalChannels);
  29722. pDescriptor->periodSizeInFrames = internalPeriodSizeInFrames;
  29723. pDescriptor->periodCount = internalPeriods;
  29724. return MA_SUCCESS;
  29725. }
  29726. static ma_result ma_device_init__audio4(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  29727. {
  29728. MA_ASSERT(pDevice != NULL);
  29729. MA_ZERO_OBJECT(&pDevice->audio4);
  29730. if (pConfig->deviceType == ma_device_type_loopback) {
  29731. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  29732. }
  29733. pDevice->audio4.fdCapture = -1;
  29734. pDevice->audio4.fdPlayback = -1;
  29735. /*
  29736. The version of the operating system dictates whether or not the device is exclusive or shared. NetBSD
  29737. introduced in-kernel mixing which means it's shared. All other BSD flavours are exclusive as far as
  29738. I'm aware.
  29739. */
  29740. #if defined(__NetBSD_Version__) && __NetBSD_Version__ >= 800000000
  29741. /* NetBSD 8.0+ */
  29742. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  29743. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  29744. return MA_SHARE_MODE_NOT_SUPPORTED;
  29745. }
  29746. #else
  29747. /* All other flavors. */
  29748. #endif
  29749. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  29750. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  29751. if (result != MA_SUCCESS) {
  29752. return result;
  29753. }
  29754. }
  29755. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  29756. ma_result result = ma_device_init_fd__audio4(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  29757. if (result != MA_SUCCESS) {
  29758. if (pConfig->deviceType == ma_device_type_duplex) {
  29759. close(pDevice->audio4.fdCapture);
  29760. }
  29761. return result;
  29762. }
  29763. }
  29764. return MA_SUCCESS;
  29765. }
  29766. static ma_result ma_device_start__audio4(ma_device* pDevice)
  29767. {
  29768. MA_ASSERT(pDevice != NULL);
  29769. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29770. if (pDevice->audio4.fdCapture == -1) {
  29771. return MA_INVALID_ARGS;
  29772. }
  29773. }
  29774. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29775. if (pDevice->audio4.fdPlayback == -1) {
  29776. return MA_INVALID_ARGS;
  29777. }
  29778. }
  29779. return MA_SUCCESS;
  29780. }
  29781. static ma_result ma_device_stop_fd__audio4(ma_device* pDevice, int fd)
  29782. {
  29783. if (fd == -1) {
  29784. return MA_INVALID_ARGS;
  29785. }
  29786. #if !defined(MA_AUDIO4_USE_NEW_API)
  29787. if (ioctl(fd, AUDIO_FLUSH, 0) < 0) {
  29788. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_FLUSH failed.");
  29789. return ma_result_from_errno(errno);
  29790. }
  29791. #else
  29792. if (ioctl(fd, AUDIO_STOP, 0) < 0) {
  29793. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to stop device. AUDIO_STOP failed.");
  29794. return ma_result_from_errno(errno);
  29795. }
  29796. #endif
  29797. return MA_SUCCESS;
  29798. }
  29799. static ma_result ma_device_stop__audio4(ma_device* pDevice)
  29800. {
  29801. MA_ASSERT(pDevice != NULL);
  29802. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  29803. ma_result result;
  29804. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdCapture);
  29805. if (result != MA_SUCCESS) {
  29806. return result;
  29807. }
  29808. }
  29809. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  29810. ma_result result;
  29811. /* 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. */
  29812. #if !defined(MA_AUDIO4_USE_NEW_API)
  29813. ioctl(pDevice->audio4.fdPlayback, AUDIO_DRAIN, 0);
  29814. #endif
  29815. /* Here is where the device is stopped immediately. */
  29816. result = ma_device_stop_fd__audio4(pDevice, pDevice->audio4.fdPlayback);
  29817. if (result != MA_SUCCESS) {
  29818. return result;
  29819. }
  29820. }
  29821. return MA_SUCCESS;
  29822. }
  29823. static ma_result ma_device_write__audio4(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  29824. {
  29825. int result;
  29826. if (pFramesWritten != NULL) {
  29827. *pFramesWritten = 0;
  29828. }
  29829. result = write(pDevice->audio4.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  29830. if (result < 0) {
  29831. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to write data to the device.");
  29832. return ma_result_from_errno(errno);
  29833. }
  29834. if (pFramesWritten != NULL) {
  29835. *pFramesWritten = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  29836. }
  29837. return MA_SUCCESS;
  29838. }
  29839. static ma_result ma_device_read__audio4(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  29840. {
  29841. int result;
  29842. if (pFramesRead != NULL) {
  29843. *pFramesRead = 0;
  29844. }
  29845. result = read(pDevice->audio4.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  29846. if (result < 0) {
  29847. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[audio4] Failed to read data from the device.");
  29848. return ma_result_from_errno(errno);
  29849. }
  29850. if (pFramesRead != NULL) {
  29851. *pFramesRead = (ma_uint32)result / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  29852. }
  29853. return MA_SUCCESS;
  29854. }
  29855. static ma_result ma_context_uninit__audio4(ma_context* pContext)
  29856. {
  29857. MA_ASSERT(pContext != NULL);
  29858. MA_ASSERT(pContext->backend == ma_backend_audio4);
  29859. (void)pContext;
  29860. return MA_SUCCESS;
  29861. }
  29862. static ma_result ma_context_init__audio4(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  29863. {
  29864. MA_ASSERT(pContext != NULL);
  29865. (void)pConfig;
  29866. pCallbacks->onContextInit = ma_context_init__audio4;
  29867. pCallbacks->onContextUninit = ma_context_uninit__audio4;
  29868. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__audio4;
  29869. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__audio4;
  29870. pCallbacks->onDeviceInit = ma_device_init__audio4;
  29871. pCallbacks->onDeviceUninit = ma_device_uninit__audio4;
  29872. pCallbacks->onDeviceStart = ma_device_start__audio4;
  29873. pCallbacks->onDeviceStop = ma_device_stop__audio4;
  29874. pCallbacks->onDeviceRead = ma_device_read__audio4;
  29875. pCallbacks->onDeviceWrite = ma_device_write__audio4;
  29876. pCallbacks->onDeviceDataLoop = NULL;
  29877. return MA_SUCCESS;
  29878. }
  29879. #endif /* audio4 */
  29880. /******************************************************************************
  29881. OSS Backend
  29882. ******************************************************************************/
  29883. #ifdef MA_HAS_OSS
  29884. #include <sys/ioctl.h>
  29885. #include <unistd.h>
  29886. #include <fcntl.h>
  29887. #include <sys/soundcard.h>
  29888. #ifndef SNDCTL_DSP_HALT
  29889. #define SNDCTL_DSP_HALT SNDCTL_DSP_RESET
  29890. #endif
  29891. #define MA_OSS_DEFAULT_DEVICE_NAME "/dev/dsp"
  29892. static int ma_open_temp_device__oss()
  29893. {
  29894. /* The OSS sample code uses "/dev/mixer" as the device for getting system properties so I'm going to do the same. */
  29895. int fd = open("/dev/mixer", O_RDONLY, 0);
  29896. if (fd >= 0) {
  29897. return fd;
  29898. }
  29899. return -1;
  29900. }
  29901. 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)
  29902. {
  29903. const char* deviceName;
  29904. int flags;
  29905. MA_ASSERT(pContext != NULL);
  29906. MA_ASSERT(pfd != NULL);
  29907. (void)pContext;
  29908. *pfd = -1;
  29909. /* This function should only be called for playback or capture, not duplex. */
  29910. if (deviceType == ma_device_type_duplex) {
  29911. return MA_INVALID_ARGS;
  29912. }
  29913. deviceName = MA_OSS_DEFAULT_DEVICE_NAME;
  29914. if (pDeviceID != NULL) {
  29915. deviceName = pDeviceID->oss;
  29916. }
  29917. flags = (deviceType == ma_device_type_playback) ? O_WRONLY : O_RDONLY;
  29918. if (shareMode == ma_share_mode_exclusive) {
  29919. flags |= O_EXCL;
  29920. }
  29921. *pfd = open(deviceName, flags, 0);
  29922. if (*pfd == -1) {
  29923. return ma_result_from_errno(errno);
  29924. }
  29925. return MA_SUCCESS;
  29926. }
  29927. static ma_result ma_context_enumerate_devices__oss(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  29928. {
  29929. int fd;
  29930. oss_sysinfo si;
  29931. int result;
  29932. MA_ASSERT(pContext != NULL);
  29933. MA_ASSERT(callback != NULL);
  29934. fd = ma_open_temp_device__oss();
  29935. if (fd == -1) {
  29936. 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.");
  29937. return MA_NO_BACKEND;
  29938. }
  29939. result = ioctl(fd, SNDCTL_SYSINFO, &si);
  29940. if (result != -1) {
  29941. int iAudioDevice;
  29942. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  29943. oss_audioinfo ai;
  29944. ai.dev = iAudioDevice;
  29945. result = ioctl(fd, SNDCTL_AUDIOINFO, &ai);
  29946. if (result != -1) {
  29947. if (ai.devnode[0] != '\0') { /* <-- Can be blank, according to documentation. */
  29948. ma_device_info deviceInfo;
  29949. ma_bool32 isTerminating = MA_FALSE;
  29950. MA_ZERO_OBJECT(&deviceInfo);
  29951. /* ID */
  29952. ma_strncpy_s(deviceInfo.id.oss, sizeof(deviceInfo.id.oss), ai.devnode, (size_t)-1);
  29953. /*
  29954. The human readable device name should be in the "ai.handle" variable, but it can
  29955. sometimes be empty in which case we just fall back to "ai.name" which is less user
  29956. friendly, but usually has a value.
  29957. */
  29958. if (ai.handle[0] != '\0') {
  29959. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.handle, (size_t)-1);
  29960. } else {
  29961. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), ai.name, (size_t)-1);
  29962. }
  29963. /* The device can be both playback and capture. */
  29964. if (!isTerminating && (ai.caps & PCM_CAP_OUTPUT) != 0) {
  29965. isTerminating = !callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  29966. }
  29967. if (!isTerminating && (ai.caps & PCM_CAP_INPUT) != 0) {
  29968. isTerminating = !callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  29969. }
  29970. if (isTerminating) {
  29971. break;
  29972. }
  29973. }
  29974. }
  29975. }
  29976. } else {
  29977. close(fd);
  29978. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  29979. return MA_NO_BACKEND;
  29980. }
  29981. close(fd);
  29982. return MA_SUCCESS;
  29983. }
  29984. static void ma_context_add_native_data_format__oss(ma_context* pContext, oss_audioinfo* pAudioInfo, ma_format format, ma_device_info* pDeviceInfo)
  29985. {
  29986. unsigned int minChannels;
  29987. unsigned int maxChannels;
  29988. unsigned int iRate;
  29989. MA_ASSERT(pContext != NULL);
  29990. MA_ASSERT(pAudioInfo != NULL);
  29991. MA_ASSERT(pDeviceInfo != NULL);
  29992. /* If we support all channels we just report 0. */
  29993. minChannels = ma_clamp(pAudioInfo->min_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  29994. maxChannels = ma_clamp(pAudioInfo->max_channels, MA_MIN_CHANNELS, MA_MAX_CHANNELS);
  29995. /*
  29996. OSS has this annoying thing where sample rates can be reported in two ways. We prefer explicitness,
  29997. which OSS has in the form of nrates/rates, however there are times where nrates can be 0, in which
  29998. case we'll need to use min_rate and max_rate and report only standard rates.
  29999. */
  30000. if (pAudioInfo->nrates > 0) {
  30001. for (iRate = 0; iRate < pAudioInfo->nrates; iRate += 1) {
  30002. unsigned int rate = pAudioInfo->rates[iRate];
  30003. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30004. 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. */
  30005. } else {
  30006. unsigned int iChannel;
  30007. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30008. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, rate, 0);
  30009. }
  30010. }
  30011. }
  30012. } else {
  30013. for (iRate = 0; iRate < ma_countof(g_maStandardSampleRatePriorities); iRate += 1) {
  30014. ma_uint32 standardRate = g_maStandardSampleRatePriorities[iRate];
  30015. if (standardRate >= (ma_uint32)pAudioInfo->min_rate && standardRate <= (ma_uint32)pAudioInfo->max_rate) {
  30016. if (minChannels == MA_MIN_CHANNELS && maxChannels == MA_MAX_CHANNELS) {
  30017. 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. */
  30018. } else {
  30019. unsigned int iChannel;
  30020. for (iChannel = minChannels; iChannel <= maxChannels; iChannel += 1) {
  30021. ma_device_info_add_native_data_format(pDeviceInfo, format, iChannel, standardRate, 0);
  30022. }
  30023. }
  30024. }
  30025. }
  30026. }
  30027. }
  30028. 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)
  30029. {
  30030. ma_bool32 foundDevice;
  30031. int fdTemp;
  30032. oss_sysinfo si;
  30033. int result;
  30034. MA_ASSERT(pContext != NULL);
  30035. /* Handle the default device a little differently. */
  30036. if (pDeviceID == NULL) {
  30037. if (deviceType == ma_device_type_playback) {
  30038. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  30039. } else {
  30040. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  30041. }
  30042. return MA_SUCCESS;
  30043. }
  30044. /* If we get here it means we are _not_ using the default device. */
  30045. foundDevice = MA_FALSE;
  30046. fdTemp = ma_open_temp_device__oss();
  30047. if (fdTemp == -1) {
  30048. 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.");
  30049. return MA_NO_BACKEND;
  30050. }
  30051. result = ioctl(fdTemp, SNDCTL_SYSINFO, &si);
  30052. if (result != -1) {
  30053. int iAudioDevice;
  30054. for (iAudioDevice = 0; iAudioDevice < si.numaudios; ++iAudioDevice) {
  30055. oss_audioinfo ai;
  30056. ai.dev = iAudioDevice;
  30057. result = ioctl(fdTemp, SNDCTL_AUDIOINFO, &ai);
  30058. if (result != -1) {
  30059. if (ma_strcmp(ai.devnode, pDeviceID->oss) == 0) {
  30060. /* It has the same name, so now just confirm the type. */
  30061. if ((deviceType == ma_device_type_playback && ((ai.caps & PCM_CAP_OUTPUT) != 0)) ||
  30062. (deviceType == ma_device_type_capture && ((ai.caps & PCM_CAP_INPUT) != 0))) {
  30063. unsigned int formatMask;
  30064. /* ID */
  30065. ma_strncpy_s(pDeviceInfo->id.oss, sizeof(pDeviceInfo->id.oss), ai.devnode, (size_t)-1);
  30066. /*
  30067. The human readable device name should be in the "ai.handle" variable, but it can
  30068. sometimes be empty in which case we just fall back to "ai.name" which is less user
  30069. friendly, but usually has a value.
  30070. */
  30071. if (ai.handle[0] != '\0') {
  30072. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.handle, (size_t)-1);
  30073. } else {
  30074. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), ai.name, (size_t)-1);
  30075. }
  30076. pDeviceInfo->nativeDataFormatCount = 0;
  30077. if (deviceType == ma_device_type_playback) {
  30078. formatMask = ai.oformats;
  30079. } else {
  30080. formatMask = ai.iformats;
  30081. }
  30082. if (((formatMask & AFMT_S16_LE) != 0 && ma_is_little_endian()) || (AFMT_S16_BE && ma_is_big_endian())) {
  30083. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s16, pDeviceInfo);
  30084. }
  30085. if (((formatMask & AFMT_S32_LE) != 0 && ma_is_little_endian()) || (AFMT_S32_BE && ma_is_big_endian())) {
  30086. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_s32, pDeviceInfo);
  30087. }
  30088. if ((formatMask & AFMT_U8) != 0) {
  30089. ma_context_add_native_data_format__oss(pContext, &ai, ma_format_u8, pDeviceInfo);
  30090. }
  30091. foundDevice = MA_TRUE;
  30092. break;
  30093. }
  30094. }
  30095. }
  30096. }
  30097. } else {
  30098. close(fdTemp);
  30099. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve system information for device enumeration.");
  30100. return MA_NO_BACKEND;
  30101. }
  30102. close(fdTemp);
  30103. if (!foundDevice) {
  30104. return MA_NO_DEVICE;
  30105. }
  30106. return MA_SUCCESS;
  30107. }
  30108. static ma_result ma_device_uninit__oss(ma_device* pDevice)
  30109. {
  30110. MA_ASSERT(pDevice != NULL);
  30111. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30112. close(pDevice->oss.fdCapture);
  30113. }
  30114. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30115. close(pDevice->oss.fdPlayback);
  30116. }
  30117. return MA_SUCCESS;
  30118. }
  30119. static int ma_format_to_oss(ma_format format)
  30120. {
  30121. int ossFormat = AFMT_U8;
  30122. switch (format) {
  30123. case ma_format_s16: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  30124. case ma_format_s24: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  30125. case ma_format_s32: ossFormat = (ma_is_little_endian()) ? AFMT_S32_LE : AFMT_S32_BE; break;
  30126. case ma_format_f32: ossFormat = (ma_is_little_endian()) ? AFMT_S16_LE : AFMT_S16_BE; break;
  30127. case ma_format_u8:
  30128. default: ossFormat = AFMT_U8; break;
  30129. }
  30130. return ossFormat;
  30131. }
  30132. static ma_format ma_format_from_oss(int ossFormat)
  30133. {
  30134. if (ossFormat == AFMT_U8) {
  30135. return ma_format_u8;
  30136. } else {
  30137. if (ma_is_little_endian()) {
  30138. switch (ossFormat) {
  30139. case AFMT_S16_LE: return ma_format_s16;
  30140. case AFMT_S32_LE: return ma_format_s32;
  30141. default: return ma_format_unknown;
  30142. }
  30143. } else {
  30144. switch (ossFormat) {
  30145. case AFMT_S16_BE: return ma_format_s16;
  30146. case AFMT_S32_BE: return ma_format_s32;
  30147. default: return ma_format_unknown;
  30148. }
  30149. }
  30150. }
  30151. return ma_format_unknown;
  30152. }
  30153. static ma_result ma_device_init_fd__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  30154. {
  30155. ma_result result;
  30156. int ossResult;
  30157. int fd;
  30158. const ma_device_id* pDeviceID = NULL;
  30159. ma_share_mode shareMode;
  30160. int ossFormat;
  30161. int ossChannels;
  30162. int ossSampleRate;
  30163. int ossFragment;
  30164. MA_ASSERT(pDevice != NULL);
  30165. MA_ASSERT(pConfig != NULL);
  30166. MA_ASSERT(deviceType != ma_device_type_duplex);
  30167. pDeviceID = pDescriptor->pDeviceID;
  30168. shareMode = pDescriptor->shareMode;
  30169. 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. */
  30170. ossChannels = (int)(pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS;
  30171. ossSampleRate = (int)(pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  30172. result = ma_context_open_device__oss(pDevice->pContext, deviceType, pDeviceID, shareMode, &fd);
  30173. if (result != MA_SUCCESS) {
  30174. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  30175. return result;
  30176. }
  30177. /*
  30178. The OSS documantation is very clear about the order we should be initializing the device's properties:
  30179. 1) Format
  30180. 2) Channels
  30181. 3) Sample rate.
  30182. */
  30183. /* Format. */
  30184. ossResult = ioctl(fd, SNDCTL_DSP_SETFMT, &ossFormat);
  30185. if (ossResult == -1) {
  30186. close(fd);
  30187. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set format.");
  30188. return ma_result_from_errno(errno);
  30189. }
  30190. /* Channels. */
  30191. ossResult = ioctl(fd, SNDCTL_DSP_CHANNELS, &ossChannels);
  30192. if (ossResult == -1) {
  30193. close(fd);
  30194. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set channel count.");
  30195. return ma_result_from_errno(errno);
  30196. }
  30197. /* Sample Rate. */
  30198. ossResult = ioctl(fd, SNDCTL_DSP_SPEED, &ossSampleRate);
  30199. if (ossResult == -1) {
  30200. close(fd);
  30201. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set sample rate.");
  30202. return ma_result_from_errno(errno);
  30203. }
  30204. /*
  30205. Buffer.
  30206. The documentation says that the fragment settings should be set as soon as possible, but I'm not sure if
  30207. it should be done before or after format/channels/rate.
  30208. OSS wants the fragment size in bytes and a power of 2. When setting, we specify the power, not the actual
  30209. value.
  30210. */
  30211. {
  30212. ma_uint32 periodSizeInFrames;
  30213. ma_uint32 periodSizeInBytes;
  30214. ma_uint32 ossFragmentSizePower;
  30215. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, (ma_uint32)ossSampleRate, pConfig->performanceProfile);
  30216. periodSizeInBytes = ma_round_to_power_of_2(periodSizeInFrames * ma_get_bytes_per_frame(ma_format_from_oss(ossFormat), ossChannels));
  30217. if (periodSizeInBytes < 16) {
  30218. periodSizeInBytes = 16;
  30219. }
  30220. ossFragmentSizePower = 4;
  30221. periodSizeInBytes >>= 4;
  30222. while (periodSizeInBytes >>= 1) {
  30223. ossFragmentSizePower += 1;
  30224. }
  30225. ossFragment = (int)((pConfig->periods << 16) | ossFragmentSizePower);
  30226. ossResult = ioctl(fd, SNDCTL_DSP_SETFRAGMENT, &ossFragment);
  30227. if (ossResult == -1) {
  30228. close(fd);
  30229. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to set fragment size and period count.");
  30230. return ma_result_from_errno(errno);
  30231. }
  30232. }
  30233. /* Internal settings. */
  30234. if (deviceType == ma_device_type_capture) {
  30235. pDevice->oss.fdCapture = fd;
  30236. } else {
  30237. pDevice->oss.fdPlayback = fd;
  30238. }
  30239. pDescriptor->format = ma_format_from_oss(ossFormat);
  30240. pDescriptor->channels = ossChannels;
  30241. pDescriptor->sampleRate = ossSampleRate;
  30242. ma_channel_map_init_standard(ma_standard_channel_map_sound4, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels);
  30243. pDescriptor->periodCount = (ma_uint32)(ossFragment >> 16);
  30244. pDescriptor->periodSizeInFrames = (ma_uint32)(1 << (ossFragment & 0xFFFF)) / ma_get_bytes_per_frame(pDescriptor->format, pDescriptor->channels);
  30245. if (pDescriptor->format == ma_format_unknown) {
  30246. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] The device's internal format is not supported by miniaudio.");
  30247. return MA_FORMAT_NOT_SUPPORTED;
  30248. }
  30249. return MA_SUCCESS;
  30250. }
  30251. static ma_result ma_device_init__oss(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  30252. {
  30253. MA_ASSERT(pDevice != NULL);
  30254. MA_ASSERT(pConfig != NULL);
  30255. MA_ZERO_OBJECT(&pDevice->oss);
  30256. if (pConfig->deviceType == ma_device_type_loopback) {
  30257. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  30258. }
  30259. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  30260. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  30261. if (result != MA_SUCCESS) {
  30262. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  30263. return result;
  30264. }
  30265. }
  30266. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  30267. ma_result result = ma_device_init_fd__oss(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  30268. if (result != MA_SUCCESS) {
  30269. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to open device.");
  30270. return result;
  30271. }
  30272. }
  30273. return MA_SUCCESS;
  30274. }
  30275. /*
  30276. Note on Starting and Stopping
  30277. =============================
  30278. In the past I was using SNDCTL_DSP_HALT to stop the device, however this results in issues when
  30279. trying to resume the device again. If we use SNDCTL_DSP_HALT, the next write() or read() will
  30280. fail. Instead what we need to do is just not write or read to and from the device when the
  30281. device is not running.
  30282. As a result, both the start and stop functions for OSS are just empty stubs. The starting and
  30283. stopping logic is handled by ma_device_write__oss() and ma_device_read__oss(). These will check
  30284. the device state, and if the device is stopped they will simply not do any kind of processing.
  30285. The downside to this technique is that I've noticed a fairly lengthy delay in stopping the
  30286. device, up to a second. This is on a virtual machine, and as such might just be due to the
  30287. virtual drivers, but I'm not fully sure. I am not sure how to work around this problem so for
  30288. the moment that's just how it's going to have to be.
  30289. When starting the device, OSS will automatically start it when write() or read() is called.
  30290. */
  30291. static ma_result ma_device_start__oss(ma_device* pDevice)
  30292. {
  30293. MA_ASSERT(pDevice != NULL);
  30294. /* The device is automatically started with reading and writing. */
  30295. (void)pDevice;
  30296. return MA_SUCCESS;
  30297. }
  30298. static ma_result ma_device_stop__oss(ma_device* pDevice)
  30299. {
  30300. MA_ASSERT(pDevice != NULL);
  30301. /* See note above on why this is empty. */
  30302. (void)pDevice;
  30303. return MA_SUCCESS;
  30304. }
  30305. static ma_result ma_device_write__oss(ma_device* pDevice, const void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesWritten)
  30306. {
  30307. int resultOSS;
  30308. ma_uint32 deviceState;
  30309. if (pFramesWritten != NULL) {
  30310. *pFramesWritten = 0;
  30311. }
  30312. /* Don't do any processing if the device is stopped. */
  30313. deviceState = ma_device_get_state(pDevice);
  30314. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  30315. return MA_SUCCESS;
  30316. }
  30317. resultOSS = write(pDevice->oss.fdPlayback, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  30318. if (resultOSS < 0) {
  30319. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OSS] Failed to send data from the client to the device.");
  30320. return ma_result_from_errno(errno);
  30321. }
  30322. if (pFramesWritten != NULL) {
  30323. *pFramesWritten = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  30324. }
  30325. return MA_SUCCESS;
  30326. }
  30327. static ma_result ma_device_read__oss(ma_device* pDevice, void* pPCMFrames, ma_uint32 frameCount, ma_uint32* pFramesRead)
  30328. {
  30329. int resultOSS;
  30330. ma_uint32 deviceState;
  30331. if (pFramesRead != NULL) {
  30332. *pFramesRead = 0;
  30333. }
  30334. /* Don't do any processing if the device is stopped. */
  30335. deviceState = ma_device_get_state(pDevice);
  30336. if (deviceState != ma_device_state_started && deviceState != ma_device_state_starting) {
  30337. return MA_SUCCESS;
  30338. }
  30339. resultOSS = read(pDevice->oss.fdCapture, pPCMFrames, frameCount * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels));
  30340. if (resultOSS < 0) {
  30341. 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.");
  30342. return ma_result_from_errno(errno);
  30343. }
  30344. if (pFramesRead != NULL) {
  30345. *pFramesRead = (ma_uint32)resultOSS / ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  30346. }
  30347. return MA_SUCCESS;
  30348. }
  30349. static ma_result ma_context_uninit__oss(ma_context* pContext)
  30350. {
  30351. MA_ASSERT(pContext != NULL);
  30352. MA_ASSERT(pContext->backend == ma_backend_oss);
  30353. (void)pContext;
  30354. return MA_SUCCESS;
  30355. }
  30356. static ma_result ma_context_init__oss(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  30357. {
  30358. int fd;
  30359. int ossVersion;
  30360. int result;
  30361. MA_ASSERT(pContext != NULL);
  30362. (void)pConfig;
  30363. /* Try opening a temporary device first so we can get version information. This is closed at the end. */
  30364. fd = ma_open_temp_device__oss();
  30365. if (fd == -1) {
  30366. 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. */
  30367. return MA_NO_BACKEND;
  30368. }
  30369. /* Grab the OSS version. */
  30370. ossVersion = 0;
  30371. result = ioctl(fd, OSS_GETVERSION, &ossVersion);
  30372. if (result == -1) {
  30373. close(fd);
  30374. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_ERROR, "[OSS] Failed to retrieve OSS version.");
  30375. return MA_NO_BACKEND;
  30376. }
  30377. /* The file handle to temp device is no longer needed. Close ASAP. */
  30378. close(fd);
  30379. pContext->oss.versionMajor = ((ossVersion & 0xFF0000) >> 16);
  30380. pContext->oss.versionMinor = ((ossVersion & 0x00FF00) >> 8);
  30381. pCallbacks->onContextInit = ma_context_init__oss;
  30382. pCallbacks->onContextUninit = ma_context_uninit__oss;
  30383. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__oss;
  30384. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__oss;
  30385. pCallbacks->onDeviceInit = ma_device_init__oss;
  30386. pCallbacks->onDeviceUninit = ma_device_uninit__oss;
  30387. pCallbacks->onDeviceStart = ma_device_start__oss;
  30388. pCallbacks->onDeviceStop = ma_device_stop__oss;
  30389. pCallbacks->onDeviceRead = ma_device_read__oss;
  30390. pCallbacks->onDeviceWrite = ma_device_write__oss;
  30391. pCallbacks->onDeviceDataLoop = NULL;
  30392. return MA_SUCCESS;
  30393. }
  30394. #endif /* OSS */
  30395. /******************************************************************************
  30396. AAudio Backend
  30397. ******************************************************************************/
  30398. #ifdef MA_HAS_AAUDIO
  30399. /*#include <AAudio/AAudio.h>*/
  30400. typedef int32_t ma_aaudio_result_t;
  30401. typedef int32_t ma_aaudio_direction_t;
  30402. typedef int32_t ma_aaudio_sharing_mode_t;
  30403. typedef int32_t ma_aaudio_format_t;
  30404. typedef int32_t ma_aaudio_stream_state_t;
  30405. typedef int32_t ma_aaudio_performance_mode_t;
  30406. typedef int32_t ma_aaudio_usage_t;
  30407. typedef int32_t ma_aaudio_content_type_t;
  30408. typedef int32_t ma_aaudio_input_preset_t;
  30409. typedef int32_t ma_aaudio_data_callback_result_t;
  30410. typedef struct ma_AAudioStreamBuilder_t* ma_AAudioStreamBuilder;
  30411. typedef struct ma_AAudioStream_t* ma_AAudioStream;
  30412. #define MA_AAUDIO_UNSPECIFIED 0
  30413. /* Result codes. miniaudio only cares about the success code. */
  30414. #define MA_AAUDIO_OK 0
  30415. /* Directions. */
  30416. #define MA_AAUDIO_DIRECTION_OUTPUT 0
  30417. #define MA_AAUDIO_DIRECTION_INPUT 1
  30418. /* Sharing modes. */
  30419. #define MA_AAUDIO_SHARING_MODE_EXCLUSIVE 0
  30420. #define MA_AAUDIO_SHARING_MODE_SHARED 1
  30421. /* Formats. */
  30422. #define MA_AAUDIO_FORMAT_PCM_I16 1
  30423. #define MA_AAUDIO_FORMAT_PCM_FLOAT 2
  30424. /* Stream states. */
  30425. #define MA_AAUDIO_STREAM_STATE_UNINITIALIZED 0
  30426. #define MA_AAUDIO_STREAM_STATE_UNKNOWN 1
  30427. #define MA_AAUDIO_STREAM_STATE_OPEN 2
  30428. #define MA_AAUDIO_STREAM_STATE_STARTING 3
  30429. #define MA_AAUDIO_STREAM_STATE_STARTED 4
  30430. #define MA_AAUDIO_STREAM_STATE_PAUSING 5
  30431. #define MA_AAUDIO_STREAM_STATE_PAUSED 6
  30432. #define MA_AAUDIO_STREAM_STATE_FLUSHING 7
  30433. #define MA_AAUDIO_STREAM_STATE_FLUSHED 8
  30434. #define MA_AAUDIO_STREAM_STATE_STOPPING 9
  30435. #define MA_AAUDIO_STREAM_STATE_STOPPED 10
  30436. #define MA_AAUDIO_STREAM_STATE_CLOSING 11
  30437. #define MA_AAUDIO_STREAM_STATE_CLOSED 12
  30438. #define MA_AAUDIO_STREAM_STATE_DISCONNECTED 13
  30439. /* Performance modes. */
  30440. #define MA_AAUDIO_PERFORMANCE_MODE_NONE 10
  30441. #define MA_AAUDIO_PERFORMANCE_MODE_POWER_SAVING 11
  30442. #define MA_AAUDIO_PERFORMANCE_MODE_LOW_LATENCY 12
  30443. /* Usage types. */
  30444. #define MA_AAUDIO_USAGE_MEDIA 1
  30445. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION 2
  30446. #define MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING 3
  30447. #define MA_AAUDIO_USAGE_ALARM 4
  30448. #define MA_AAUDIO_USAGE_NOTIFICATION 5
  30449. #define MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE 6
  30450. #define MA_AAUDIO_USAGE_NOTIFICATION_EVENT 10
  30451. #define MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY 11
  30452. #define MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE 12
  30453. #define MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION 13
  30454. #define MA_AAUDIO_USAGE_GAME 14
  30455. #define MA_AAUDIO_USAGE_ASSISTANT 16
  30456. #define MA_AAUDIO_SYSTEM_USAGE_EMERGENCY 1000
  30457. #define MA_AAUDIO_SYSTEM_USAGE_SAFETY 1001
  30458. #define MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS 1002
  30459. #define MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT 1003
  30460. /* Content types. */
  30461. #define MA_AAUDIO_CONTENT_TYPE_SPEECH 1
  30462. #define MA_AAUDIO_CONTENT_TYPE_MUSIC 2
  30463. #define MA_AAUDIO_CONTENT_TYPE_MOVIE 3
  30464. #define MA_AAUDIO_CONTENT_TYPE_SONIFICATION 4
  30465. /* Input presets. */
  30466. #define MA_AAUDIO_INPUT_PRESET_GENERIC 1
  30467. #define MA_AAUDIO_INPUT_PRESET_CAMCORDER 5
  30468. #define MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION 6
  30469. #define MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION 7
  30470. #define MA_AAUDIO_INPUT_PRESET_UNPROCESSED 9
  30471. #define MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE 10
  30472. /* Callback results. */
  30473. #define MA_AAUDIO_CALLBACK_RESULT_CONTINUE 0
  30474. #define MA_AAUDIO_CALLBACK_RESULT_STOP 1
  30475. typedef ma_aaudio_data_callback_result_t (* ma_AAudioStream_dataCallback) (ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t numFrames);
  30476. typedef void (* ma_AAudioStream_errorCallback)(ma_AAudioStream *pStream, void *pUserData, ma_aaudio_result_t error);
  30477. typedef ma_aaudio_result_t (* MA_PFN_AAudio_createStreamBuilder) (ma_AAudioStreamBuilder** ppBuilder);
  30478. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_delete) (ma_AAudioStreamBuilder* pBuilder);
  30479. typedef void (* MA_PFN_AAudioStreamBuilder_setDeviceId) (ma_AAudioStreamBuilder* pBuilder, int32_t deviceId);
  30480. typedef void (* MA_PFN_AAudioStreamBuilder_setDirection) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_direction_t direction);
  30481. typedef void (* MA_PFN_AAudioStreamBuilder_setSharingMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_sharing_mode_t sharingMode);
  30482. typedef void (* MA_PFN_AAudioStreamBuilder_setFormat) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_format_t format);
  30483. typedef void (* MA_PFN_AAudioStreamBuilder_setChannelCount) (ma_AAudioStreamBuilder* pBuilder, int32_t channelCount);
  30484. typedef void (* MA_PFN_AAudioStreamBuilder_setSampleRate) (ma_AAudioStreamBuilder* pBuilder, int32_t sampleRate);
  30485. typedef void (* MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)(ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  30486. typedef void (* MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback) (ma_AAudioStreamBuilder* pBuilder, int32_t numFrames);
  30487. typedef void (* MA_PFN_AAudioStreamBuilder_setDataCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_dataCallback callback, void* pUserData);
  30488. typedef void (* MA_PFN_AAudioStreamBuilder_setErrorCallback) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream_errorCallback callback, void* pUserData);
  30489. typedef void (* MA_PFN_AAudioStreamBuilder_setPerformanceMode) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_performance_mode_t mode);
  30490. typedef void (* MA_PFN_AAudioStreamBuilder_setUsage) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_usage_t contentType);
  30491. typedef void (* MA_PFN_AAudioStreamBuilder_setContentType) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_content_type_t contentType);
  30492. typedef void (* MA_PFN_AAudioStreamBuilder_setInputPreset) (ma_AAudioStreamBuilder* pBuilder, ma_aaudio_input_preset_t inputPreset);
  30493. typedef ma_aaudio_result_t (* MA_PFN_AAudioStreamBuilder_openStream) (ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream);
  30494. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_close) (ma_AAudioStream* pStream);
  30495. typedef ma_aaudio_stream_state_t (* MA_PFN_AAudioStream_getState) (ma_AAudioStream* pStream);
  30496. 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);
  30497. typedef ma_aaudio_format_t (* MA_PFN_AAudioStream_getFormat) (ma_AAudioStream* pStream);
  30498. typedef int32_t (* MA_PFN_AAudioStream_getChannelCount) (ma_AAudioStream* pStream);
  30499. typedef int32_t (* MA_PFN_AAudioStream_getSampleRate) (ma_AAudioStream* pStream);
  30500. typedef int32_t (* MA_PFN_AAudioStream_getBufferCapacityInFrames) (ma_AAudioStream* pStream);
  30501. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerDataCallback) (ma_AAudioStream* pStream);
  30502. typedef int32_t (* MA_PFN_AAudioStream_getFramesPerBurst) (ma_AAudioStream* pStream);
  30503. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStart) (ma_AAudioStream* pStream);
  30504. typedef ma_aaudio_result_t (* MA_PFN_AAudioStream_requestStop) (ma_AAudioStream* pStream);
  30505. static ma_result ma_result_from_aaudio(ma_aaudio_result_t resultAA)
  30506. {
  30507. switch (resultAA)
  30508. {
  30509. case MA_AAUDIO_OK: return MA_SUCCESS;
  30510. default: break;
  30511. }
  30512. return MA_ERROR;
  30513. }
  30514. static ma_aaudio_usage_t ma_to_usage__aaudio(ma_aaudio_usage usage)
  30515. {
  30516. switch (usage) {
  30517. case ma_aaudio_usage_media: return MA_AAUDIO_USAGE_MEDIA;
  30518. case ma_aaudio_usage_voice_communication: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION;
  30519. case ma_aaudio_usage_voice_communication_signalling: return MA_AAUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING;
  30520. case ma_aaudio_usage_alarm: return MA_AAUDIO_USAGE_ALARM;
  30521. case ma_aaudio_usage_notification: return MA_AAUDIO_USAGE_NOTIFICATION;
  30522. case ma_aaudio_usage_notification_ringtone: return MA_AAUDIO_USAGE_NOTIFICATION_RINGTONE;
  30523. case ma_aaudio_usage_notification_event: return MA_AAUDIO_USAGE_NOTIFICATION_EVENT;
  30524. case ma_aaudio_usage_assistance_accessibility: return MA_AAUDIO_USAGE_ASSISTANCE_ACCESSIBILITY;
  30525. case ma_aaudio_usage_assistance_navigation_guidance: return MA_AAUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE;
  30526. case ma_aaudio_usage_assistance_sonification: return MA_AAUDIO_USAGE_ASSISTANCE_SONIFICATION;
  30527. case ma_aaudio_usage_game: return MA_AAUDIO_USAGE_GAME;
  30528. case ma_aaudio_usage_assitant: return MA_AAUDIO_USAGE_ASSISTANT;
  30529. case ma_aaudio_usage_emergency: return MA_AAUDIO_SYSTEM_USAGE_EMERGENCY;
  30530. case ma_aaudio_usage_safety: return MA_AAUDIO_SYSTEM_USAGE_SAFETY;
  30531. case ma_aaudio_usage_vehicle_status: return MA_AAUDIO_SYSTEM_USAGE_VEHICLE_STATUS;
  30532. case ma_aaudio_usage_announcement: return MA_AAUDIO_SYSTEM_USAGE_ANNOUNCEMENT;
  30533. default: break;
  30534. }
  30535. return MA_AAUDIO_USAGE_MEDIA;
  30536. }
  30537. static ma_aaudio_content_type_t ma_to_content_type__aaudio(ma_aaudio_content_type contentType)
  30538. {
  30539. switch (contentType) {
  30540. case ma_aaudio_content_type_speech: return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  30541. case ma_aaudio_content_type_music: return MA_AAUDIO_CONTENT_TYPE_MUSIC;
  30542. case ma_aaudio_content_type_movie: return MA_AAUDIO_CONTENT_TYPE_MOVIE;
  30543. case ma_aaudio_content_type_sonification: return MA_AAUDIO_CONTENT_TYPE_SONIFICATION;
  30544. default: break;
  30545. }
  30546. return MA_AAUDIO_CONTENT_TYPE_SPEECH;
  30547. }
  30548. static ma_aaudio_input_preset_t ma_to_input_preset__aaudio(ma_aaudio_input_preset inputPreset)
  30549. {
  30550. switch (inputPreset) {
  30551. case ma_aaudio_input_preset_generic: return MA_AAUDIO_INPUT_PRESET_GENERIC;
  30552. case ma_aaudio_input_preset_camcorder: return MA_AAUDIO_INPUT_PRESET_CAMCORDER;
  30553. case ma_aaudio_input_preset_voice_recognition: return MA_AAUDIO_INPUT_PRESET_VOICE_RECOGNITION;
  30554. case ma_aaudio_input_preset_voice_communication: return MA_AAUDIO_INPUT_PRESET_VOICE_COMMUNICATION;
  30555. case ma_aaudio_input_preset_unprocessed: return MA_AAUDIO_INPUT_PRESET_UNPROCESSED;
  30556. case ma_aaudio_input_preset_voice_performance: return MA_AAUDIO_INPUT_PRESET_VOICE_PERFORMANCE;
  30557. default: break;
  30558. }
  30559. return MA_AAUDIO_INPUT_PRESET_GENERIC;
  30560. }
  30561. static void ma_stream_error_callback__aaudio(ma_AAudioStream* pStream, void* pUserData, ma_aaudio_result_t error)
  30562. {
  30563. ma_device* pDevice = (ma_device*)pUserData;
  30564. MA_ASSERT(pDevice != NULL);
  30565. (void)error;
  30566. 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));
  30567. /*
  30568. From the documentation for AAudio, when a device is disconnected all we can do is stop it. However, we cannot stop it from the callback - we need
  30569. to do it from another thread. Therefore we are going to use an event thread for the AAudio backend to do this cleanly and safely.
  30570. */
  30571. if (((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream) == MA_AAUDIO_STREAM_STATE_DISCONNECTED) {
  30572. /* We need to post a job to the job thread for processing. This will reroute the device by reinitializing the stream. */
  30573. ma_result result;
  30574. ma_job job = ma_job_init(MA_JOB_TYPE_DEVICE_AAUDIO_REROUTE);
  30575. job.data.device.aaudio.reroute.pDevice = pDevice;
  30576. if (pStream == pDevice->aaudio.pStreamCapture) {
  30577. job.data.device.aaudio.reroute.deviceType = ma_device_type_capture;
  30578. } else {
  30579. job.data.device.aaudio.reroute.deviceType = ma_device_type_playback;
  30580. }
  30581. result = ma_device_job_thread_post(&pDevice->pContext->aaudio.jobThread, &job);
  30582. if (result != MA_SUCCESS) {
  30583. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[AAudio] Device Disconnected. Failed to post job for rerouting.\n");
  30584. return;
  30585. }
  30586. }
  30587. }
  30588. static ma_aaudio_data_callback_result_t ma_stream_data_callback_capture__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  30589. {
  30590. ma_device* pDevice = (ma_device*)pUserData;
  30591. MA_ASSERT(pDevice != NULL);
  30592. ma_device_handle_backend_data_callback(pDevice, NULL, pAudioData, frameCount);
  30593. (void)pStream;
  30594. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  30595. }
  30596. static ma_aaudio_data_callback_result_t ma_stream_data_callback_playback__aaudio(ma_AAudioStream* pStream, void* pUserData, void* pAudioData, int32_t frameCount)
  30597. {
  30598. ma_device* pDevice = (ma_device*)pUserData;
  30599. MA_ASSERT(pDevice != NULL);
  30600. ma_device_handle_backend_data_callback(pDevice, pAudioData, NULL, frameCount);
  30601. (void)pStream;
  30602. return MA_AAUDIO_CALLBACK_RESULT_CONTINUE;
  30603. }
  30604. 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)
  30605. {
  30606. ma_AAudioStreamBuilder* pBuilder;
  30607. ma_aaudio_result_t resultAA;
  30608. ma_uint32 bufferCapacityInFrames;
  30609. /* Safety. */
  30610. *ppBuilder = NULL;
  30611. resultAA = ((MA_PFN_AAudio_createStreamBuilder)pContext->aaudio.AAudio_createStreamBuilder)(&pBuilder);
  30612. if (resultAA != MA_AAUDIO_OK) {
  30613. return ma_result_from_aaudio(resultAA);
  30614. }
  30615. if (pDeviceID != NULL) {
  30616. ((MA_PFN_AAudioStreamBuilder_setDeviceId)pContext->aaudio.AAudioStreamBuilder_setDeviceId)(pBuilder, pDeviceID->aaudio);
  30617. }
  30618. ((MA_PFN_AAudioStreamBuilder_setDirection)pContext->aaudio.AAudioStreamBuilder_setDirection)(pBuilder, (deviceType == ma_device_type_playback) ? MA_AAUDIO_DIRECTION_OUTPUT : MA_AAUDIO_DIRECTION_INPUT);
  30619. ((MA_PFN_AAudioStreamBuilder_setSharingMode)pContext->aaudio.AAudioStreamBuilder_setSharingMode)(pBuilder, (shareMode == ma_share_mode_shared) ? MA_AAUDIO_SHARING_MODE_SHARED : MA_AAUDIO_SHARING_MODE_EXCLUSIVE);
  30620. /* If we have a device descriptor make sure we configure the stream builder to take our requested parameters. */
  30621. if (pDescriptor != NULL) {
  30622. 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. */
  30623. if (pDescriptor->sampleRate != 0) {
  30624. ((MA_PFN_AAudioStreamBuilder_setSampleRate)pContext->aaudio.AAudioStreamBuilder_setSampleRate)(pBuilder, pDescriptor->sampleRate);
  30625. }
  30626. if (deviceType == ma_device_type_capture) {
  30627. if (pDescriptor->channels != 0) {
  30628. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  30629. }
  30630. if (pDescriptor->format != ma_format_unknown) {
  30631. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  30632. }
  30633. } else {
  30634. if (pDescriptor->channels != 0) {
  30635. ((MA_PFN_AAudioStreamBuilder_setChannelCount)pContext->aaudio.AAudioStreamBuilder_setChannelCount)(pBuilder, pDescriptor->channels);
  30636. }
  30637. if (pDescriptor->format != ma_format_unknown) {
  30638. ((MA_PFN_AAudioStreamBuilder_setFormat)pContext->aaudio.AAudioStreamBuilder_setFormat)(pBuilder, (pDescriptor->format == ma_format_s16) ? MA_AAUDIO_FORMAT_PCM_I16 : MA_AAUDIO_FORMAT_PCM_FLOAT);
  30639. }
  30640. }
  30641. /*
  30642. AAudio is annoying when it comes to it's buffer calculation stuff because it doesn't let you
  30643. retrieve the actual sample rate until after you've opened the stream. But you need to configure
  30644. the buffer capacity before you open the stream... :/
  30645. To solve, we're just going to assume MA_DEFAULT_SAMPLE_RATE (48000) and move on.
  30646. */
  30647. bufferCapacityInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptor, pDescriptor->sampleRate, pConfig->performanceProfile) * pDescriptor->periodCount;
  30648. ((MA_PFN_AAudioStreamBuilder_setBufferCapacityInFrames)pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames)(pBuilder, bufferCapacityInFrames);
  30649. ((MA_PFN_AAudioStreamBuilder_setFramesPerDataCallback)pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback)(pBuilder, bufferCapacityInFrames / pDescriptor->periodCount);
  30650. if (deviceType == ma_device_type_capture) {
  30651. if (pConfig->aaudio.inputPreset != ma_aaudio_input_preset_default && pContext->aaudio.AAudioStreamBuilder_setInputPreset != NULL) {
  30652. ((MA_PFN_AAudioStreamBuilder_setInputPreset)pContext->aaudio.AAudioStreamBuilder_setInputPreset)(pBuilder, ma_to_input_preset__aaudio(pConfig->aaudio.inputPreset));
  30653. }
  30654. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_capture__aaudio, (void*)pDevice);
  30655. } else {
  30656. if (pConfig->aaudio.usage != ma_aaudio_usage_default && pContext->aaudio.AAudioStreamBuilder_setUsage != NULL) {
  30657. ((MA_PFN_AAudioStreamBuilder_setUsage)pContext->aaudio.AAudioStreamBuilder_setUsage)(pBuilder, ma_to_usage__aaudio(pConfig->aaudio.usage));
  30658. }
  30659. if (pConfig->aaudio.contentType != ma_aaudio_content_type_default && pContext->aaudio.AAudioStreamBuilder_setContentType != NULL) {
  30660. ((MA_PFN_AAudioStreamBuilder_setContentType)pContext->aaudio.AAudioStreamBuilder_setContentType)(pBuilder, ma_to_content_type__aaudio(pConfig->aaudio.contentType));
  30661. }
  30662. ((MA_PFN_AAudioStreamBuilder_setDataCallback)pContext->aaudio.AAudioStreamBuilder_setDataCallback)(pBuilder, ma_stream_data_callback_playback__aaudio, (void*)pDevice);
  30663. }
  30664. /* 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. */
  30665. ((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);
  30666. /* We need to set an error callback to detect device changes. */
  30667. 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. */
  30668. ((MA_PFN_AAudioStreamBuilder_setErrorCallback)pContext->aaudio.AAudioStreamBuilder_setErrorCallback)(pBuilder, ma_stream_error_callback__aaudio, (void*)pDevice);
  30669. }
  30670. }
  30671. *ppBuilder = pBuilder;
  30672. return MA_SUCCESS;
  30673. }
  30674. static ma_result ma_open_stream_and_close_builder__aaudio(ma_context* pContext, ma_AAudioStreamBuilder* pBuilder, ma_AAudioStream** ppStream)
  30675. {
  30676. ma_result result;
  30677. result = ma_result_from_aaudio(((MA_PFN_AAudioStreamBuilder_openStream)pContext->aaudio.AAudioStreamBuilder_openStream)(pBuilder, ppStream));
  30678. ((MA_PFN_AAudioStreamBuilder_delete)pContext->aaudio.AAudioStreamBuilder_delete)(pBuilder);
  30679. return result;
  30680. }
  30681. 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)
  30682. {
  30683. ma_result result;
  30684. ma_AAudioStreamBuilder* pBuilder;
  30685. *ppStream = NULL;
  30686. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pContext, pDeviceID, deviceType, shareMode, NULL, NULL, NULL, &pBuilder);
  30687. if (result != MA_SUCCESS) {
  30688. return result;
  30689. }
  30690. return ma_open_stream_and_close_builder__aaudio(pContext, pBuilder, ppStream);
  30691. }
  30692. 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)
  30693. {
  30694. ma_result result;
  30695. ma_AAudioStreamBuilder* pBuilder;
  30696. MA_ASSERT(pDevice != NULL);
  30697. MA_ASSERT(pDescriptor != NULL);
  30698. MA_ASSERT(deviceType != ma_device_type_duplex); /* This function should not be called for a full-duplex device type. */
  30699. *ppStream = NULL;
  30700. result = ma_create_and_configure_AAudioStreamBuilder__aaudio(pDevice->pContext, pDescriptor->pDeviceID, deviceType, pDescriptor->shareMode, pDescriptor, pConfig, pDevice, &pBuilder);
  30701. if (result != MA_SUCCESS) {
  30702. return result;
  30703. }
  30704. return ma_open_stream_and_close_builder__aaudio(pDevice->pContext, pBuilder, ppStream);
  30705. }
  30706. static ma_result ma_close_stream__aaudio(ma_context* pContext, ma_AAudioStream* pStream)
  30707. {
  30708. return ma_result_from_aaudio(((MA_PFN_AAudioStream_close)pContext->aaudio.AAudioStream_close)(pStream));
  30709. }
  30710. static ma_bool32 ma_has_default_device__aaudio(ma_context* pContext, ma_device_type deviceType)
  30711. {
  30712. /* The only way to know this is to try creating a stream. */
  30713. ma_AAudioStream* pStream;
  30714. ma_result result = ma_open_stream_basic__aaudio(pContext, NULL, deviceType, ma_share_mode_shared, &pStream);
  30715. if (result != MA_SUCCESS) {
  30716. return MA_FALSE;
  30717. }
  30718. ma_close_stream__aaudio(pContext, pStream);
  30719. return MA_TRUE;
  30720. }
  30721. 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)
  30722. {
  30723. ma_aaudio_stream_state_t actualNewState;
  30724. ma_aaudio_result_t resultAA = ((MA_PFN_AAudioStream_waitForStateChange)pContext->aaudio.AAudioStream_waitForStateChange)(pStream, oldState, &actualNewState, 5000000000); /* 5 second timeout. */
  30725. if (resultAA != MA_AAUDIO_OK) {
  30726. return ma_result_from_aaudio(resultAA);
  30727. }
  30728. if (newState != actualNewState) {
  30729. return MA_ERROR; /* Failed to transition into the expected state. */
  30730. }
  30731. return MA_SUCCESS;
  30732. }
  30733. static ma_result ma_context_enumerate_devices__aaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  30734. {
  30735. ma_bool32 cbResult = MA_TRUE;
  30736. MA_ASSERT(pContext != NULL);
  30737. MA_ASSERT(callback != NULL);
  30738. /* 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. */
  30739. /* Playback. */
  30740. if (cbResult) {
  30741. ma_device_info deviceInfo;
  30742. MA_ZERO_OBJECT(&deviceInfo);
  30743. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  30744. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  30745. if (ma_has_default_device__aaudio(pContext, ma_device_type_playback)) {
  30746. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  30747. }
  30748. }
  30749. /* Capture. */
  30750. if (cbResult) {
  30751. ma_device_info deviceInfo;
  30752. MA_ZERO_OBJECT(&deviceInfo);
  30753. deviceInfo.id.aaudio = MA_AAUDIO_UNSPECIFIED;
  30754. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  30755. if (ma_has_default_device__aaudio(pContext, ma_device_type_capture)) {
  30756. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  30757. }
  30758. }
  30759. return MA_SUCCESS;
  30760. }
  30761. 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)
  30762. {
  30763. MA_ASSERT(pContext != NULL);
  30764. MA_ASSERT(pStream != NULL);
  30765. MA_ASSERT(pDeviceInfo != NULL);
  30766. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  30767. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = ((MA_PFN_AAudioStream_getChannelCount)pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  30768. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  30769. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = flags;
  30770. pDeviceInfo->nativeDataFormatCount += 1;
  30771. }
  30772. static void ma_context_add_native_data_format_from_AAudioStream__aaudio(ma_context* pContext, ma_AAudioStream* pStream, ma_uint32 flags, ma_device_info* pDeviceInfo)
  30773. {
  30774. /* AAudio supports s16 and f32. */
  30775. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_f32, flags, pDeviceInfo);
  30776. ma_context_add_native_data_format_from_AAudioStream_ex__aaudio(pContext, pStream, ma_format_s16, flags, pDeviceInfo);
  30777. }
  30778. 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)
  30779. {
  30780. ma_AAudioStream* pStream;
  30781. ma_result result;
  30782. MA_ASSERT(pContext != NULL);
  30783. /* ID */
  30784. if (pDeviceID != NULL) {
  30785. pDeviceInfo->id.aaudio = pDeviceID->aaudio;
  30786. } else {
  30787. pDeviceInfo->id.aaudio = MA_AAUDIO_UNSPECIFIED;
  30788. }
  30789. /* Name */
  30790. if (deviceType == ma_device_type_playback) {
  30791. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  30792. } else {
  30793. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  30794. }
  30795. pDeviceInfo->nativeDataFormatCount = 0;
  30796. /* We'll need to open the device to get accurate sample rate and channel count information. */
  30797. result = ma_open_stream_basic__aaudio(pContext, pDeviceID, deviceType, ma_share_mode_shared, &pStream);
  30798. if (result != MA_SUCCESS) {
  30799. return result;
  30800. }
  30801. ma_context_add_native_data_format_from_AAudioStream__aaudio(pContext, pStream, 0, pDeviceInfo);
  30802. ma_close_stream__aaudio(pContext, pStream);
  30803. pStream = NULL;
  30804. return MA_SUCCESS;
  30805. }
  30806. static ma_result ma_device_uninit__aaudio(ma_device* pDevice)
  30807. {
  30808. MA_ASSERT(pDevice != NULL);
  30809. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30810. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  30811. pDevice->aaudio.pStreamCapture = NULL;
  30812. }
  30813. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30814. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  30815. pDevice->aaudio.pStreamPlayback = NULL;
  30816. }
  30817. return MA_SUCCESS;
  30818. }
  30819. 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)
  30820. {
  30821. ma_result result;
  30822. int32_t bufferCapacityInFrames;
  30823. int32_t framesPerDataCallback;
  30824. ma_AAudioStream* pStream;
  30825. MA_ASSERT(pDevice != NULL);
  30826. MA_ASSERT(pConfig != NULL);
  30827. MA_ASSERT(pDescriptor != NULL);
  30828. *ppStream = NULL; /* Safety. */
  30829. /* First step is to open the stream. From there we'll be able to extract the internal configuration. */
  30830. result = ma_open_stream__aaudio(pDevice, pConfig, deviceType, pDescriptor, &pStream);
  30831. if (result != MA_SUCCESS) {
  30832. return result; /* Failed to open the AAudio stream. */
  30833. }
  30834. /* Now extract the internal configuration. */
  30835. pDescriptor->format = (((MA_PFN_AAudioStream_getFormat)pDevice->pContext->aaudio.AAudioStream_getFormat)(pStream) == MA_AAUDIO_FORMAT_PCM_I16) ? ma_format_s16 : ma_format_f32;
  30836. pDescriptor->channels = ((MA_PFN_AAudioStream_getChannelCount)pDevice->pContext->aaudio.AAudioStream_getChannelCount)(pStream);
  30837. pDescriptor->sampleRate = ((MA_PFN_AAudioStream_getSampleRate)pDevice->pContext->aaudio.AAudioStream_getSampleRate)(pStream);
  30838. /* For the channel map we need to be sure we don't overflow any buffers. */
  30839. if (pDescriptor->channels <= MA_MAX_CHANNELS) {
  30840. 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. */
  30841. } else {
  30842. ma_channel_map_init_blank(pDescriptor->channelMap, MA_MAX_CHANNELS); /* Too many channels. Use a blank channel map. */
  30843. }
  30844. bufferCapacityInFrames = ((MA_PFN_AAudioStream_getBufferCapacityInFrames)pDevice->pContext->aaudio.AAudioStream_getBufferCapacityInFrames)(pStream);
  30845. framesPerDataCallback = ((MA_PFN_AAudioStream_getFramesPerDataCallback)pDevice->pContext->aaudio.AAudioStream_getFramesPerDataCallback)(pStream);
  30846. if (framesPerDataCallback > 0) {
  30847. pDescriptor->periodSizeInFrames = framesPerDataCallback;
  30848. pDescriptor->periodCount = bufferCapacityInFrames / framesPerDataCallback;
  30849. } else {
  30850. pDescriptor->periodSizeInFrames = bufferCapacityInFrames;
  30851. pDescriptor->periodCount = 1;
  30852. }
  30853. *ppStream = pStream;
  30854. return MA_SUCCESS;
  30855. }
  30856. static ma_result ma_device_init__aaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  30857. {
  30858. ma_result result;
  30859. MA_ASSERT(pDevice != NULL);
  30860. if (pConfig->deviceType == ma_device_type_loopback) {
  30861. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  30862. }
  30863. pDevice->aaudio.usage = pConfig->aaudio.usage;
  30864. pDevice->aaudio.contentType = pConfig->aaudio.contentType;
  30865. pDevice->aaudio.inputPreset = pConfig->aaudio.inputPreset;
  30866. pDevice->aaudio.noAutoStartAfterReroute = pConfig->aaudio.noAutoStartAfterReroute;
  30867. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  30868. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_capture, pDescriptorCapture, (ma_AAudioStream**)&pDevice->aaudio.pStreamCapture);
  30869. if (result != MA_SUCCESS) {
  30870. return result;
  30871. }
  30872. }
  30873. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  30874. result = ma_device_init_by_type__aaudio(pDevice, pConfig, ma_device_type_playback, pDescriptorPlayback, (ma_AAudioStream**)&pDevice->aaudio.pStreamPlayback);
  30875. if (result != MA_SUCCESS) {
  30876. return result;
  30877. }
  30878. }
  30879. return MA_SUCCESS;
  30880. }
  30881. static ma_result ma_device_start_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  30882. {
  30883. ma_aaudio_result_t resultAA;
  30884. ma_aaudio_stream_state_t currentState;
  30885. MA_ASSERT(pDevice != NULL);
  30886. resultAA = ((MA_PFN_AAudioStream_requestStart)pDevice->pContext->aaudio.AAudioStream_requestStart)(pStream);
  30887. if (resultAA != MA_AAUDIO_OK) {
  30888. return ma_result_from_aaudio(resultAA);
  30889. }
  30890. /* Do we actually need to wait for the device to transition into it's started state? */
  30891. /* 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. */
  30892. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  30893. if (currentState != MA_AAUDIO_STREAM_STATE_STARTED) {
  30894. ma_result result;
  30895. if (currentState != MA_AAUDIO_STREAM_STATE_STARTING) {
  30896. return MA_ERROR; /* Expecting the stream to be a starting or started state. */
  30897. }
  30898. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STARTED);
  30899. if (result != MA_SUCCESS) {
  30900. return result;
  30901. }
  30902. }
  30903. return MA_SUCCESS;
  30904. }
  30905. static ma_result ma_device_stop_stream__aaudio(ma_device* pDevice, ma_AAudioStream* pStream)
  30906. {
  30907. ma_aaudio_result_t resultAA;
  30908. ma_aaudio_stream_state_t currentState;
  30909. MA_ASSERT(pDevice != NULL);
  30910. /*
  30911. From the AAudio documentation:
  30912. The stream will stop after all of the data currently buffered has been played.
  30913. This maps with miniaudio's requirement that device's be drained which means we don't need to implement any draining logic.
  30914. */
  30915. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  30916. if (currentState == MA_AAUDIO_STREAM_STATE_DISCONNECTED) {
  30917. return MA_SUCCESS; /* The device is disconnected. Don't try stopping it. */
  30918. }
  30919. resultAA = ((MA_PFN_AAudioStream_requestStop)pDevice->pContext->aaudio.AAudioStream_requestStop)(pStream);
  30920. if (resultAA != MA_AAUDIO_OK) {
  30921. return ma_result_from_aaudio(resultAA);
  30922. }
  30923. /* 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. */
  30924. currentState = ((MA_PFN_AAudioStream_getState)pDevice->pContext->aaudio.AAudioStream_getState)(pStream);
  30925. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPED) {
  30926. ma_result result;
  30927. if (currentState != MA_AAUDIO_STREAM_STATE_STOPPING) {
  30928. return MA_ERROR; /* Expecting the stream to be a stopping or stopped state. */
  30929. }
  30930. result = ma_wait_for_simple_state_transition__aaudio(pDevice->pContext, pStream, currentState, MA_AAUDIO_STREAM_STATE_STOPPED);
  30931. if (result != MA_SUCCESS) {
  30932. return result;
  30933. }
  30934. }
  30935. return MA_SUCCESS;
  30936. }
  30937. static ma_result ma_device_start__aaudio(ma_device* pDevice)
  30938. {
  30939. MA_ASSERT(pDevice != NULL);
  30940. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30941. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  30942. if (result != MA_SUCCESS) {
  30943. return result;
  30944. }
  30945. }
  30946. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30947. ma_result result = ma_device_start_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  30948. if (result != MA_SUCCESS) {
  30949. if (pDevice->type == ma_device_type_duplex) {
  30950. ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  30951. }
  30952. return result;
  30953. }
  30954. }
  30955. return MA_SUCCESS;
  30956. }
  30957. static ma_result ma_device_stop__aaudio(ma_device* pDevice)
  30958. {
  30959. MA_ASSERT(pDevice != NULL);
  30960. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  30961. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  30962. if (result != MA_SUCCESS) {
  30963. return result;
  30964. }
  30965. }
  30966. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  30967. ma_result result = ma_device_stop_stream__aaudio(pDevice, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  30968. if (result != MA_SUCCESS) {
  30969. return result;
  30970. }
  30971. }
  30972. ma_device__on_notification_stopped(pDevice);
  30973. return MA_SUCCESS;
  30974. }
  30975. static ma_result ma_device_reinit__aaudio(ma_device* pDevice, ma_device_type deviceType)
  30976. {
  30977. ma_result result;
  30978. MA_ASSERT(pDevice != NULL);
  30979. /* The first thing to do is close the streams. */
  30980. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex) {
  30981. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamCapture);
  30982. pDevice->aaudio.pStreamCapture = NULL;
  30983. }
  30984. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  30985. ma_close_stream__aaudio(pDevice->pContext, (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback);
  30986. pDevice->aaudio.pStreamPlayback = NULL;
  30987. }
  30988. /* Now we need to reinitialize each streams. The hardest part with this is just filling output the config and descriptors. */
  30989. {
  30990. ma_device_config deviceConfig;
  30991. ma_device_descriptor descriptorPlayback;
  30992. ma_device_descriptor descriptorCapture;
  30993. deviceConfig = ma_device_config_init(deviceType);
  30994. deviceConfig.playback.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  30995. deviceConfig.playback.shareMode = pDevice->playback.shareMode;
  30996. deviceConfig.playback.format = pDevice->playback.format;
  30997. deviceConfig.playback.channels = pDevice->playback.channels;
  30998. deviceConfig.capture.pDeviceID = NULL; /* Only doing rerouting with default devices. */
  30999. deviceConfig.capture.shareMode = pDevice->capture.shareMode;
  31000. deviceConfig.capture.format = pDevice->capture.format;
  31001. deviceConfig.capture.channels = pDevice->capture.channels;
  31002. deviceConfig.sampleRate = pDevice->sampleRate;
  31003. deviceConfig.aaudio.usage = pDevice->aaudio.usage;
  31004. deviceConfig.aaudio.contentType = pDevice->aaudio.contentType;
  31005. deviceConfig.aaudio.inputPreset = pDevice->aaudio.inputPreset;
  31006. deviceConfig.aaudio.noAutoStartAfterReroute = pDevice->aaudio.noAutoStartAfterReroute;
  31007. deviceConfig.periods = 1;
  31008. /* Try to get an accurate period size. */
  31009. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31010. deviceConfig.periodSizeInFrames = pDevice->playback.internalPeriodSizeInFrames;
  31011. } else {
  31012. deviceConfig.periodSizeInFrames = pDevice->capture.internalPeriodSizeInFrames;
  31013. }
  31014. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  31015. descriptorCapture.pDeviceID = deviceConfig.capture.pDeviceID;
  31016. descriptorCapture.shareMode = deviceConfig.capture.shareMode;
  31017. descriptorCapture.format = deviceConfig.capture.format;
  31018. descriptorCapture.channels = deviceConfig.capture.channels;
  31019. descriptorCapture.sampleRate = deviceConfig.sampleRate;
  31020. descriptorCapture.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  31021. descriptorCapture.periodCount = deviceConfig.periods;
  31022. }
  31023. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  31024. descriptorPlayback.pDeviceID = deviceConfig.playback.pDeviceID;
  31025. descriptorPlayback.shareMode = deviceConfig.playback.shareMode;
  31026. descriptorPlayback.format = deviceConfig.playback.format;
  31027. descriptorPlayback.channels = deviceConfig.playback.channels;
  31028. descriptorPlayback.sampleRate = deviceConfig.sampleRate;
  31029. descriptorPlayback.periodSizeInFrames = deviceConfig.periodSizeInFrames;
  31030. descriptorPlayback.periodCount = deviceConfig.periods;
  31031. }
  31032. result = ma_device_init__aaudio(pDevice, &deviceConfig, &descriptorPlayback, &descriptorCapture);
  31033. if (result != MA_SUCCESS) {
  31034. return result;
  31035. }
  31036. result = ma_device_post_init(pDevice, deviceType, &descriptorPlayback, &descriptorCapture);
  31037. if (result != MA_SUCCESS) {
  31038. ma_device_uninit__aaudio(pDevice);
  31039. return result;
  31040. }
  31041. /* We'll only ever do this in response to a reroute. */
  31042. ma_device__on_notification_rerouted(pDevice);
  31043. /* If the device is started, start the streams. Maybe make this configurable? */
  31044. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  31045. if (pDevice->aaudio.noAutoStartAfterReroute == MA_FALSE) {
  31046. ma_device_start__aaudio(pDevice);
  31047. } else {
  31048. ma_device_stop(pDevice); /* Do a full device stop so we set internal state correctly. */
  31049. }
  31050. }
  31051. return MA_SUCCESS;
  31052. }
  31053. }
  31054. static ma_result ma_device_get_info__aaudio(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  31055. {
  31056. ma_AAudioStream* pStream = NULL;
  31057. MA_ASSERT(pDevice != NULL);
  31058. MA_ASSERT(type != ma_device_type_duplex);
  31059. MA_ASSERT(pDeviceInfo != NULL);
  31060. if (type == ma_device_type_playback) {
  31061. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamCapture;
  31062. pDeviceInfo->id.aaudio = pDevice->capture.id.aaudio;
  31063. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  31064. }
  31065. if (type == ma_device_type_capture) {
  31066. pStream = (ma_AAudioStream*)pDevice->aaudio.pStreamPlayback;
  31067. pDeviceInfo->id.aaudio = pDevice->playback.id.aaudio;
  31068. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1); /* Only supporting default devices. */
  31069. }
  31070. /* Safety. Should never happen. */
  31071. if (pStream == NULL) {
  31072. return MA_INVALID_OPERATION;
  31073. }
  31074. pDeviceInfo->nativeDataFormatCount = 0;
  31075. ma_context_add_native_data_format_from_AAudioStream__aaudio(pDevice->pContext, pStream, 0, pDeviceInfo);
  31076. return MA_SUCCESS;
  31077. }
  31078. static ma_result ma_context_uninit__aaudio(ma_context* pContext)
  31079. {
  31080. MA_ASSERT(pContext != NULL);
  31081. MA_ASSERT(pContext->backend == ma_backend_aaudio);
  31082. ma_device_job_thread_uninit(&pContext->aaudio.jobThread, &pContext->allocationCallbacks);
  31083. ma_dlclose(pContext, pContext->aaudio.hAAudio);
  31084. pContext->aaudio.hAAudio = NULL;
  31085. return MA_SUCCESS;
  31086. }
  31087. static ma_result ma_context_init__aaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  31088. {
  31089. size_t i;
  31090. const char* libNames[] = {
  31091. "libaaudio.so"
  31092. };
  31093. for (i = 0; i < ma_countof(libNames); ++i) {
  31094. pContext->aaudio.hAAudio = ma_dlopen(pContext, libNames[i]);
  31095. if (pContext->aaudio.hAAudio != NULL) {
  31096. break;
  31097. }
  31098. }
  31099. if (pContext->aaudio.hAAudio == NULL) {
  31100. return MA_FAILED_TO_INIT_BACKEND;
  31101. }
  31102. pContext->aaudio.AAudio_createStreamBuilder = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudio_createStreamBuilder");
  31103. pContext->aaudio.AAudioStreamBuilder_delete = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_delete");
  31104. pContext->aaudio.AAudioStreamBuilder_setDeviceId = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDeviceId");
  31105. pContext->aaudio.AAudioStreamBuilder_setDirection = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDirection");
  31106. pContext->aaudio.AAudioStreamBuilder_setSharingMode = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSharingMode");
  31107. pContext->aaudio.AAudioStreamBuilder_setFormat = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFormat");
  31108. pContext->aaudio.AAudioStreamBuilder_setChannelCount = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setChannelCount");
  31109. pContext->aaudio.AAudioStreamBuilder_setSampleRate = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setSampleRate");
  31110. pContext->aaudio.AAudioStreamBuilder_setBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setBufferCapacityInFrames");
  31111. pContext->aaudio.AAudioStreamBuilder_setFramesPerDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setFramesPerDataCallback");
  31112. pContext->aaudio.AAudioStreamBuilder_setDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setDataCallback");
  31113. pContext->aaudio.AAudioStreamBuilder_setErrorCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setErrorCallback");
  31114. pContext->aaudio.AAudioStreamBuilder_setPerformanceMode = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setPerformanceMode");
  31115. pContext->aaudio.AAudioStreamBuilder_setUsage = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setUsage");
  31116. pContext->aaudio.AAudioStreamBuilder_setContentType = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setContentType");
  31117. pContext->aaudio.AAudioStreamBuilder_setInputPreset = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_setInputPreset");
  31118. pContext->aaudio.AAudioStreamBuilder_openStream = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStreamBuilder_openStream");
  31119. pContext->aaudio.AAudioStream_close = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_close");
  31120. pContext->aaudio.AAudioStream_getState = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getState");
  31121. pContext->aaudio.AAudioStream_waitForStateChange = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_waitForStateChange");
  31122. pContext->aaudio.AAudioStream_getFormat = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFormat");
  31123. pContext->aaudio.AAudioStream_getChannelCount = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getChannelCount");
  31124. pContext->aaudio.AAudioStream_getSampleRate = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getSampleRate");
  31125. pContext->aaudio.AAudioStream_getBufferCapacityInFrames = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getBufferCapacityInFrames");
  31126. pContext->aaudio.AAudioStream_getFramesPerDataCallback = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFramesPerDataCallback");
  31127. pContext->aaudio.AAudioStream_getFramesPerBurst = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_getFramesPerBurst");
  31128. pContext->aaudio.AAudioStream_requestStart = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_requestStart");
  31129. pContext->aaudio.AAudioStream_requestStop = (ma_proc)ma_dlsym(pContext, pContext->aaudio.hAAudio, "AAudioStream_requestStop");
  31130. pCallbacks->onContextInit = ma_context_init__aaudio;
  31131. pCallbacks->onContextUninit = ma_context_uninit__aaudio;
  31132. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__aaudio;
  31133. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__aaudio;
  31134. pCallbacks->onDeviceInit = ma_device_init__aaudio;
  31135. pCallbacks->onDeviceUninit = ma_device_uninit__aaudio;
  31136. pCallbacks->onDeviceStart = ma_device_start__aaudio;
  31137. pCallbacks->onDeviceStop = ma_device_stop__aaudio;
  31138. pCallbacks->onDeviceRead = NULL; /* Not used because AAudio is asynchronous. */
  31139. pCallbacks->onDeviceWrite = NULL; /* Not used because AAudio is asynchronous. */
  31140. pCallbacks->onDeviceDataLoop = NULL; /* Not used because AAudio is asynchronous. */
  31141. pCallbacks->onDeviceGetInfo = ma_device_get_info__aaudio;
  31142. /* We need a job thread so we can deal with rerouting. */
  31143. {
  31144. ma_result result;
  31145. ma_device_job_thread_config jobThreadConfig;
  31146. jobThreadConfig = ma_device_job_thread_config_init();
  31147. result = ma_device_job_thread_init(&jobThreadConfig, &pContext->allocationCallbacks, &pContext->aaudio.jobThread);
  31148. if (result != MA_SUCCESS) {
  31149. ma_dlclose(pContext, pContext->aaudio.hAAudio);
  31150. pContext->aaudio.hAAudio = NULL;
  31151. return result;
  31152. }
  31153. }
  31154. (void)pConfig;
  31155. return MA_SUCCESS;
  31156. }
  31157. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  31158. {
  31159. ma_device* pDevice;
  31160. MA_ASSERT(pJob != NULL);
  31161. pDevice = (ma_device*)pJob->data.device.aaudio.reroute.pDevice;
  31162. MA_ASSERT(pDevice != NULL);
  31163. /* Here is where we need to reroute the device. To do this we need to uninitialize the stream and reinitialize it. */
  31164. return ma_device_reinit__aaudio(pDevice, (ma_device_type)pJob->data.device.aaudio.reroute.deviceType);
  31165. }
  31166. #else
  31167. /* Getting here means there is no AAudio backend so we need a no-op job implementation. */
  31168. static ma_result ma_job_process__device__aaudio_reroute(ma_job* pJob)
  31169. {
  31170. return ma_job_process__noop(pJob);
  31171. }
  31172. #endif /* AAudio */
  31173. /******************************************************************************
  31174. OpenSL|ES Backend
  31175. ******************************************************************************/
  31176. #ifdef MA_HAS_OPENSL
  31177. #include <SLES/OpenSLES.h>
  31178. #ifdef MA_ANDROID
  31179. #include <SLES/OpenSLES_Android.h>
  31180. #endif
  31181. typedef SLresult (SLAPIENTRY * ma_slCreateEngine_proc)(SLObjectItf* pEngine, SLuint32 numOptions, SLEngineOption* pEngineOptions, SLuint32 numInterfaces, SLInterfaceID* pInterfaceIds, SLboolean* pInterfaceRequired);
  31182. /* OpenSL|ES has one-per-application objects :( */
  31183. static SLObjectItf g_maEngineObjectSL = NULL;
  31184. static SLEngineItf g_maEngineSL = NULL;
  31185. static ma_uint32 g_maOpenSLInitCounter = 0;
  31186. static ma_spinlock g_maOpenSLSpinlock = 0; /* For init/uninit. */
  31187. #define MA_OPENSL_OBJ(p) (*((SLObjectItf)(p)))
  31188. #define MA_OPENSL_OUTPUTMIX(p) (*((SLOutputMixItf)(p)))
  31189. #define MA_OPENSL_PLAY(p) (*((SLPlayItf)(p)))
  31190. #define MA_OPENSL_RECORD(p) (*((SLRecordItf)(p)))
  31191. #ifdef MA_ANDROID
  31192. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLAndroidSimpleBufferQueueItf)(p)))
  31193. #else
  31194. #define MA_OPENSL_BUFFERQUEUE(p) (*((SLBufferQueueItf)(p)))
  31195. #endif
  31196. static ma_result ma_result_from_OpenSL(SLuint32 result)
  31197. {
  31198. switch (result)
  31199. {
  31200. case SL_RESULT_SUCCESS: return MA_SUCCESS;
  31201. case SL_RESULT_PRECONDITIONS_VIOLATED: return MA_ERROR;
  31202. case SL_RESULT_PARAMETER_INVALID: return MA_INVALID_ARGS;
  31203. case SL_RESULT_MEMORY_FAILURE: return MA_OUT_OF_MEMORY;
  31204. case SL_RESULT_RESOURCE_ERROR: return MA_INVALID_DATA;
  31205. case SL_RESULT_RESOURCE_LOST: return MA_ERROR;
  31206. case SL_RESULT_IO_ERROR: return MA_IO_ERROR;
  31207. case SL_RESULT_BUFFER_INSUFFICIENT: return MA_NO_SPACE;
  31208. case SL_RESULT_CONTENT_CORRUPTED: return MA_INVALID_DATA;
  31209. case SL_RESULT_CONTENT_UNSUPPORTED: return MA_FORMAT_NOT_SUPPORTED;
  31210. case SL_RESULT_CONTENT_NOT_FOUND: return MA_ERROR;
  31211. case SL_RESULT_PERMISSION_DENIED: return MA_ACCESS_DENIED;
  31212. case SL_RESULT_FEATURE_UNSUPPORTED: return MA_NOT_IMPLEMENTED;
  31213. case SL_RESULT_INTERNAL_ERROR: return MA_ERROR;
  31214. case SL_RESULT_UNKNOWN_ERROR: return MA_ERROR;
  31215. case SL_RESULT_OPERATION_ABORTED: return MA_ERROR;
  31216. case SL_RESULT_CONTROL_LOST: return MA_ERROR;
  31217. default: return MA_ERROR;
  31218. }
  31219. }
  31220. /* Converts an individual OpenSL-style channel identifier (SL_SPEAKER_FRONT_LEFT, etc.) to miniaudio. */
  31221. static ma_uint8 ma_channel_id_to_ma__opensl(SLuint32 id)
  31222. {
  31223. switch (id)
  31224. {
  31225. case SL_SPEAKER_FRONT_LEFT: return MA_CHANNEL_FRONT_LEFT;
  31226. case SL_SPEAKER_FRONT_RIGHT: return MA_CHANNEL_FRONT_RIGHT;
  31227. case SL_SPEAKER_FRONT_CENTER: return MA_CHANNEL_FRONT_CENTER;
  31228. case SL_SPEAKER_LOW_FREQUENCY: return MA_CHANNEL_LFE;
  31229. case SL_SPEAKER_BACK_LEFT: return MA_CHANNEL_BACK_LEFT;
  31230. case SL_SPEAKER_BACK_RIGHT: return MA_CHANNEL_BACK_RIGHT;
  31231. case SL_SPEAKER_FRONT_LEFT_OF_CENTER: return MA_CHANNEL_FRONT_LEFT_CENTER;
  31232. case SL_SPEAKER_FRONT_RIGHT_OF_CENTER: return MA_CHANNEL_FRONT_RIGHT_CENTER;
  31233. case SL_SPEAKER_BACK_CENTER: return MA_CHANNEL_BACK_CENTER;
  31234. case SL_SPEAKER_SIDE_LEFT: return MA_CHANNEL_SIDE_LEFT;
  31235. case SL_SPEAKER_SIDE_RIGHT: return MA_CHANNEL_SIDE_RIGHT;
  31236. case SL_SPEAKER_TOP_CENTER: return MA_CHANNEL_TOP_CENTER;
  31237. case SL_SPEAKER_TOP_FRONT_LEFT: return MA_CHANNEL_TOP_FRONT_LEFT;
  31238. case SL_SPEAKER_TOP_FRONT_CENTER: return MA_CHANNEL_TOP_FRONT_CENTER;
  31239. case SL_SPEAKER_TOP_FRONT_RIGHT: return MA_CHANNEL_TOP_FRONT_RIGHT;
  31240. case SL_SPEAKER_TOP_BACK_LEFT: return MA_CHANNEL_TOP_BACK_LEFT;
  31241. case SL_SPEAKER_TOP_BACK_CENTER: return MA_CHANNEL_TOP_BACK_CENTER;
  31242. case SL_SPEAKER_TOP_BACK_RIGHT: return MA_CHANNEL_TOP_BACK_RIGHT;
  31243. default: return 0;
  31244. }
  31245. }
  31246. /* Converts an individual miniaudio channel identifier (MA_CHANNEL_FRONT_LEFT, etc.) to OpenSL-style. */
  31247. static SLuint32 ma_channel_id_to_opensl(ma_uint8 id)
  31248. {
  31249. switch (id)
  31250. {
  31251. case MA_CHANNEL_MONO: return SL_SPEAKER_FRONT_CENTER;
  31252. case MA_CHANNEL_FRONT_LEFT: return SL_SPEAKER_FRONT_LEFT;
  31253. case MA_CHANNEL_FRONT_RIGHT: return SL_SPEAKER_FRONT_RIGHT;
  31254. case MA_CHANNEL_FRONT_CENTER: return SL_SPEAKER_FRONT_CENTER;
  31255. case MA_CHANNEL_LFE: return SL_SPEAKER_LOW_FREQUENCY;
  31256. case MA_CHANNEL_BACK_LEFT: return SL_SPEAKER_BACK_LEFT;
  31257. case MA_CHANNEL_BACK_RIGHT: return SL_SPEAKER_BACK_RIGHT;
  31258. case MA_CHANNEL_FRONT_LEFT_CENTER: return SL_SPEAKER_FRONT_LEFT_OF_CENTER;
  31259. case MA_CHANNEL_FRONT_RIGHT_CENTER: return SL_SPEAKER_FRONT_RIGHT_OF_CENTER;
  31260. case MA_CHANNEL_BACK_CENTER: return SL_SPEAKER_BACK_CENTER;
  31261. case MA_CHANNEL_SIDE_LEFT: return SL_SPEAKER_SIDE_LEFT;
  31262. case MA_CHANNEL_SIDE_RIGHT: return SL_SPEAKER_SIDE_RIGHT;
  31263. case MA_CHANNEL_TOP_CENTER: return SL_SPEAKER_TOP_CENTER;
  31264. case MA_CHANNEL_TOP_FRONT_LEFT: return SL_SPEAKER_TOP_FRONT_LEFT;
  31265. case MA_CHANNEL_TOP_FRONT_CENTER: return SL_SPEAKER_TOP_FRONT_CENTER;
  31266. case MA_CHANNEL_TOP_FRONT_RIGHT: return SL_SPEAKER_TOP_FRONT_RIGHT;
  31267. case MA_CHANNEL_TOP_BACK_LEFT: return SL_SPEAKER_TOP_BACK_LEFT;
  31268. case MA_CHANNEL_TOP_BACK_CENTER: return SL_SPEAKER_TOP_BACK_CENTER;
  31269. case MA_CHANNEL_TOP_BACK_RIGHT: return SL_SPEAKER_TOP_BACK_RIGHT;
  31270. default: return 0;
  31271. }
  31272. }
  31273. /* Converts a channel mapping to an OpenSL-style channel mask. */
  31274. static SLuint32 ma_channel_map_to_channel_mask__opensl(const ma_channel* pChannelMap, ma_uint32 channels)
  31275. {
  31276. SLuint32 channelMask = 0;
  31277. ma_uint32 iChannel;
  31278. for (iChannel = 0; iChannel < channels; ++iChannel) {
  31279. channelMask |= ma_channel_id_to_opensl(pChannelMap[iChannel]);
  31280. }
  31281. return channelMask;
  31282. }
  31283. /* Converts an OpenSL-style channel mask to a miniaudio channel map. */
  31284. static void ma_channel_mask_to_channel_map__opensl(SLuint32 channelMask, ma_uint32 channels, ma_channel* pChannelMap)
  31285. {
  31286. if (channels == 1 && channelMask == 0) {
  31287. pChannelMap[0] = MA_CHANNEL_MONO;
  31288. } else if (channels == 2 && channelMask == 0) {
  31289. pChannelMap[0] = MA_CHANNEL_FRONT_LEFT;
  31290. pChannelMap[1] = MA_CHANNEL_FRONT_RIGHT;
  31291. } else {
  31292. if (channels == 1 && (channelMask & SL_SPEAKER_FRONT_CENTER) != 0) {
  31293. pChannelMap[0] = MA_CHANNEL_MONO;
  31294. } else {
  31295. /* Just iterate over each bit. */
  31296. ma_uint32 iChannel = 0;
  31297. ma_uint32 iBit;
  31298. for (iBit = 0; iBit < 32 && iChannel < channels; ++iBit) {
  31299. SLuint32 bitValue = (channelMask & (1UL << iBit));
  31300. if (bitValue != 0) {
  31301. /* The bit is set. */
  31302. pChannelMap[iChannel] = ma_channel_id_to_ma__opensl(bitValue);
  31303. iChannel += 1;
  31304. }
  31305. }
  31306. }
  31307. }
  31308. }
  31309. static SLuint32 ma_round_to_standard_sample_rate__opensl(SLuint32 samplesPerSec)
  31310. {
  31311. if (samplesPerSec <= SL_SAMPLINGRATE_8) {
  31312. return SL_SAMPLINGRATE_8;
  31313. }
  31314. if (samplesPerSec <= SL_SAMPLINGRATE_11_025) {
  31315. return SL_SAMPLINGRATE_11_025;
  31316. }
  31317. if (samplesPerSec <= SL_SAMPLINGRATE_12) {
  31318. return SL_SAMPLINGRATE_12;
  31319. }
  31320. if (samplesPerSec <= SL_SAMPLINGRATE_16) {
  31321. return SL_SAMPLINGRATE_16;
  31322. }
  31323. if (samplesPerSec <= SL_SAMPLINGRATE_22_05) {
  31324. return SL_SAMPLINGRATE_22_05;
  31325. }
  31326. if (samplesPerSec <= SL_SAMPLINGRATE_24) {
  31327. return SL_SAMPLINGRATE_24;
  31328. }
  31329. if (samplesPerSec <= SL_SAMPLINGRATE_32) {
  31330. return SL_SAMPLINGRATE_32;
  31331. }
  31332. if (samplesPerSec <= SL_SAMPLINGRATE_44_1) {
  31333. return SL_SAMPLINGRATE_44_1;
  31334. }
  31335. if (samplesPerSec <= SL_SAMPLINGRATE_48) {
  31336. return SL_SAMPLINGRATE_48;
  31337. }
  31338. /* Android doesn't support more than 48000. */
  31339. #ifndef MA_ANDROID
  31340. if (samplesPerSec <= SL_SAMPLINGRATE_64) {
  31341. return SL_SAMPLINGRATE_64;
  31342. }
  31343. if (samplesPerSec <= SL_SAMPLINGRATE_88_2) {
  31344. return SL_SAMPLINGRATE_88_2;
  31345. }
  31346. if (samplesPerSec <= SL_SAMPLINGRATE_96) {
  31347. return SL_SAMPLINGRATE_96;
  31348. }
  31349. if (samplesPerSec <= SL_SAMPLINGRATE_192) {
  31350. return SL_SAMPLINGRATE_192;
  31351. }
  31352. #endif
  31353. return SL_SAMPLINGRATE_16;
  31354. }
  31355. static SLint32 ma_to_stream_type__opensl(ma_opensl_stream_type streamType)
  31356. {
  31357. switch (streamType) {
  31358. case ma_opensl_stream_type_voice: return SL_ANDROID_STREAM_VOICE;
  31359. case ma_opensl_stream_type_system: return SL_ANDROID_STREAM_SYSTEM;
  31360. case ma_opensl_stream_type_ring: return SL_ANDROID_STREAM_RING;
  31361. case ma_opensl_stream_type_media: return SL_ANDROID_STREAM_MEDIA;
  31362. case ma_opensl_stream_type_alarm: return SL_ANDROID_STREAM_ALARM;
  31363. case ma_opensl_stream_type_notification: return SL_ANDROID_STREAM_NOTIFICATION;
  31364. default: break;
  31365. }
  31366. return SL_ANDROID_STREAM_VOICE;
  31367. }
  31368. static SLint32 ma_to_recording_preset__opensl(ma_opensl_recording_preset recordingPreset)
  31369. {
  31370. switch (recordingPreset) {
  31371. case ma_opensl_recording_preset_generic: return SL_ANDROID_RECORDING_PRESET_GENERIC;
  31372. case ma_opensl_recording_preset_camcorder: return SL_ANDROID_RECORDING_PRESET_CAMCORDER;
  31373. case ma_opensl_recording_preset_voice_recognition: return SL_ANDROID_RECORDING_PRESET_VOICE_RECOGNITION;
  31374. case ma_opensl_recording_preset_voice_communication: return SL_ANDROID_RECORDING_PRESET_VOICE_COMMUNICATION;
  31375. case ma_opensl_recording_preset_voice_unprocessed: return SL_ANDROID_RECORDING_PRESET_UNPROCESSED;
  31376. default: break;
  31377. }
  31378. return SL_ANDROID_RECORDING_PRESET_NONE;
  31379. }
  31380. static ma_result ma_context_enumerate_devices__opensl(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  31381. {
  31382. ma_bool32 cbResult;
  31383. MA_ASSERT(pContext != NULL);
  31384. MA_ASSERT(callback != NULL);
  31385. 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. */
  31386. if (g_maOpenSLInitCounter == 0) {
  31387. return MA_INVALID_OPERATION;
  31388. }
  31389. /*
  31390. TODO: Test Me.
  31391. This is currently untested, so for now we are just returning default devices.
  31392. */
  31393. #if 0 && !defined(MA_ANDROID)
  31394. ma_bool32 isTerminated = MA_FALSE;
  31395. SLuint32 pDeviceIDs[128];
  31396. SLint32 deviceCount = sizeof(pDeviceIDs) / sizeof(pDeviceIDs[0]);
  31397. SLAudioIODeviceCapabilitiesItf deviceCaps;
  31398. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  31399. if (resultSL != SL_RESULT_SUCCESS) {
  31400. /* The interface may not be supported so just report a default device. */
  31401. goto return_default_device;
  31402. }
  31403. /* Playback */
  31404. if (!isTerminated) {
  31405. resultSL = (*deviceCaps)->GetAvailableAudioOutputs(deviceCaps, &deviceCount, pDeviceIDs);
  31406. if (resultSL != SL_RESULT_SUCCESS) {
  31407. return ma_result_from_OpenSL(resultSL);
  31408. }
  31409. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  31410. ma_device_info deviceInfo;
  31411. MA_ZERO_OBJECT(&deviceInfo);
  31412. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  31413. SLAudioOutputDescriptor desc;
  31414. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  31415. if (resultSL == SL_RESULT_SUCCESS) {
  31416. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.pDeviceName, (size_t)-1);
  31417. ma_bool32 cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  31418. if (cbResult == MA_FALSE) {
  31419. isTerminated = MA_TRUE;
  31420. break;
  31421. }
  31422. }
  31423. }
  31424. }
  31425. /* Capture */
  31426. if (!isTerminated) {
  31427. resultSL = (*deviceCaps)->GetAvailableAudioInputs(deviceCaps, &deviceCount, pDeviceIDs);
  31428. if (resultSL != SL_RESULT_SUCCESS) {
  31429. return ma_result_from_OpenSL(resultSL);
  31430. }
  31431. for (SLint32 iDevice = 0; iDevice < deviceCount; ++iDevice) {
  31432. ma_device_info deviceInfo;
  31433. MA_ZERO_OBJECT(&deviceInfo);
  31434. deviceInfo.id.opensl = pDeviceIDs[iDevice];
  31435. SLAudioInputDescriptor desc;
  31436. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, deviceInfo.id.opensl, &desc);
  31437. if (resultSL == SL_RESULT_SUCCESS) {
  31438. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), (const char*)desc.deviceName, (size_t)-1);
  31439. ma_bool32 cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  31440. if (cbResult == MA_FALSE) {
  31441. isTerminated = MA_TRUE;
  31442. break;
  31443. }
  31444. }
  31445. }
  31446. }
  31447. return MA_SUCCESS;
  31448. #else
  31449. goto return_default_device;
  31450. #endif
  31451. return_default_device:;
  31452. cbResult = MA_TRUE;
  31453. /* Playback. */
  31454. if (cbResult) {
  31455. ma_device_info deviceInfo;
  31456. MA_ZERO_OBJECT(&deviceInfo);
  31457. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  31458. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31459. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  31460. }
  31461. /* Capture. */
  31462. if (cbResult) {
  31463. ma_device_info deviceInfo;
  31464. MA_ZERO_OBJECT(&deviceInfo);
  31465. deviceInfo.id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  31466. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31467. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  31468. }
  31469. return MA_SUCCESS;
  31470. }
  31471. 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)
  31472. {
  31473. MA_ASSERT(pContext != NULL);
  31474. MA_ASSERT(pDeviceInfo != NULL);
  31475. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].format = format;
  31476. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].channels = channels;
  31477. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].sampleRate = sampleRate;
  31478. pDeviceInfo->nativeDataFormats[pDeviceInfo->nativeDataFormatCount].flags = 0;
  31479. pDeviceInfo->nativeDataFormatCount += 1;
  31480. }
  31481. static void ma_context_add_data_format__opensl(ma_context* pContext, ma_format format, ma_device_info* pDeviceInfo)
  31482. {
  31483. ma_uint32 minChannels = 1;
  31484. ma_uint32 maxChannels = 2;
  31485. ma_uint32 minSampleRate = (ma_uint32)ma_standard_sample_rate_8000;
  31486. ma_uint32 maxSampleRate = (ma_uint32)ma_standard_sample_rate_48000;
  31487. ma_uint32 iChannel;
  31488. ma_uint32 iSampleRate;
  31489. MA_ASSERT(pContext != NULL);
  31490. MA_ASSERT(pDeviceInfo != NULL);
  31491. /*
  31492. Each sample format can support mono and stereo, and we'll support a small subset of standard
  31493. rates (up to 48000). A better solution would be to somehow find a native sample rate.
  31494. */
  31495. for (iChannel = minChannels; iChannel < maxChannels; iChannel += 1) {
  31496. for (iSampleRate = 0; iSampleRate < ma_countof(g_maStandardSampleRatePriorities); iSampleRate += 1) {
  31497. ma_uint32 standardSampleRate = g_maStandardSampleRatePriorities[iSampleRate];
  31498. if (standardSampleRate >= minSampleRate && standardSampleRate <= maxSampleRate) {
  31499. ma_context_add_data_format_ex__opensl(pContext, format, iChannel, standardSampleRate, pDeviceInfo);
  31500. }
  31501. }
  31502. }
  31503. }
  31504. 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)
  31505. {
  31506. MA_ASSERT(pContext != NULL);
  31507. 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. */
  31508. if (g_maOpenSLInitCounter == 0) {
  31509. return MA_INVALID_OPERATION;
  31510. }
  31511. /*
  31512. TODO: Test Me.
  31513. This is currently untested, so for now we are just returning default devices.
  31514. */
  31515. #if 0 && !defined(MA_ANDROID)
  31516. SLAudioIODeviceCapabilitiesItf deviceCaps;
  31517. SLresult resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES, &deviceCaps);
  31518. if (resultSL != SL_RESULT_SUCCESS) {
  31519. /* The interface may not be supported so just report a default device. */
  31520. goto return_default_device;
  31521. }
  31522. if (deviceType == ma_device_type_playback) {
  31523. SLAudioOutputDescriptor desc;
  31524. resultSL = (*deviceCaps)->QueryAudioOutputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  31525. if (resultSL != SL_RESULT_SUCCESS) {
  31526. return ma_result_from_OpenSL(resultSL);
  31527. }
  31528. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.pDeviceName, (size_t)-1);
  31529. } else {
  31530. SLAudioInputDescriptor desc;
  31531. resultSL = (*deviceCaps)->QueryAudioInputCapabilities(deviceCaps, pDeviceID->opensl, &desc);
  31532. if (resultSL != SL_RESULT_SUCCESS) {
  31533. return ma_result_from_OpenSL(resultSL);
  31534. }
  31535. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), (const char*)desc.deviceName, (size_t)-1);
  31536. }
  31537. goto return_detailed_info;
  31538. #else
  31539. goto return_default_device;
  31540. #endif
  31541. return_default_device:
  31542. if (pDeviceID != NULL) {
  31543. if ((deviceType == ma_device_type_playback && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOOUTPUT) ||
  31544. (deviceType == ma_device_type_capture && pDeviceID->opensl != SL_DEFAULTDEVICEID_AUDIOINPUT)) {
  31545. return MA_NO_DEVICE; /* Don't know the device. */
  31546. }
  31547. }
  31548. /* ID and Name / Description */
  31549. if (deviceType == ma_device_type_playback) {
  31550. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOOUTPUT;
  31551. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  31552. } else {
  31553. pDeviceInfo->id.opensl = SL_DEFAULTDEVICEID_AUDIOINPUT;
  31554. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  31555. }
  31556. pDeviceInfo->isDefault = MA_TRUE;
  31557. goto return_detailed_info;
  31558. return_detailed_info:
  31559. /*
  31560. For now we're just outputting a set of values that are supported by the API but not necessarily supported
  31561. by the device natively. Later on we should work on this so that it more closely reflects the device's
  31562. actual native format.
  31563. */
  31564. pDeviceInfo->nativeDataFormatCount = 0;
  31565. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  31566. ma_context_add_data_format__opensl(pContext, ma_format_f32, pDeviceInfo);
  31567. #endif
  31568. ma_context_add_data_format__opensl(pContext, ma_format_s16, pDeviceInfo);
  31569. ma_context_add_data_format__opensl(pContext, ma_format_u8, pDeviceInfo);
  31570. return MA_SUCCESS;
  31571. }
  31572. #ifdef MA_ANDROID
  31573. /*void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, SLuint32 eventFlags, const void* pBuffer, SLuint32 bufferSize, SLuint32 dataUsed, void* pContext)*/
  31574. static void ma_buffer_queue_callback_capture__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  31575. {
  31576. ma_device* pDevice = (ma_device*)pUserData;
  31577. size_t periodSizeInBytes;
  31578. ma_uint8* pBuffer;
  31579. SLresult resultSL;
  31580. MA_ASSERT(pDevice != NULL);
  31581. (void)pBufferQueue;
  31582. /*
  31583. For now, don't do anything unless the buffer was fully processed. From what I can tell, it looks like
  31584. OpenSL|ES 1.1 improves on buffer queues to the point that we could much more intelligently handle this,
  31585. but unfortunately it looks like Android is only supporting OpenSL|ES 1.0.1 for now :(
  31586. */
  31587. /* Don't do anything if the device is not started. */
  31588. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  31589. return;
  31590. }
  31591. /* Don't do anything if the device is being drained. */
  31592. if (pDevice->opensl.isDrainingCapture) {
  31593. return;
  31594. }
  31595. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  31596. pBuffer = pDevice->opensl.pBufferCapture + (pDevice->opensl.currentBufferIndexCapture * periodSizeInBytes);
  31597. ma_device_handle_backend_data_callback(pDevice, NULL, pBuffer, pDevice->capture.internalPeriodSizeInFrames);
  31598. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pBuffer, periodSizeInBytes);
  31599. if (resultSL != SL_RESULT_SUCCESS) {
  31600. return;
  31601. }
  31602. pDevice->opensl.currentBufferIndexCapture = (pDevice->opensl.currentBufferIndexCapture + 1) % pDevice->capture.internalPeriods;
  31603. }
  31604. static void ma_buffer_queue_callback_playback__opensl_android(SLAndroidSimpleBufferQueueItf pBufferQueue, void* pUserData)
  31605. {
  31606. ma_device* pDevice = (ma_device*)pUserData;
  31607. size_t periodSizeInBytes;
  31608. ma_uint8* pBuffer;
  31609. SLresult resultSL;
  31610. MA_ASSERT(pDevice != NULL);
  31611. (void)pBufferQueue;
  31612. /* Don't do anything if the device is not started. */
  31613. if (ma_device_get_state(pDevice) != ma_device_state_started) {
  31614. return;
  31615. }
  31616. /* Don't do anything if the device is being drained. */
  31617. if (pDevice->opensl.isDrainingPlayback) {
  31618. return;
  31619. }
  31620. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  31621. pBuffer = pDevice->opensl.pBufferPlayback + (pDevice->opensl.currentBufferIndexPlayback * periodSizeInBytes);
  31622. ma_device_handle_backend_data_callback(pDevice, pBuffer, NULL, pDevice->playback.internalPeriodSizeInFrames);
  31623. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pBuffer, periodSizeInBytes);
  31624. if (resultSL != SL_RESULT_SUCCESS) {
  31625. return;
  31626. }
  31627. pDevice->opensl.currentBufferIndexPlayback = (pDevice->opensl.currentBufferIndexPlayback + 1) % pDevice->playback.internalPeriods;
  31628. }
  31629. #endif
  31630. static ma_result ma_device_uninit__opensl(ma_device* pDevice)
  31631. {
  31632. MA_ASSERT(pDevice != NULL);
  31633. 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. */
  31634. if (g_maOpenSLInitCounter == 0) {
  31635. return MA_INVALID_OPERATION;
  31636. }
  31637. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31638. if (pDevice->opensl.pAudioRecorderObj) {
  31639. MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioRecorderObj);
  31640. }
  31641. ma_free(pDevice->opensl.pBufferCapture, &pDevice->pContext->allocationCallbacks);
  31642. }
  31643. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  31644. if (pDevice->opensl.pAudioPlayerObj) {
  31645. MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Destroy((SLObjectItf)pDevice->opensl.pAudioPlayerObj);
  31646. }
  31647. if (pDevice->opensl.pOutputMixObj) {
  31648. MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Destroy((SLObjectItf)pDevice->opensl.pOutputMixObj);
  31649. }
  31650. ma_free(pDevice->opensl.pBufferPlayback, &pDevice->pContext->allocationCallbacks);
  31651. }
  31652. return MA_SUCCESS;
  31653. }
  31654. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  31655. typedef SLAndroidDataFormat_PCM_EX ma_SLDataFormat_PCM;
  31656. #else
  31657. typedef SLDataFormat_PCM ma_SLDataFormat_PCM;
  31658. #endif
  31659. 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)
  31660. {
  31661. /* We need to convert our format/channels/rate so that they aren't set to default. */
  31662. if (format == ma_format_unknown) {
  31663. format = MA_DEFAULT_FORMAT;
  31664. }
  31665. if (channels == 0) {
  31666. channels = MA_DEFAULT_CHANNELS;
  31667. }
  31668. if (sampleRate == 0) {
  31669. sampleRate = MA_DEFAULT_SAMPLE_RATE;
  31670. }
  31671. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  31672. if (format == ma_format_f32) {
  31673. pDataFormat->formatType = SL_ANDROID_DATAFORMAT_PCM_EX;
  31674. pDataFormat->representation = SL_ANDROID_PCM_REPRESENTATION_FLOAT;
  31675. } else {
  31676. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  31677. }
  31678. #else
  31679. pDataFormat->formatType = SL_DATAFORMAT_PCM;
  31680. #endif
  31681. pDataFormat->numChannels = channels;
  31682. ((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 */
  31683. pDataFormat->bitsPerSample = ma_get_bytes_per_sample(format) * 8;
  31684. pDataFormat->channelMask = ma_channel_map_to_channel_mask__opensl(channelMap, channels);
  31685. pDataFormat->endianness = (ma_is_little_endian()) ? SL_BYTEORDER_LITTLEENDIAN : SL_BYTEORDER_BIGENDIAN;
  31686. /*
  31687. Android has a few restrictions on the format as documented here: https://developer.android.com/ndk/guides/audio/opensl-for-android.html
  31688. - Only mono and stereo is supported.
  31689. - Only u8 and s16 formats are supported.
  31690. - Maximum sample rate of 48000.
  31691. */
  31692. #ifdef MA_ANDROID
  31693. if (pDataFormat->numChannels > 2) {
  31694. pDataFormat->numChannels = 2;
  31695. }
  31696. #if __ANDROID_API__ >= 21
  31697. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  31698. /* It's floating point. */
  31699. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  31700. if (pDataFormat->bitsPerSample > 32) {
  31701. pDataFormat->bitsPerSample = 32;
  31702. }
  31703. } else {
  31704. if (pDataFormat->bitsPerSample > 16) {
  31705. pDataFormat->bitsPerSample = 16;
  31706. }
  31707. }
  31708. #else
  31709. if (pDataFormat->bitsPerSample > 16) {
  31710. pDataFormat->bitsPerSample = 16;
  31711. }
  31712. #endif
  31713. if (((SLDataFormat_PCM*)pDataFormat)->samplesPerSec > SL_SAMPLINGRATE_48) {
  31714. ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec = SL_SAMPLINGRATE_48;
  31715. }
  31716. #endif
  31717. pDataFormat->containerSize = pDataFormat->bitsPerSample; /* Always tightly packed for now. */
  31718. return MA_SUCCESS;
  31719. }
  31720. 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)
  31721. {
  31722. ma_bool32 isFloatingPoint = MA_FALSE;
  31723. #if defined(MA_ANDROID) && __ANDROID_API__ >= 21
  31724. if (pDataFormat->formatType == SL_ANDROID_DATAFORMAT_PCM_EX) {
  31725. MA_ASSERT(pDataFormat->representation == SL_ANDROID_PCM_REPRESENTATION_FLOAT);
  31726. isFloatingPoint = MA_TRUE;
  31727. }
  31728. #endif
  31729. if (isFloatingPoint) {
  31730. if (pDataFormat->bitsPerSample == 32) {
  31731. *pFormat = ma_format_f32;
  31732. }
  31733. } else {
  31734. if (pDataFormat->bitsPerSample == 8) {
  31735. *pFormat = ma_format_u8;
  31736. } else if (pDataFormat->bitsPerSample == 16) {
  31737. *pFormat = ma_format_s16;
  31738. } else if (pDataFormat->bitsPerSample == 24) {
  31739. *pFormat = ma_format_s24;
  31740. } else if (pDataFormat->bitsPerSample == 32) {
  31741. *pFormat = ma_format_s32;
  31742. }
  31743. }
  31744. *pChannels = pDataFormat->numChannels;
  31745. *pSampleRate = ((SLDataFormat_PCM*)pDataFormat)->samplesPerSec / 1000;
  31746. ma_channel_mask_to_channel_map__opensl(pDataFormat->channelMask, ma_min(pDataFormat->numChannels, channelMapCap), pChannelMap);
  31747. return MA_SUCCESS;
  31748. }
  31749. static ma_result ma_device_init__opensl(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  31750. {
  31751. #ifdef MA_ANDROID
  31752. SLDataLocator_AndroidSimpleBufferQueue queue;
  31753. SLresult resultSL;
  31754. size_t bufferSizeInBytes;
  31755. SLInterfaceID itfIDs[2];
  31756. const SLboolean itfIDsRequired[] = {
  31757. SL_BOOLEAN_TRUE, /* SL_IID_ANDROIDSIMPLEBUFFERQUEUE */
  31758. SL_BOOLEAN_FALSE /* SL_IID_ANDROIDCONFIGURATION */
  31759. };
  31760. #endif
  31761. 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. */
  31762. if (g_maOpenSLInitCounter == 0) {
  31763. return MA_INVALID_OPERATION;
  31764. }
  31765. if (pConfig->deviceType == ma_device_type_loopback) {
  31766. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  31767. }
  31768. /*
  31769. For now, only supporting Android implementations of OpenSL|ES since that's the only one I've
  31770. been able to test with and I currently depend on Android-specific extensions (simple buffer
  31771. queues).
  31772. */
  31773. #ifdef MA_ANDROID
  31774. itfIDs[0] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  31775. itfIDs[1] = (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION;
  31776. /* No exclusive mode with OpenSL|ES. */
  31777. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  31778. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  31779. return MA_SHARE_MODE_NOT_SUPPORTED;
  31780. }
  31781. /* Now we can start initializing the device properly. */
  31782. MA_ASSERT(pDevice != NULL);
  31783. MA_ZERO_OBJECT(&pDevice->opensl);
  31784. queue.locatorType = SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE;
  31785. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  31786. ma_SLDataFormat_PCM pcm;
  31787. SLDataLocator_IODevice locatorDevice;
  31788. SLDataSource source;
  31789. SLDataSink sink;
  31790. SLAndroidConfigurationItf pRecorderConfig;
  31791. ma_SLDataFormat_PCM_init__opensl(pDescriptorCapture->format, pDescriptorCapture->channels, pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, &pcm);
  31792. locatorDevice.locatorType = SL_DATALOCATOR_IODEVICE;
  31793. locatorDevice.deviceType = SL_IODEVICE_AUDIOINPUT;
  31794. locatorDevice.deviceID = SL_DEFAULTDEVICEID_AUDIOINPUT; /* Must always use the default device with Android. */
  31795. locatorDevice.device = NULL;
  31796. source.pLocator = &locatorDevice;
  31797. source.pFormat = NULL;
  31798. queue.numBuffers = pDescriptorCapture->periodCount;
  31799. sink.pLocator = &queue;
  31800. sink.pFormat = (SLDataFormat_PCM*)&pcm;
  31801. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  31802. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  31803. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  31804. pcm.formatType = SL_DATAFORMAT_PCM;
  31805. pcm.numChannels = 1;
  31806. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16; /* The name of the sample rate variable is different between SLAndroidDataFormat_PCM_EX and SLDataFormat_PCM. */
  31807. pcm.bitsPerSample = 16;
  31808. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  31809. pcm.channelMask = 0;
  31810. resultSL = (*g_maEngineSL)->CreateAudioRecorder(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioRecorderObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  31811. }
  31812. if (resultSL != SL_RESULT_SUCCESS) {
  31813. ma_device_uninit__opensl(pDevice);
  31814. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio recorder.");
  31815. return ma_result_from_OpenSL(resultSL);
  31816. }
  31817. /* Set the recording preset before realizing the player. */
  31818. if (pConfig->opensl.recordingPreset != ma_opensl_recording_preset_default) {
  31819. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pRecorderConfig);
  31820. if (resultSL == SL_RESULT_SUCCESS) {
  31821. SLint32 recordingPreset = ma_to_recording_preset__opensl(pConfig->opensl.recordingPreset);
  31822. resultSL = (*pRecorderConfig)->SetConfiguration(pRecorderConfig, SL_ANDROID_KEY_RECORDING_PRESET, &recordingPreset, sizeof(SLint32));
  31823. if (resultSL != SL_RESULT_SUCCESS) {
  31824. /* Failed to set the configuration. Just keep going. */
  31825. }
  31826. }
  31827. }
  31828. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->Realize((SLObjectItf)pDevice->opensl.pAudioRecorderObj, SL_BOOLEAN_FALSE);
  31829. if (resultSL != SL_RESULT_SUCCESS) {
  31830. ma_device_uninit__opensl(pDevice);
  31831. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio recorder.");
  31832. return ma_result_from_OpenSL(resultSL);
  31833. }
  31834. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_RECORD, &pDevice->opensl.pAudioRecorder);
  31835. if (resultSL != SL_RESULT_SUCCESS) {
  31836. ma_device_uninit__opensl(pDevice);
  31837. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_RECORD interface.");
  31838. return ma_result_from_OpenSL(resultSL);
  31839. }
  31840. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioRecorderObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioRecorderObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueueCapture);
  31841. if (resultSL != SL_RESULT_SUCCESS) {
  31842. ma_device_uninit__opensl(pDevice);
  31843. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  31844. return ma_result_from_OpenSL(resultSL);
  31845. }
  31846. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, ma_buffer_queue_callback_capture__opensl_android, pDevice);
  31847. if (resultSL != SL_RESULT_SUCCESS) {
  31848. ma_device_uninit__opensl(pDevice);
  31849. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.");
  31850. return ma_result_from_OpenSL(resultSL);
  31851. }
  31852. /* The internal format is determined by the "pcm" object. */
  31853. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorCapture->format, &pDescriptorCapture->channels, &pDescriptorCapture->sampleRate, pDescriptorCapture->channelMap, ma_countof(pDescriptorCapture->channelMap));
  31854. /* Buffer. */
  31855. pDescriptorCapture->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorCapture, pDescriptorCapture->sampleRate, pConfig->performanceProfile);
  31856. pDevice->opensl.currentBufferIndexCapture = 0;
  31857. bufferSizeInBytes = pDescriptorCapture->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorCapture->format, pDescriptorCapture->channels) * pDescriptorCapture->periodCount;
  31858. pDevice->opensl.pBufferCapture = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  31859. if (pDevice->opensl.pBufferCapture == NULL) {
  31860. ma_device_uninit__opensl(pDevice);
  31861. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  31862. return MA_OUT_OF_MEMORY;
  31863. }
  31864. MA_ZERO_MEMORY(pDevice->opensl.pBufferCapture, bufferSizeInBytes);
  31865. }
  31866. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  31867. ma_SLDataFormat_PCM pcm;
  31868. SLDataSource source;
  31869. SLDataLocator_OutputMix outmixLocator;
  31870. SLDataSink sink;
  31871. SLAndroidConfigurationItf pPlayerConfig;
  31872. ma_SLDataFormat_PCM_init__opensl(pDescriptorPlayback->format, pDescriptorPlayback->channels, pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, &pcm);
  31873. resultSL = (*g_maEngineSL)->CreateOutputMix(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pOutputMixObj, 0, NULL, NULL);
  31874. if (resultSL != SL_RESULT_SUCCESS) {
  31875. ma_device_uninit__opensl(pDevice);
  31876. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create output mix.");
  31877. return ma_result_from_OpenSL(resultSL);
  31878. }
  31879. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->Realize((SLObjectItf)pDevice->opensl.pOutputMixObj, SL_BOOLEAN_FALSE);
  31880. if (resultSL != SL_RESULT_SUCCESS) {
  31881. ma_device_uninit__opensl(pDevice);
  31882. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize output mix object.");
  31883. return ma_result_from_OpenSL(resultSL);
  31884. }
  31885. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pOutputMixObj)->GetInterface((SLObjectItf)pDevice->opensl.pOutputMixObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_OUTPUTMIX, &pDevice->opensl.pOutputMix);
  31886. if (resultSL != SL_RESULT_SUCCESS) {
  31887. ma_device_uninit__opensl(pDevice);
  31888. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_OUTPUTMIX interface.");
  31889. return ma_result_from_OpenSL(resultSL);
  31890. }
  31891. /* Set the output device. */
  31892. if (pDescriptorPlayback->pDeviceID != NULL) {
  31893. SLuint32 deviceID_OpenSL = pDescriptorPlayback->pDeviceID->opensl;
  31894. MA_OPENSL_OUTPUTMIX(pDevice->opensl.pOutputMix)->ReRoute((SLOutputMixItf)pDevice->opensl.pOutputMix, 1, &deviceID_OpenSL);
  31895. }
  31896. queue.numBuffers = pDescriptorPlayback->periodCount;
  31897. source.pLocator = &queue;
  31898. source.pFormat = (SLDataFormat_PCM*)&pcm;
  31899. outmixLocator.locatorType = SL_DATALOCATOR_OUTPUTMIX;
  31900. outmixLocator.outputMix = (SLObjectItf)pDevice->opensl.pOutputMixObj;
  31901. sink.pLocator = &outmixLocator;
  31902. sink.pFormat = NULL;
  31903. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  31904. if (resultSL == SL_RESULT_CONTENT_UNSUPPORTED || resultSL == SL_RESULT_PARAMETER_INVALID) {
  31905. /* Unsupported format. Fall back to something safer and try again. If this fails, just abort. */
  31906. pcm.formatType = SL_DATAFORMAT_PCM;
  31907. pcm.numChannels = 2;
  31908. ((SLDataFormat_PCM*)&pcm)->samplesPerSec = SL_SAMPLINGRATE_16;
  31909. pcm.bitsPerSample = 16;
  31910. pcm.containerSize = pcm.bitsPerSample; /* Always tightly packed for now. */
  31911. pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT;
  31912. resultSL = (*g_maEngineSL)->CreateAudioPlayer(g_maEngineSL, (SLObjectItf*)&pDevice->opensl.pAudioPlayerObj, &source, &sink, ma_countof(itfIDs), itfIDs, itfIDsRequired);
  31913. }
  31914. if (resultSL != SL_RESULT_SUCCESS) {
  31915. ma_device_uninit__opensl(pDevice);
  31916. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to create audio player.");
  31917. return ma_result_from_OpenSL(resultSL);
  31918. }
  31919. /* Set the stream type before realizing the player. */
  31920. if (pConfig->opensl.streamType != ma_opensl_stream_type_default) {
  31921. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDCONFIGURATION, &pPlayerConfig);
  31922. if (resultSL == SL_RESULT_SUCCESS) {
  31923. SLint32 streamType = ma_to_stream_type__opensl(pConfig->opensl.streamType);
  31924. resultSL = (*pPlayerConfig)->SetConfiguration(pPlayerConfig, SL_ANDROID_KEY_STREAM_TYPE, &streamType, sizeof(SLint32));
  31925. if (resultSL != SL_RESULT_SUCCESS) {
  31926. /* Failed to set the configuration. Just keep going. */
  31927. }
  31928. }
  31929. }
  31930. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->Realize((SLObjectItf)pDevice->opensl.pAudioPlayerObj, SL_BOOLEAN_FALSE);
  31931. if (resultSL != SL_RESULT_SUCCESS) {
  31932. ma_device_uninit__opensl(pDevice);
  31933. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to realize audio player.");
  31934. return ma_result_from_OpenSL(resultSL);
  31935. }
  31936. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_PLAY, &pDevice->opensl.pAudioPlayer);
  31937. if (resultSL != SL_RESULT_SUCCESS) {
  31938. ma_device_uninit__opensl(pDevice);
  31939. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_PLAY interface.");
  31940. return ma_result_from_OpenSL(resultSL);
  31941. }
  31942. resultSL = MA_OPENSL_OBJ(pDevice->opensl.pAudioPlayerObj)->GetInterface((SLObjectItf)pDevice->opensl.pAudioPlayerObj, (SLInterfaceID)pDevice->pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE, &pDevice->opensl.pBufferQueuePlayback);
  31943. if (resultSL != SL_RESULT_SUCCESS) {
  31944. ma_device_uninit__opensl(pDevice);
  31945. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to retrieve SL_IID_ANDROIDSIMPLEBUFFERQUEUE interface.");
  31946. return ma_result_from_OpenSL(resultSL);
  31947. }
  31948. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->RegisterCallback((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, ma_buffer_queue_callback_playback__opensl_android, pDevice);
  31949. if (resultSL != SL_RESULT_SUCCESS) {
  31950. ma_device_uninit__opensl(pDevice);
  31951. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to register buffer queue callback.");
  31952. return ma_result_from_OpenSL(resultSL);
  31953. }
  31954. /* The internal format is determined by the "pcm" object. */
  31955. ma_deconstruct_SLDataFormat_PCM__opensl(&pcm, &pDescriptorPlayback->format, &pDescriptorPlayback->channels, &pDescriptorPlayback->sampleRate, pDescriptorPlayback->channelMap, ma_countof(pDescriptorPlayback->channelMap));
  31956. /* Buffer. */
  31957. pDescriptorPlayback->periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_descriptor(pDescriptorPlayback, pDescriptorPlayback->sampleRate, pConfig->performanceProfile);
  31958. pDevice->opensl.currentBufferIndexPlayback = 0;
  31959. bufferSizeInBytes = pDescriptorPlayback->periodSizeInFrames * ma_get_bytes_per_frame(pDescriptorPlayback->format, pDescriptorPlayback->channels) * pDescriptorPlayback->periodCount;
  31960. pDevice->opensl.pBufferPlayback = (ma_uint8*)ma_calloc(bufferSizeInBytes, &pDevice->pContext->allocationCallbacks);
  31961. if (pDevice->opensl.pBufferPlayback == NULL) {
  31962. ma_device_uninit__opensl(pDevice);
  31963. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to allocate memory for data buffer.");
  31964. return MA_OUT_OF_MEMORY;
  31965. }
  31966. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, bufferSizeInBytes);
  31967. }
  31968. return MA_SUCCESS;
  31969. #else
  31970. return MA_NO_BACKEND; /* Non-Android implementations are not supported. */
  31971. #endif
  31972. }
  31973. static ma_result ma_device_start__opensl(ma_device* pDevice)
  31974. {
  31975. SLresult resultSL;
  31976. size_t periodSizeInBytes;
  31977. ma_uint32 iPeriod;
  31978. MA_ASSERT(pDevice != NULL);
  31979. 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. */
  31980. if (g_maOpenSLInitCounter == 0) {
  31981. return MA_INVALID_OPERATION;
  31982. }
  31983. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  31984. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_RECORDING);
  31985. if (resultSL != SL_RESULT_SUCCESS) {
  31986. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal capture device.");
  31987. return ma_result_from_OpenSL(resultSL);
  31988. }
  31989. periodSizeInBytes = pDevice->capture.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->capture.internalFormat, pDevice->capture.internalChannels);
  31990. for (iPeriod = 0; iPeriod < pDevice->capture.internalPeriods; ++iPeriod) {
  31991. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture, pDevice->opensl.pBufferCapture + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  31992. if (resultSL != SL_RESULT_SUCCESS) {
  31993. MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  31994. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for capture device.");
  31995. return ma_result_from_OpenSL(resultSL);
  31996. }
  31997. }
  31998. }
  31999. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32000. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_PLAYING);
  32001. if (resultSL != SL_RESULT_SUCCESS) {
  32002. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to start internal playback device.");
  32003. return ma_result_from_OpenSL(resultSL);
  32004. }
  32005. /* In playback mode (no duplex) we need to load some initial buffers. In duplex mode we need to enqueu silent buffers. */
  32006. if (pDevice->type == ma_device_type_duplex) {
  32007. MA_ZERO_MEMORY(pDevice->opensl.pBufferPlayback, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels));
  32008. } else {
  32009. ma_device__read_frames_from_client(pDevice, pDevice->playback.internalPeriodSizeInFrames * pDevice->playback.internalPeriods, pDevice->opensl.pBufferPlayback);
  32010. }
  32011. periodSizeInBytes = pDevice->playback.internalPeriodSizeInFrames * ma_get_bytes_per_frame(pDevice->playback.internalFormat, pDevice->playback.internalChannels);
  32012. for (iPeriod = 0; iPeriod < pDevice->playback.internalPeriods; ++iPeriod) {
  32013. resultSL = MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Enqueue((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback, pDevice->opensl.pBufferPlayback + (periodSizeInBytes * iPeriod), periodSizeInBytes);
  32014. if (resultSL != SL_RESULT_SUCCESS) {
  32015. MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  32016. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to enqueue buffer for playback device.");
  32017. return ma_result_from_OpenSL(resultSL);
  32018. }
  32019. }
  32020. }
  32021. return MA_SUCCESS;
  32022. }
  32023. static ma_result ma_device_drain__opensl(ma_device* pDevice, ma_device_type deviceType)
  32024. {
  32025. SLAndroidSimpleBufferQueueItf pBufferQueue;
  32026. MA_ASSERT(deviceType == ma_device_type_capture || deviceType == ma_device_type_playback);
  32027. if (pDevice->type == ma_device_type_capture) {
  32028. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture;
  32029. pDevice->opensl.isDrainingCapture = MA_TRUE;
  32030. } else {
  32031. pBufferQueue = (SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback;
  32032. pDevice->opensl.isDrainingPlayback = MA_TRUE;
  32033. }
  32034. for (;;) {
  32035. SLAndroidSimpleBufferQueueState state;
  32036. MA_OPENSL_BUFFERQUEUE(pBufferQueue)->GetState(pBufferQueue, &state);
  32037. if (state.count == 0) {
  32038. break;
  32039. }
  32040. ma_sleep(10);
  32041. }
  32042. if (pDevice->type == ma_device_type_capture) {
  32043. pDevice->opensl.isDrainingCapture = MA_FALSE;
  32044. } else {
  32045. pDevice->opensl.isDrainingPlayback = MA_FALSE;
  32046. }
  32047. return MA_SUCCESS;
  32048. }
  32049. static ma_result ma_device_stop__opensl(ma_device* pDevice)
  32050. {
  32051. SLresult resultSL;
  32052. MA_ASSERT(pDevice != NULL);
  32053. 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. */
  32054. if (g_maOpenSLInitCounter == 0) {
  32055. return MA_INVALID_OPERATION;
  32056. }
  32057. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32058. ma_device_drain__opensl(pDevice, ma_device_type_capture);
  32059. resultSL = MA_OPENSL_RECORD(pDevice->opensl.pAudioRecorder)->SetRecordState((SLRecordItf)pDevice->opensl.pAudioRecorder, SL_RECORDSTATE_STOPPED);
  32060. if (resultSL != SL_RESULT_SUCCESS) {
  32061. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal capture device.");
  32062. return ma_result_from_OpenSL(resultSL);
  32063. }
  32064. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueueCapture)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueueCapture);
  32065. }
  32066. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32067. ma_device_drain__opensl(pDevice, ma_device_type_playback);
  32068. resultSL = MA_OPENSL_PLAY(pDevice->opensl.pAudioPlayer)->SetPlayState((SLPlayItf)pDevice->opensl.pAudioPlayer, SL_PLAYSTATE_STOPPED);
  32069. if (resultSL != SL_RESULT_SUCCESS) {
  32070. ma_log_post(ma_device_get_log(pDevice), MA_LOG_LEVEL_ERROR, "[OpenSL] Failed to stop internal playback device.");
  32071. return ma_result_from_OpenSL(resultSL);
  32072. }
  32073. MA_OPENSL_BUFFERQUEUE(pDevice->opensl.pBufferQueuePlayback)->Clear((SLAndroidSimpleBufferQueueItf)pDevice->opensl.pBufferQueuePlayback);
  32074. }
  32075. /* 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. */
  32076. ma_device__on_notification_stopped(pDevice);
  32077. return MA_SUCCESS;
  32078. }
  32079. static ma_result ma_context_uninit__opensl(ma_context* pContext)
  32080. {
  32081. MA_ASSERT(pContext != NULL);
  32082. MA_ASSERT(pContext->backend == ma_backend_opensl);
  32083. (void)pContext;
  32084. /* Uninit global data. */
  32085. ma_spinlock_lock(&g_maOpenSLSpinlock);
  32086. {
  32087. 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(). */
  32088. g_maOpenSLInitCounter -= 1;
  32089. if (g_maOpenSLInitCounter == 0) {
  32090. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  32091. }
  32092. }
  32093. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  32094. return MA_SUCCESS;
  32095. }
  32096. static ma_result ma_dlsym_SLInterfaceID__opensl(ma_context* pContext, const char* pName, ma_handle* pHandle)
  32097. {
  32098. /* 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. */
  32099. ma_handle* p = (ma_handle*)ma_dlsym(pContext, pContext->opensl.libOpenSLES, pName);
  32100. if (p == NULL) {
  32101. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol %s", pName);
  32102. return MA_NO_BACKEND;
  32103. }
  32104. *pHandle = *p;
  32105. return MA_SUCCESS;
  32106. }
  32107. static ma_result ma_context_init_engine_nolock__opensl(ma_context* pContext)
  32108. {
  32109. g_maOpenSLInitCounter += 1;
  32110. if (g_maOpenSLInitCounter == 1) {
  32111. SLresult resultSL;
  32112. resultSL = ((ma_slCreateEngine_proc)pContext->opensl.slCreateEngine)(&g_maEngineObjectSL, 0, NULL, 0, NULL, NULL);
  32113. if (resultSL != SL_RESULT_SUCCESS) {
  32114. g_maOpenSLInitCounter -= 1;
  32115. return ma_result_from_OpenSL(resultSL);
  32116. }
  32117. (*g_maEngineObjectSL)->Realize(g_maEngineObjectSL, SL_BOOLEAN_FALSE);
  32118. resultSL = (*g_maEngineObjectSL)->GetInterface(g_maEngineObjectSL, (SLInterfaceID)pContext->opensl.SL_IID_ENGINE, &g_maEngineSL);
  32119. if (resultSL != SL_RESULT_SUCCESS) {
  32120. (*g_maEngineObjectSL)->Destroy(g_maEngineObjectSL);
  32121. g_maOpenSLInitCounter -= 1;
  32122. return ma_result_from_OpenSL(resultSL);
  32123. }
  32124. }
  32125. return MA_SUCCESS;
  32126. }
  32127. static ma_result ma_context_init__opensl(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  32128. {
  32129. ma_result result;
  32130. #if !defined(MA_NO_RUNTIME_LINKING)
  32131. size_t i;
  32132. const char* libOpenSLESNames[] = {
  32133. "libOpenSLES.so"
  32134. };
  32135. #endif
  32136. MA_ASSERT(pContext != NULL);
  32137. (void)pConfig;
  32138. #if !defined(MA_NO_RUNTIME_LINKING)
  32139. /*
  32140. Dynamically link against libOpenSLES.so. I have now had multiple reports that SL_IID_ANDROIDSIMPLEBUFFERQUEUE cannot be found. One
  32141. report was happening at compile time and another at runtime. To try working around this, I'm going to link to libOpenSLES at runtime
  32142. and extract the symbols rather than reference them directly. This should, hopefully, fix these issues as the compiler won't see any
  32143. references to the symbols and will hopefully skip the checks.
  32144. */
  32145. for (i = 0; i < ma_countof(libOpenSLESNames); i += 1) {
  32146. pContext->opensl.libOpenSLES = ma_dlopen(pContext, libOpenSLESNames[i]);
  32147. if (pContext->opensl.libOpenSLES != NULL) {
  32148. break;
  32149. }
  32150. }
  32151. if (pContext->opensl.libOpenSLES == NULL) {
  32152. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Could not find libOpenSLES.so");
  32153. return MA_NO_BACKEND;
  32154. }
  32155. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ENGINE", &pContext->opensl.SL_IID_ENGINE);
  32156. if (result != MA_SUCCESS) {
  32157. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32158. return result;
  32159. }
  32160. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_AUDIOIODEVICECAPABILITIES", &pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES);
  32161. if (result != MA_SUCCESS) {
  32162. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32163. return result;
  32164. }
  32165. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDSIMPLEBUFFERQUEUE", &pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE);
  32166. if (result != MA_SUCCESS) {
  32167. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32168. return result;
  32169. }
  32170. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_RECORD", &pContext->opensl.SL_IID_RECORD);
  32171. if (result != MA_SUCCESS) {
  32172. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32173. return result;
  32174. }
  32175. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_PLAY", &pContext->opensl.SL_IID_PLAY);
  32176. if (result != MA_SUCCESS) {
  32177. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32178. return result;
  32179. }
  32180. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_OUTPUTMIX", &pContext->opensl.SL_IID_OUTPUTMIX);
  32181. if (result != MA_SUCCESS) {
  32182. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32183. return result;
  32184. }
  32185. result = ma_dlsym_SLInterfaceID__opensl(pContext, "SL_IID_ANDROIDCONFIGURATION", &pContext->opensl.SL_IID_ANDROIDCONFIGURATION);
  32186. if (result != MA_SUCCESS) {
  32187. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32188. return result;
  32189. }
  32190. pContext->opensl.slCreateEngine = (ma_proc)ma_dlsym(pContext, pContext->opensl.libOpenSLES, "slCreateEngine");
  32191. if (pContext->opensl.slCreateEngine == NULL) {
  32192. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32193. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Cannot find symbol slCreateEngine.");
  32194. return MA_NO_BACKEND;
  32195. }
  32196. #else
  32197. pContext->opensl.SL_IID_ENGINE = (ma_handle)SL_IID_ENGINE;
  32198. pContext->opensl.SL_IID_AUDIOIODEVICECAPABILITIES = (ma_handle)SL_IID_AUDIOIODEVICECAPABILITIES;
  32199. pContext->opensl.SL_IID_ANDROIDSIMPLEBUFFERQUEUE = (ma_handle)SL_IID_ANDROIDSIMPLEBUFFERQUEUE;
  32200. pContext->opensl.SL_IID_RECORD = (ma_handle)SL_IID_RECORD;
  32201. pContext->opensl.SL_IID_PLAY = (ma_handle)SL_IID_PLAY;
  32202. pContext->opensl.SL_IID_OUTPUTMIX = (ma_handle)SL_IID_OUTPUTMIX;
  32203. pContext->opensl.SL_IID_ANDROIDCONFIGURATION = (ma_handle)SL_IID_ANDROIDCONFIGURATION;
  32204. pContext->opensl.slCreateEngine = (ma_proc)slCreateEngine;
  32205. #endif
  32206. /* Initialize global data first if applicable. */
  32207. ma_spinlock_lock(&g_maOpenSLSpinlock);
  32208. {
  32209. result = ma_context_init_engine_nolock__opensl(pContext);
  32210. }
  32211. ma_spinlock_unlock(&g_maOpenSLSpinlock);
  32212. if (result != MA_SUCCESS) {
  32213. ma_dlclose(pContext, pContext->opensl.libOpenSLES);
  32214. ma_log_post(ma_context_get_log(pContext), MA_LOG_LEVEL_INFO, "[OpenSL] Failed to initialize OpenSL engine.");
  32215. return result;
  32216. }
  32217. pCallbacks->onContextInit = ma_context_init__opensl;
  32218. pCallbacks->onContextUninit = ma_context_uninit__opensl;
  32219. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__opensl;
  32220. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__opensl;
  32221. pCallbacks->onDeviceInit = ma_device_init__opensl;
  32222. pCallbacks->onDeviceUninit = ma_device_uninit__opensl;
  32223. pCallbacks->onDeviceStart = ma_device_start__opensl;
  32224. pCallbacks->onDeviceStop = ma_device_stop__opensl;
  32225. pCallbacks->onDeviceRead = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  32226. pCallbacks->onDeviceWrite = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  32227. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because OpenSL|ES is asynchronous. */
  32228. return MA_SUCCESS;
  32229. }
  32230. #endif /* OpenSL|ES */
  32231. /******************************************************************************
  32232. Web Audio Backend
  32233. ******************************************************************************/
  32234. #ifdef MA_HAS_WEBAUDIO
  32235. #include <emscripten/emscripten.h>
  32236. static ma_bool32 ma_is_capture_supported__webaudio()
  32237. {
  32238. return EM_ASM_INT({
  32239. return (navigator.mediaDevices !== undefined && navigator.mediaDevices.getUserMedia !== undefined);
  32240. }, 0) != 0; /* Must pass in a dummy argument for C99 compatibility. */
  32241. }
  32242. #ifdef __cplusplus
  32243. extern "C" {
  32244. #endif
  32245. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_capture__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  32246. {
  32247. ma_device_handle_backend_data_callback(pDevice, NULL, pFrames, (ma_uint32)frameCount);
  32248. }
  32249. void EMSCRIPTEN_KEEPALIVE ma_device_process_pcm_frames_playback__webaudio(ma_device* pDevice, int frameCount, float* pFrames)
  32250. {
  32251. ma_device_handle_backend_data_callback(pDevice, pFrames, NULL, (ma_uint32)frameCount);
  32252. }
  32253. #ifdef __cplusplus
  32254. }
  32255. #endif
  32256. static ma_result ma_context_enumerate_devices__webaudio(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  32257. {
  32258. ma_bool32 cbResult = MA_TRUE;
  32259. MA_ASSERT(pContext != NULL);
  32260. MA_ASSERT(callback != NULL);
  32261. /* Only supporting default devices for now. */
  32262. /* Playback. */
  32263. if (cbResult) {
  32264. ma_device_info deviceInfo;
  32265. MA_ZERO_OBJECT(&deviceInfo);
  32266. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32267. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  32268. cbResult = callback(pContext, ma_device_type_playback, &deviceInfo, pUserData);
  32269. }
  32270. /* Capture. */
  32271. if (cbResult) {
  32272. if (ma_is_capture_supported__webaudio()) {
  32273. ma_device_info deviceInfo;
  32274. MA_ZERO_OBJECT(&deviceInfo);
  32275. ma_strncpy_s(deviceInfo.name, sizeof(deviceInfo.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32276. deviceInfo.isDefault = MA_TRUE; /* Only supporting default devices. */
  32277. cbResult = callback(pContext, ma_device_type_capture, &deviceInfo, pUserData);
  32278. }
  32279. }
  32280. return MA_SUCCESS;
  32281. }
  32282. 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)
  32283. {
  32284. MA_ASSERT(pContext != NULL);
  32285. if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
  32286. return MA_NO_DEVICE;
  32287. }
  32288. MA_ZERO_MEMORY(pDeviceInfo->id.webaudio, sizeof(pDeviceInfo->id.webaudio));
  32289. /* Only supporting default devices for now. */
  32290. (void)pDeviceID;
  32291. if (deviceType == ma_device_type_playback) {
  32292. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32293. } else {
  32294. ma_strncpy_s(pDeviceInfo->name, sizeof(pDeviceInfo->name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32295. }
  32296. /* Only supporting default devices. */
  32297. pDeviceInfo->isDefault = MA_TRUE;
  32298. /* Web Audio can support any number of channels and sample rates. It only supports f32 formats, however. */
  32299. pDeviceInfo->nativeDataFormats[0].flags = 0;
  32300. pDeviceInfo->nativeDataFormats[0].format = ma_format_unknown;
  32301. pDeviceInfo->nativeDataFormats[0].channels = 0; /* All channels are supported. */
  32302. pDeviceInfo->nativeDataFormats[0].sampleRate = EM_ASM_INT({
  32303. try {
  32304. var temp = new (window.AudioContext || window.webkitAudioContext)();
  32305. var sampleRate = temp.sampleRate;
  32306. temp.close();
  32307. return sampleRate;
  32308. } catch(e) {
  32309. return 0;
  32310. }
  32311. }, 0); /* Must pass in a dummy argument for C99 compatibility. */
  32312. if (pDeviceInfo->nativeDataFormats[0].sampleRate == 0) {
  32313. return MA_NO_DEVICE;
  32314. }
  32315. pDeviceInfo->nativeDataFormatCount = 1;
  32316. return MA_SUCCESS;
  32317. }
  32318. static void ma_device_uninit_by_index__webaudio(ma_device* pDevice, ma_device_type deviceType, int deviceIndex)
  32319. {
  32320. MA_ASSERT(pDevice != NULL);
  32321. EM_ASM({
  32322. var device = miniaudio.get_device_by_index($0);
  32323. /* Make sure all nodes are disconnected and marked for collection. */
  32324. if (device.scriptNode !== undefined) {
  32325. 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... */
  32326. device.scriptNode.disconnect();
  32327. device.scriptNode = undefined;
  32328. }
  32329. if (device.streamNode !== undefined) {
  32330. device.streamNode.disconnect();
  32331. device.streamNode = undefined;
  32332. }
  32333. /*
  32334. Stop the device. I think there is a chance the callback could get fired after calling this, hence why we want
  32335. to clear the callback before closing.
  32336. */
  32337. device.webaudio.close();
  32338. device.webaudio = undefined;
  32339. /* Can't forget to free the intermediary buffer. This is the buffer that's shared between JavaScript and C. */
  32340. if (device.intermediaryBuffer !== undefined) {
  32341. Module._free(device.intermediaryBuffer);
  32342. device.intermediaryBuffer = undefined;
  32343. device.intermediaryBufferView = undefined;
  32344. device.intermediaryBufferSizeInBytes = undefined;
  32345. }
  32346. /* Make sure the device is untracked so the slot can be reused later. */
  32347. miniaudio.untrack_device_by_index($0);
  32348. }, deviceIndex, deviceType);
  32349. }
  32350. static ma_result ma_device_uninit__webaudio(ma_device* pDevice)
  32351. {
  32352. MA_ASSERT(pDevice != NULL);
  32353. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32354. ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
  32355. }
  32356. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32357. ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_playback, pDevice->webaudio.indexPlayback);
  32358. }
  32359. return MA_SUCCESS;
  32360. }
  32361. static ma_uint32 ma_calculate_period_size_in_frames_from_descriptor__webaudio(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  32362. {
  32363. /*
  32364. There have been reports of the default buffer size being too small on some browsers. There have been reports of the default buffer
  32365. size being too small on some browsers. If we're using default buffer size, we'll make sure the period size is a big biffer than our
  32366. standard defaults.
  32367. */
  32368. ma_uint32 periodSizeInFrames;
  32369. if (pDescriptor->periodSizeInFrames == 0) {
  32370. if (pDescriptor->periodSizeInMilliseconds == 0) {
  32371. if (performanceProfile == ma_performance_profile_low_latency) {
  32372. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(33, nativeSampleRate); /* 1 frame @ 30 FPS */
  32373. } else {
  32374. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(333, nativeSampleRate);
  32375. }
  32376. } else {
  32377. periodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  32378. }
  32379. } else {
  32380. periodSizeInFrames = pDescriptor->periodSizeInFrames;
  32381. }
  32382. /* The size of the buffer must be a power of 2 and between 256 and 16384. */
  32383. if (periodSizeInFrames < 256) {
  32384. periodSizeInFrames = 256;
  32385. } else if (periodSizeInFrames > 16384) {
  32386. periodSizeInFrames = 16384;
  32387. } else {
  32388. periodSizeInFrames = ma_next_power_of_2(periodSizeInFrames);
  32389. }
  32390. return periodSizeInFrames;
  32391. }
  32392. static ma_result ma_device_init_by_type__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptor, ma_device_type deviceType)
  32393. {
  32394. int deviceIndex;
  32395. ma_uint32 channels;
  32396. ma_uint32 sampleRate;
  32397. ma_uint32 periodSizeInFrames;
  32398. MA_ASSERT(pDevice != NULL);
  32399. MA_ASSERT(pConfig != NULL);
  32400. MA_ASSERT(deviceType != ma_device_type_duplex);
  32401. if (deviceType == ma_device_type_capture && !ma_is_capture_supported__webaudio()) {
  32402. return MA_NO_DEVICE;
  32403. }
  32404. /* We're going to calculate some stuff in C just to simplify the JS code. */
  32405. channels = (pDescriptor->channels > 0) ? pDescriptor->channels : MA_DEFAULT_CHANNELS;
  32406. sampleRate = (pDescriptor->sampleRate > 0) ? pDescriptor->sampleRate : MA_DEFAULT_SAMPLE_RATE;
  32407. periodSizeInFrames = ma_calculate_period_size_in_frames_from_descriptor__webaudio(pDescriptor, sampleRate, pConfig->performanceProfile);
  32408. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_DEBUG, "periodSizeInFrames = %d\n", (int)periodSizeInFrames);
  32409. /* We create the device on the JavaScript side and reference it using an index. We use this to make it possible to reference the device between JavaScript and C. */
  32410. deviceIndex = EM_ASM_INT({
  32411. var channels = $0;
  32412. var sampleRate = $1;
  32413. var bufferSize = $2; /* In PCM frames. */
  32414. var isCapture = $3;
  32415. var pDevice = $4;
  32416. if (typeof(window.miniaudio) === 'undefined') {
  32417. return -1; /* Context not initialized. */
  32418. }
  32419. var device = {};
  32420. /* The AudioContext must be created in a suspended state. */
  32421. device.webaudio = new (window.AudioContext || window.webkitAudioContext)({sampleRate:sampleRate});
  32422. device.webaudio.suspend();
  32423. device.state = 1; /* ma_device_state_stopped */
  32424. /*
  32425. We need an intermediary buffer which we use for JavaScript and C interop. This buffer stores interleaved f32 PCM data. Because it's passed between
  32426. JavaScript and C it needs to be allocated and freed using Module._malloc() and Module._free().
  32427. */
  32428. device.intermediaryBufferSizeInBytes = channels * bufferSize * 4;
  32429. device.intermediaryBuffer = Module._malloc(device.intermediaryBufferSizeInBytes);
  32430. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  32431. /*
  32432. Both playback and capture devices use a ScriptProcessorNode for performing per-sample operations.
  32433. ScriptProcessorNode is actually deprecated so this is likely to be temporary. The way this works for playback is very simple. You just set a callback
  32434. that's periodically fired, just like a normal audio callback function. But apparently this design is "flawed" and is now deprecated in favour of
  32435. something called AudioWorklets which _forces_ you to load a _separate_ .js file at run time... nice... Hopefully ScriptProcessorNode will continue to
  32436. work for years to come, but this may need to change to use AudioSourceBufferNode instead, which I think is what Emscripten uses for it's built-in SDL
  32437. implementation. I'll be avoiding that insane AudioWorklet API like the plague...
  32438. For capture it is a bit unintuitive. We use the ScriptProccessorNode _only_ to get the raw PCM data. It is connected to an AudioContext just like the
  32439. playback case, however we just output silence to the AudioContext instead of passing any real data. It would make more sense to me to use the
  32440. MediaRecorder API, but unfortunately you need to specify a MIME time (Opus, Vorbis, etc.) for the binary blob that's returned to the client, but I've
  32441. been unable to figure out how to get this as raw PCM. The closest I can think is to use the MIME type for WAV files and just parse it, but I don't know
  32442. how well this would work. Although ScriptProccessorNode is deprecated, in practice it seems to have pretty good browser support so I'm leaving it like
  32443. this for now. If anyone knows how I could get raw PCM data using the MediaRecorder API please let me know!
  32444. */
  32445. device.scriptNode = device.webaudio.createScriptProcessor(bufferSize, (isCapture) ? channels : 0, (isCapture) ? 0 : channels);
  32446. if (isCapture) {
  32447. device.scriptNode.onaudioprocess = function(e) {
  32448. if (device.intermediaryBuffer === undefined) {
  32449. return; /* This means the device has been uninitialized. */
  32450. }
  32451. if (device.intermediaryBufferView.length == 0) {
  32452. /* Recreate intermediaryBufferView when losing reference to the underlying buffer, probably due to emscripten resizing heap. */
  32453. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  32454. }
  32455. /* Make sure silence it output to the AudioContext destination. Not doing this will cause sound to come out of the speakers! */
  32456. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  32457. e.outputBuffer.getChannelData(iChannel).fill(0.0);
  32458. }
  32459. /* There are some situations where we may want to send silence to the client. */
  32460. var sendSilence = false;
  32461. if (device.streamNode === undefined) {
  32462. sendSilence = true;
  32463. }
  32464. /* Sanity check. This will never happen, right? */
  32465. if (e.inputBuffer.numberOfChannels != channels) {
  32466. console.log("Capture: Channel count mismatch. " + e.inputBufer.numberOfChannels + " != " + channels + ". Sending silence.");
  32467. sendSilence = true;
  32468. }
  32469. /* This looped design guards against the situation where e.inputBuffer is a different size to the original buffer size. Should never happen in practice. */
  32470. var totalFramesProcessed = 0;
  32471. while (totalFramesProcessed < e.inputBuffer.length) {
  32472. var framesRemaining = e.inputBuffer.length - totalFramesProcessed;
  32473. var framesToProcess = framesRemaining;
  32474. if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
  32475. framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
  32476. }
  32477. /* We need to do the reverse of the playback case. We need to interleave the input data and copy it into the intermediary buffer. Then we send it to the client. */
  32478. if (sendSilence) {
  32479. device.intermediaryBufferView.fill(0.0);
  32480. } else {
  32481. for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
  32482. for (var iChannel = 0; iChannel < e.inputBuffer.numberOfChannels; ++iChannel) {
  32483. device.intermediaryBufferView[iFrame*channels + iChannel] = e.inputBuffer.getChannelData(iChannel)[totalFramesProcessed + iFrame];
  32484. }
  32485. }
  32486. }
  32487. /* Send data to the client from our intermediary buffer. */
  32488. _ma_device_process_pcm_frames_capture__webaudio(pDevice, framesToProcess, device.intermediaryBuffer);
  32489. totalFramesProcessed += framesToProcess;
  32490. }
  32491. };
  32492. navigator.mediaDevices.getUserMedia({audio:true, video:false})
  32493. .then(function(stream) {
  32494. device.streamNode = device.webaudio.createMediaStreamSource(stream);
  32495. device.streamNode.connect(device.scriptNode);
  32496. device.scriptNode.connect(device.webaudio.destination);
  32497. })
  32498. .catch(function(error) {
  32499. /* I think this should output silence... */
  32500. device.scriptNode.connect(device.webaudio.destination);
  32501. });
  32502. } else {
  32503. device.scriptNode.onaudioprocess = function(e) {
  32504. if (device.intermediaryBuffer === undefined) {
  32505. return; /* This means the device has been uninitialized. */
  32506. }
  32507. if(device.intermediaryBufferView.length == 0) {
  32508. /* Recreate intermediaryBufferView when losing reference to the underlying buffer, probably due to emscripten resizing heap. */
  32509. device.intermediaryBufferView = new Float32Array(Module.HEAPF32.buffer, device.intermediaryBuffer, device.intermediaryBufferSizeInBytes);
  32510. }
  32511. var outputSilence = false;
  32512. /* Sanity check. This will never happen, right? */
  32513. if (e.outputBuffer.numberOfChannels != channels) {
  32514. console.log("Playback: Channel count mismatch. " + e.outputBufer.numberOfChannels + " != " + channels + ". Outputting silence.");
  32515. outputSilence = true;
  32516. return;
  32517. }
  32518. /* This looped design guards against the situation where e.outputBuffer is a different size to the original buffer size. Should never happen in practice. */
  32519. var totalFramesProcessed = 0;
  32520. while (totalFramesProcessed < e.outputBuffer.length) {
  32521. var framesRemaining = e.outputBuffer.length - totalFramesProcessed;
  32522. var framesToProcess = framesRemaining;
  32523. if (framesToProcess > (device.intermediaryBufferSizeInBytes/channels/4)) {
  32524. framesToProcess = (device.intermediaryBufferSizeInBytes/channels/4);
  32525. }
  32526. /* Read data from the client into our intermediary buffer. */
  32527. _ma_device_process_pcm_frames_playback__webaudio(pDevice, framesToProcess, device.intermediaryBuffer);
  32528. /* At this point we'll have data in our intermediary buffer which we now need to deinterleave and copy over to the output buffers. */
  32529. if (outputSilence) {
  32530. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  32531. e.outputBuffer.getChannelData(iChannel).fill(0.0);
  32532. }
  32533. } else {
  32534. for (var iChannel = 0; iChannel < e.outputBuffer.numberOfChannels; ++iChannel) {
  32535. var outputBuffer = e.outputBuffer.getChannelData(iChannel);
  32536. var intermediaryBuffer = device.intermediaryBufferView;
  32537. for (var iFrame = 0; iFrame < framesToProcess; ++iFrame) {
  32538. outputBuffer[totalFramesProcessed + iFrame] = intermediaryBuffer[iFrame*channels + iChannel];
  32539. }
  32540. }
  32541. }
  32542. totalFramesProcessed += framesToProcess;
  32543. }
  32544. };
  32545. device.scriptNode.connect(device.webaudio.destination);
  32546. }
  32547. return miniaudio.track_device(device);
  32548. }, channels, sampleRate, periodSizeInFrames, deviceType == ma_device_type_capture, pDevice);
  32549. if (deviceIndex < 0) {
  32550. return MA_FAILED_TO_OPEN_BACKEND_DEVICE;
  32551. }
  32552. if (deviceType == ma_device_type_capture) {
  32553. pDevice->webaudio.indexCapture = deviceIndex;
  32554. } else {
  32555. pDevice->webaudio.indexPlayback = deviceIndex;
  32556. }
  32557. pDescriptor->format = ma_format_f32;
  32558. pDescriptor->channels = channels;
  32559. ma_channel_map_init_standard(ma_standard_channel_map_webaudio, pDescriptor->channelMap, ma_countof(pDescriptor->channelMap), pDescriptor->channels);
  32560. pDescriptor->sampleRate = EM_ASM_INT({ return miniaudio.get_device_by_index($0).webaudio.sampleRate; }, deviceIndex);
  32561. pDescriptor->periodSizeInFrames = periodSizeInFrames;
  32562. pDescriptor->periodCount = 1;
  32563. return MA_SUCCESS;
  32564. }
  32565. static ma_result ma_device_init__webaudio(ma_device* pDevice, const ma_device_config* pConfig, ma_device_descriptor* pDescriptorPlayback, ma_device_descriptor* pDescriptorCapture)
  32566. {
  32567. ma_result result;
  32568. if (pConfig->deviceType == ma_device_type_loopback) {
  32569. return MA_DEVICE_TYPE_NOT_SUPPORTED;
  32570. }
  32571. /* No exclusive mode with Web Audio. */
  32572. if (((pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) && pDescriptorPlayback->shareMode == ma_share_mode_exclusive) ||
  32573. ((pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) && pDescriptorCapture->shareMode == ma_share_mode_exclusive)) {
  32574. return MA_SHARE_MODE_NOT_SUPPORTED;
  32575. }
  32576. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  32577. result = ma_device_init_by_type__webaudio(pDevice, pConfig, pDescriptorCapture, ma_device_type_capture);
  32578. if (result != MA_SUCCESS) {
  32579. return result;
  32580. }
  32581. }
  32582. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  32583. result = ma_device_init_by_type__webaudio(pDevice, pConfig, pDescriptorPlayback, ma_device_type_playback);
  32584. if (result != MA_SUCCESS) {
  32585. if (pConfig->deviceType == ma_device_type_duplex) {
  32586. ma_device_uninit_by_index__webaudio(pDevice, ma_device_type_capture, pDevice->webaudio.indexCapture);
  32587. }
  32588. return result;
  32589. }
  32590. }
  32591. return MA_SUCCESS;
  32592. }
  32593. static ma_result ma_device_start__webaudio(ma_device* pDevice)
  32594. {
  32595. MA_ASSERT(pDevice != NULL);
  32596. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32597. EM_ASM({
  32598. var device = miniaudio.get_device_by_index($0);
  32599. device.webaudio.resume();
  32600. device.state = 2; /* ma_device_state_started */
  32601. }, pDevice->webaudio.indexCapture);
  32602. }
  32603. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32604. EM_ASM({
  32605. var device = miniaudio.get_device_by_index($0);
  32606. device.webaudio.resume();
  32607. device.state = 2; /* ma_device_state_started */
  32608. }, pDevice->webaudio.indexPlayback);
  32609. }
  32610. return MA_SUCCESS;
  32611. }
  32612. static ma_result ma_device_stop__webaudio(ma_device* pDevice)
  32613. {
  32614. MA_ASSERT(pDevice != NULL);
  32615. /*
  32616. From the WebAudio API documentation for AudioContext.suspend():
  32617. Suspends the progression of AudioContext's currentTime, allows any current context processing blocks that are already processed to be played to the
  32618. destination, and then allows the system to release its claim on audio hardware.
  32619. 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
  32620. do any kind of explicit draining.
  32621. */
  32622. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex) {
  32623. EM_ASM({
  32624. var device = miniaudio.get_device_by_index($0);
  32625. device.webaudio.suspend();
  32626. device.state = 1; /* ma_device_state_stopped */
  32627. }, pDevice->webaudio.indexCapture);
  32628. }
  32629. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  32630. EM_ASM({
  32631. var device = miniaudio.get_device_by_index($0);
  32632. device.webaudio.suspend();
  32633. device.state = 1; /* ma_device_state_stopped */
  32634. }, pDevice->webaudio.indexPlayback);
  32635. }
  32636. ma_device__on_notification_stopped(pDevice);
  32637. return MA_SUCCESS;
  32638. }
  32639. static ma_result ma_context_uninit__webaudio(ma_context* pContext)
  32640. {
  32641. MA_ASSERT(pContext != NULL);
  32642. MA_ASSERT(pContext->backend == ma_backend_webaudio);
  32643. (void)pContext; /* Unused. */
  32644. /* Remove the global miniaudio object from window if there are no more references to it. */
  32645. EM_ASM({
  32646. if (typeof(window.miniaudio) !== 'undefined') {
  32647. window.miniaudio.referenceCount--;
  32648. if (window.miniaudio.referenceCount === 0) {
  32649. delete window.miniaudio;
  32650. }
  32651. }
  32652. });
  32653. return MA_SUCCESS;
  32654. }
  32655. static ma_result ma_context_init__webaudio(ma_context* pContext, const ma_context_config* pConfig, ma_backend_callbacks* pCallbacks)
  32656. {
  32657. int resultFromJS;
  32658. MA_ASSERT(pContext != NULL);
  32659. (void)pConfig; /* Unused. */
  32660. /* Here is where our global JavaScript object is initialized. */
  32661. resultFromJS = EM_ASM_INT({
  32662. if (typeof window === 'undefined' || (window.AudioContext || window.webkitAudioContext) === undefined) {
  32663. return 0; /* Web Audio not supported. */
  32664. }
  32665. if (typeof(window.miniaudio) === 'undefined') {
  32666. window.miniaudio = {
  32667. referenceCount: 0
  32668. };
  32669. miniaudio.devices = []; /* Device cache for mapping devices to indexes for JavaScript/C interop. */
  32670. miniaudio.track_device = function(device) {
  32671. /* Try inserting into a free slot first. */
  32672. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  32673. if (miniaudio.devices[iDevice] == null) {
  32674. miniaudio.devices[iDevice] = device;
  32675. return iDevice;
  32676. }
  32677. }
  32678. /* Getting here means there is no empty slots in the array so we just push to the end. */
  32679. miniaudio.devices.push(device);
  32680. return miniaudio.devices.length - 1;
  32681. };
  32682. miniaudio.untrack_device_by_index = function(deviceIndex) {
  32683. /* We just set the device's slot to null. The slot will get reused in the next call to ma_track_device. */
  32684. miniaudio.devices[deviceIndex] = null;
  32685. /* Trim the array if possible. */
  32686. while (miniaudio.devices.length > 0) {
  32687. if (miniaudio.devices[miniaudio.devices.length-1] == null) {
  32688. miniaudio.devices.pop();
  32689. } else {
  32690. break;
  32691. }
  32692. }
  32693. };
  32694. miniaudio.untrack_device = function(device) {
  32695. for (var iDevice = 0; iDevice < miniaudio.devices.length; ++iDevice) {
  32696. if (miniaudio.devices[iDevice] == device) {
  32697. return miniaudio.untrack_device_by_index(iDevice);
  32698. }
  32699. }
  32700. };
  32701. miniaudio.get_device_by_index = function(deviceIndex) {
  32702. return miniaudio.devices[deviceIndex];
  32703. };
  32704. miniaudio.unlock_event_types = (function(){
  32705. return ['touchstart', 'touchend', 'click'];
  32706. })();
  32707. miniaudio.unlock = function() {
  32708. for(var i = 0; i < miniaudio.devices.length; ++i) {
  32709. var device = miniaudio.devices[i];
  32710. if (device != null && device.webaudio != null && device.state === 2 /* ma_device_state_started */) {
  32711. device.webaudio.resume();
  32712. }
  32713. }
  32714. miniaudio.unlock_event_types.map(function(event_type) {
  32715. document.removeEventListener(event_type, miniaudio.unlock, true);
  32716. });
  32717. };
  32718. miniaudio.unlock_event_types.map(function(event_type) {
  32719. document.addEventListener(event_type, miniaudio.unlock, true);
  32720. });
  32721. }
  32722. window.miniaudio.referenceCount++;
  32723. return 1;
  32724. }, 0); /* Must pass in a dummy argument for C99 compatibility. */
  32725. if (resultFromJS != 1) {
  32726. return MA_FAILED_TO_INIT_BACKEND;
  32727. }
  32728. pCallbacks->onContextInit = ma_context_init__webaudio;
  32729. pCallbacks->onContextUninit = ma_context_uninit__webaudio;
  32730. pCallbacks->onContextEnumerateDevices = ma_context_enumerate_devices__webaudio;
  32731. pCallbacks->onContextGetDeviceInfo = ma_context_get_device_info__webaudio;
  32732. pCallbacks->onDeviceInit = ma_device_init__webaudio;
  32733. pCallbacks->onDeviceUninit = ma_device_uninit__webaudio;
  32734. pCallbacks->onDeviceStart = ma_device_start__webaudio;
  32735. pCallbacks->onDeviceStop = ma_device_stop__webaudio;
  32736. pCallbacks->onDeviceRead = NULL; /* Not needed because WebAudio is asynchronous. */
  32737. pCallbacks->onDeviceWrite = NULL; /* Not needed because WebAudio is asynchronous. */
  32738. pCallbacks->onDeviceDataLoop = NULL; /* Not needed because WebAudio is asynchronous. */
  32739. return MA_SUCCESS;
  32740. }
  32741. #endif /* Web Audio */
  32742. static ma_bool32 ma__is_channel_map_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  32743. {
  32744. /* A blank channel map should be allowed, in which case it should use an appropriate default which will depend on context. */
  32745. if (pChannelMap != NULL && pChannelMap[0] != MA_CHANNEL_NONE) {
  32746. ma_uint32 iChannel;
  32747. if (channels == 0 || channels > MA_MAX_CHANNELS) {
  32748. return MA_FALSE; /* Channel count out of range. */
  32749. }
  32750. /* A channel cannot be present in the channel map more than once. */
  32751. for (iChannel = 0; iChannel < channels; ++iChannel) {
  32752. ma_uint32 jChannel;
  32753. for (jChannel = iChannel + 1; jChannel < channels; ++jChannel) {
  32754. if (pChannelMap[iChannel] == pChannelMap[jChannel]) {
  32755. return MA_FALSE;
  32756. }
  32757. }
  32758. }
  32759. }
  32760. return MA_TRUE;
  32761. }
  32762. static ma_result ma_device__post_init_setup(ma_device* pDevice, ma_device_type deviceType)
  32763. {
  32764. ma_result result;
  32765. MA_ASSERT(pDevice != NULL);
  32766. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32767. if (pDevice->capture.format == ma_format_unknown) {
  32768. pDevice->capture.format = pDevice->capture.internalFormat;
  32769. }
  32770. if (pDevice->capture.channels == 0) {
  32771. pDevice->capture.channels = pDevice->capture.internalChannels;
  32772. }
  32773. if (pDevice->capture.channelMap[0] == MA_CHANNEL_NONE) {
  32774. MA_ASSERT(pDevice->capture.channels <= MA_MAX_CHANNELS);
  32775. if (pDevice->capture.internalChannels == pDevice->capture.channels) {
  32776. ma_channel_map_copy(pDevice->capture.channelMap, pDevice->capture.internalChannelMap, pDevice->capture.channels);
  32777. } else {
  32778. if (pDevice->capture.channelMixMode == ma_channel_mix_mode_simple) {
  32779. ma_channel_map_init_blank(pDevice->capture.channelMap, pDevice->capture.channels);
  32780. } else {
  32781. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pDevice->capture.channels);
  32782. }
  32783. }
  32784. }
  32785. }
  32786. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32787. if (pDevice->playback.format == ma_format_unknown) {
  32788. pDevice->playback.format = pDevice->playback.internalFormat;
  32789. }
  32790. if (pDevice->playback.channels == 0) {
  32791. pDevice->playback.channels = pDevice->playback.internalChannels;
  32792. }
  32793. if (pDevice->playback.channelMap[0] == MA_CHANNEL_NONE) {
  32794. MA_ASSERT(pDevice->playback.channels <= MA_MAX_CHANNELS);
  32795. if (pDevice->playback.internalChannels == pDevice->playback.channels) {
  32796. ma_channel_map_copy(pDevice->playback.channelMap, pDevice->playback.internalChannelMap, pDevice->playback.channels);
  32797. } else {
  32798. if (pDevice->playback.channelMixMode == ma_channel_mix_mode_simple) {
  32799. ma_channel_map_init_blank(pDevice->playback.channelMap, pDevice->playback.channels);
  32800. } else {
  32801. ma_channel_map_init_standard(ma_standard_channel_map_default, pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pDevice->playback.channels);
  32802. }
  32803. }
  32804. }
  32805. }
  32806. if (pDevice->sampleRate == 0) {
  32807. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32808. pDevice->sampleRate = pDevice->capture.internalSampleRate;
  32809. } else {
  32810. pDevice->sampleRate = pDevice->playback.internalSampleRate;
  32811. }
  32812. }
  32813. /* Data converters. */
  32814. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32815. /* Converting from internal device format to client format. */
  32816. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  32817. converterConfig.formatIn = pDevice->capture.internalFormat;
  32818. converterConfig.channelsIn = pDevice->capture.internalChannels;
  32819. converterConfig.sampleRateIn = pDevice->capture.internalSampleRate;
  32820. converterConfig.pChannelMapIn = pDevice->capture.internalChannelMap;
  32821. converterConfig.formatOut = pDevice->capture.format;
  32822. converterConfig.channelsOut = pDevice->capture.channels;
  32823. converterConfig.sampleRateOut = pDevice->sampleRate;
  32824. converterConfig.pChannelMapOut = pDevice->capture.channelMap;
  32825. converterConfig.channelMixMode = pDevice->capture.channelMixMode;
  32826. converterConfig.calculateLFEFromSpatialChannels = pDevice->capture.calculateLFEFromSpatialChannels;
  32827. converterConfig.allowDynamicSampleRate = MA_FALSE;
  32828. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  32829. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  32830. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  32831. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  32832. /* Make sure the old converter is uninitialized first. */
  32833. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  32834. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  32835. }
  32836. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->capture.converter);
  32837. if (result != MA_SUCCESS) {
  32838. return result;
  32839. }
  32840. }
  32841. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32842. /* Converting from client format to device format. */
  32843. ma_data_converter_config converterConfig = ma_data_converter_config_init_default();
  32844. converterConfig.formatIn = pDevice->playback.format;
  32845. converterConfig.channelsIn = pDevice->playback.channels;
  32846. converterConfig.sampleRateIn = pDevice->sampleRate;
  32847. converterConfig.pChannelMapIn = pDevice->playback.channelMap;
  32848. converterConfig.formatOut = pDevice->playback.internalFormat;
  32849. converterConfig.channelsOut = pDevice->playback.internalChannels;
  32850. converterConfig.sampleRateOut = pDevice->playback.internalSampleRate;
  32851. converterConfig.pChannelMapOut = pDevice->playback.internalChannelMap;
  32852. converterConfig.channelMixMode = pDevice->playback.channelMixMode;
  32853. converterConfig.calculateLFEFromSpatialChannels = pDevice->playback.calculateLFEFromSpatialChannels;
  32854. converterConfig.allowDynamicSampleRate = MA_FALSE;
  32855. converterConfig.resampling.algorithm = pDevice->resampling.algorithm;
  32856. converterConfig.resampling.linear.lpfOrder = pDevice->resampling.linear.lpfOrder;
  32857. converterConfig.resampling.pBackendVTable = pDevice->resampling.pBackendVTable;
  32858. converterConfig.resampling.pBackendUserData = pDevice->resampling.pBackendUserData;
  32859. /* Make sure the old converter is uninitialized first. */
  32860. if (ma_device_get_state(pDevice) != ma_device_state_uninitialized) {
  32861. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  32862. }
  32863. result = ma_data_converter_init(&converterConfig, &pDevice->pContext->allocationCallbacks, &pDevice->playback.converter);
  32864. if (result != MA_SUCCESS) {
  32865. return result;
  32866. }
  32867. }
  32868. /*
  32869. In playback mode, if the data converter does not support retrieval of the required number of
  32870. input frames given a number of output frames, we need to fall back to a heap-allocated cache.
  32871. */
  32872. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32873. ma_uint64 unused;
  32874. pDevice->playback.inputCacheConsumed = 0;
  32875. pDevice->playback.inputCacheRemaining = 0;
  32876. if (deviceType == ma_device_type_duplex || ma_data_converter_get_required_input_frame_count(&pDevice->playback.converter, 1, &unused) != MA_SUCCESS) {
  32877. /* We need a heap allocated cache. We want to size this based on the period size. */
  32878. void* pNewInputCache;
  32879. ma_uint64 newInputCacheCap;
  32880. ma_uint64 newInputCacheSizeInBytes;
  32881. newInputCacheCap = ma_calculate_frame_count_after_resampling(pDevice->playback.internalSampleRate, pDevice->sampleRate, pDevice->playback.internalPeriodSizeInFrames);
  32882. newInputCacheSizeInBytes = newInputCacheCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  32883. if (newInputCacheSizeInBytes > MA_SIZE_MAX) {
  32884. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  32885. pDevice->playback.pInputCache = NULL;
  32886. pDevice->playback.inputCacheCap = 0;
  32887. return MA_OUT_OF_MEMORY; /* Allocation too big. Should never hit this, but makes the cast below safer for 32-bit builds. */
  32888. }
  32889. pNewInputCache = ma_realloc(pDevice->playback.pInputCache, (size_t)newInputCacheSizeInBytes, &pDevice->pContext->allocationCallbacks);
  32890. if (pNewInputCache == NULL) {
  32891. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  32892. pDevice->playback.pInputCache = NULL;
  32893. pDevice->playback.inputCacheCap = 0;
  32894. return MA_OUT_OF_MEMORY;
  32895. }
  32896. pDevice->playback.pInputCache = pNewInputCache;
  32897. pDevice->playback.inputCacheCap = newInputCacheCap;
  32898. } else {
  32899. /* 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. */
  32900. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  32901. pDevice->playback.pInputCache = NULL;
  32902. pDevice->playback.inputCacheCap = 0;
  32903. }
  32904. }
  32905. return MA_SUCCESS;
  32906. }
  32907. 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)
  32908. {
  32909. ma_result result;
  32910. if (pDevice == NULL) {
  32911. return MA_INVALID_ARGS;
  32912. }
  32913. /* Capture. */
  32914. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32915. if (ma_device_descriptor_is_valid(pDescriptorCapture) == MA_FALSE) {
  32916. return MA_INVALID_ARGS;
  32917. }
  32918. pDevice->capture.internalFormat = pDescriptorCapture->format;
  32919. pDevice->capture.internalChannels = pDescriptorCapture->channels;
  32920. pDevice->capture.internalSampleRate = pDescriptorCapture->sampleRate;
  32921. MA_COPY_MEMORY(pDevice->capture.internalChannelMap, pDescriptorCapture->channelMap, sizeof(pDescriptorCapture->channelMap));
  32922. pDevice->capture.internalPeriodSizeInFrames = pDescriptorCapture->periodSizeInFrames;
  32923. pDevice->capture.internalPeriods = pDescriptorCapture->periodCount;
  32924. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  32925. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorCapture->periodSizeInMilliseconds, pDescriptorCapture->sampleRate);
  32926. }
  32927. }
  32928. /* Playback. */
  32929. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32930. if (ma_device_descriptor_is_valid(pDescriptorPlayback) == MA_FALSE) {
  32931. return MA_INVALID_ARGS;
  32932. }
  32933. pDevice->playback.internalFormat = pDescriptorPlayback->format;
  32934. pDevice->playback.internalChannels = pDescriptorPlayback->channels;
  32935. pDevice->playback.internalSampleRate = pDescriptorPlayback->sampleRate;
  32936. MA_COPY_MEMORY(pDevice->playback.internalChannelMap, pDescriptorPlayback->channelMap, sizeof(pDescriptorPlayback->channelMap));
  32937. pDevice->playback.internalPeriodSizeInFrames = pDescriptorPlayback->periodSizeInFrames;
  32938. pDevice->playback.internalPeriods = pDescriptorPlayback->periodCount;
  32939. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  32940. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptorPlayback->periodSizeInMilliseconds, pDescriptorPlayback->sampleRate);
  32941. }
  32942. }
  32943. /*
  32944. 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.
  32945. For loopback devices, we need to retrieve the name of the playback device.
  32946. */
  32947. {
  32948. ma_device_info deviceInfo;
  32949. if (deviceType == ma_device_type_capture || deviceType == ma_device_type_duplex || deviceType == ma_device_type_loopback) {
  32950. result = ma_device_get_info(pDevice, (deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  32951. if (result == MA_SUCCESS) {
  32952. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  32953. } else {
  32954. /* We failed to retrieve the device info. Fall back to a default name. */
  32955. if (pDescriptorCapture->pDeviceID == NULL) {
  32956. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  32957. } else {
  32958. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  32959. }
  32960. }
  32961. }
  32962. if (deviceType == ma_device_type_playback || deviceType == ma_device_type_duplex) {
  32963. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  32964. if (result == MA_SUCCESS) {
  32965. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  32966. } else {
  32967. /* We failed to retrieve the device info. Fall back to a default name. */
  32968. if (pDescriptorPlayback->pDeviceID == NULL) {
  32969. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  32970. } else {
  32971. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  32972. }
  32973. }
  32974. }
  32975. }
  32976. /* Update data conversion. */
  32977. return ma_device__post_init_setup(pDevice, deviceType); /* TODO: Should probably rename ma_device__post_init_setup() to something better. */
  32978. }
  32979. static ma_thread_result MA_THREADCALL ma_worker_thread(void* pData)
  32980. {
  32981. ma_device* pDevice = (ma_device*)pData;
  32982. MA_ASSERT(pDevice != NULL);
  32983. #ifdef MA_WIN32
  32984. ma_CoInitializeEx(pDevice->pContext, NULL, MA_COINIT_VALUE);
  32985. #endif
  32986. /*
  32987. When the device is being initialized it's initial state is set to ma_device_state_uninitialized. Before returning from
  32988. ma_device_init(), the state needs to be set to something valid. In miniaudio the device's default state immediately
  32989. after initialization is stopped, so therefore we need to mark the device as such. miniaudio will wait on the worker
  32990. thread to signal an event to know when the worker thread is ready for action.
  32991. */
  32992. ma_device__set_state(pDevice, ma_device_state_stopped);
  32993. ma_event_signal(&pDevice->stopEvent);
  32994. for (;;) { /* <-- This loop just keeps the thread alive. The main audio loop is inside. */
  32995. ma_result startResult;
  32996. ma_result stopResult; /* <-- This will store the result from onDeviceStop(). If it returns an error, we don't fire the stopped notification callback. */
  32997. /* We wait on an event to know when something has requested that the device be started and the main loop entered. */
  32998. ma_event_wait(&pDevice->wakeupEvent);
  32999. /* Default result code. */
  33000. pDevice->workResult = MA_SUCCESS;
  33001. /* If the reason for the wake up is that we are terminating, just break from the loop. */
  33002. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  33003. break;
  33004. }
  33005. /*
  33006. Getting to this point means the device is wanting to get started. The function that has requested that the device
  33007. be started will be waiting on an event (pDevice->startEvent) which means we need to make sure we signal the event
  33008. in both the success and error case. It's important that the state of the device is set _before_ signaling the event.
  33009. */
  33010. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_starting);
  33011. /* If the device has a start callback, start it now. */
  33012. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  33013. startResult = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  33014. } else {
  33015. startResult = MA_SUCCESS;
  33016. }
  33017. /*
  33018. If starting was not successful we'll need to loop back to the start and wait for something
  33019. to happen (pDevice->wakeupEvent).
  33020. */
  33021. if (startResult != MA_SUCCESS) {
  33022. pDevice->workResult = startResult;
  33023. ma_event_signal(&pDevice->startEvent); /* <-- Always signal the start event so ma_device_start() can return as it'll be waiting on it. */
  33024. continue;
  33025. }
  33026. /* Make sure the state is set appropriately. */
  33027. 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. */
  33028. ma_event_signal(&pDevice->startEvent);
  33029. ma_device__on_notification_started(pDevice);
  33030. if (pDevice->pContext->callbacks.onDeviceDataLoop != NULL) {
  33031. pDevice->pContext->callbacks.onDeviceDataLoop(pDevice);
  33032. } else {
  33033. /* The backend is not using a custom main loop implementation, so now fall back to the blocking read-write implementation. */
  33034. ma_device_audio_thread__default_read_write(pDevice);
  33035. }
  33036. /* Getting here means we have broken from the main loop which happens the application has requested that device be stopped. */
  33037. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  33038. stopResult = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  33039. } else {
  33040. stopResult = MA_SUCCESS; /* No stop callback with the backend. Just assume successful. */
  33041. }
  33042. /*
  33043. After the device has stopped, make sure an event is posted. Don't post a stopped event if
  33044. stopping failed. This can happen on some backends when the underlying stream has been
  33045. stopped due to the device being physically unplugged or disabled via an OS setting.
  33046. */
  33047. if (stopResult == MA_SUCCESS) {
  33048. ma_device__on_notification_stopped(pDevice);
  33049. }
  33050. /* 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. */
  33051. ma_device__set_state(pDevice, ma_device_state_stopped);
  33052. ma_event_signal(&pDevice->stopEvent);
  33053. }
  33054. #ifdef MA_WIN32
  33055. ma_CoUninitialize(pDevice->pContext);
  33056. #endif
  33057. return (ma_thread_result)0;
  33058. }
  33059. /* Helper for determining whether or not the given device is initialized. */
  33060. static ma_bool32 ma_device__is_initialized(ma_device* pDevice)
  33061. {
  33062. if (pDevice == NULL) {
  33063. return MA_FALSE;
  33064. }
  33065. return ma_device_get_state(pDevice) != ma_device_state_uninitialized;
  33066. }
  33067. #ifdef MA_WIN32
  33068. static ma_result ma_context_uninit_backend_apis__win32(ma_context* pContext)
  33069. {
  33070. /* For some reason UWP complains when CoUninitialize() is called. I'm just not going to call it on UWP. */
  33071. #ifdef MA_WIN32_DESKTOP
  33072. ma_CoUninitialize(pContext);
  33073. ma_dlclose(pContext, pContext->win32.hUser32DLL);
  33074. ma_dlclose(pContext, pContext->win32.hOle32DLL);
  33075. ma_dlclose(pContext, pContext->win32.hAdvapi32DLL);
  33076. #else
  33077. (void)pContext;
  33078. #endif
  33079. return MA_SUCCESS;
  33080. }
  33081. static ma_result ma_context_init_backend_apis__win32(ma_context* pContext)
  33082. {
  33083. #ifdef MA_WIN32_DESKTOP
  33084. /* Ole32.dll */
  33085. pContext->win32.hOle32DLL = ma_dlopen(pContext, "ole32.dll");
  33086. if (pContext->win32.hOle32DLL == NULL) {
  33087. return MA_FAILED_TO_INIT_BACKEND;
  33088. }
  33089. pContext->win32.CoInitializeEx = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoInitializeEx");
  33090. pContext->win32.CoUninitialize = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoUninitialize");
  33091. pContext->win32.CoCreateInstance = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoCreateInstance");
  33092. pContext->win32.CoTaskMemFree = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "CoTaskMemFree");
  33093. pContext->win32.PropVariantClear = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "PropVariantClear");
  33094. pContext->win32.StringFromGUID2 = (ma_proc)ma_dlsym(pContext, pContext->win32.hOle32DLL, "StringFromGUID2");
  33095. /* User32.dll */
  33096. pContext->win32.hUser32DLL = ma_dlopen(pContext, "user32.dll");
  33097. if (pContext->win32.hUser32DLL == NULL) {
  33098. return MA_FAILED_TO_INIT_BACKEND;
  33099. }
  33100. pContext->win32.GetForegroundWindow = (ma_proc)ma_dlsym(pContext, pContext->win32.hUser32DLL, "GetForegroundWindow");
  33101. pContext->win32.GetDesktopWindow = (ma_proc)ma_dlsym(pContext, pContext->win32.hUser32DLL, "GetDesktopWindow");
  33102. /* Advapi32.dll */
  33103. pContext->win32.hAdvapi32DLL = ma_dlopen(pContext, "advapi32.dll");
  33104. if (pContext->win32.hAdvapi32DLL == NULL) {
  33105. return MA_FAILED_TO_INIT_BACKEND;
  33106. }
  33107. pContext->win32.RegOpenKeyExA = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegOpenKeyExA");
  33108. pContext->win32.RegCloseKey = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegCloseKey");
  33109. pContext->win32.RegQueryValueExA = (ma_proc)ma_dlsym(pContext, pContext->win32.hAdvapi32DLL, "RegQueryValueExA");
  33110. #else
  33111. (void)pContext; /* Unused. */
  33112. #endif
  33113. ma_CoInitializeEx(pContext, NULL, MA_COINIT_VALUE);
  33114. return MA_SUCCESS;
  33115. }
  33116. #else
  33117. static ma_result ma_context_uninit_backend_apis__nix(ma_context* pContext)
  33118. {
  33119. #if defined(MA_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MA_NO_RUNTIME_LINKING)
  33120. ma_dlclose(pContext, pContext->posix.pthreadSO);
  33121. #else
  33122. (void)pContext;
  33123. #endif
  33124. return MA_SUCCESS;
  33125. }
  33126. static ma_result ma_context_init_backend_apis__nix(ma_context* pContext)
  33127. {
  33128. /* pthread */
  33129. #if defined(MA_USE_RUNTIME_LINKING_FOR_PTHREAD) && !defined(MA_NO_RUNTIME_LINKING)
  33130. const char* libpthreadFileNames[] = {
  33131. "libpthread.so",
  33132. "libpthread.so.0",
  33133. "libpthread.dylib"
  33134. };
  33135. size_t i;
  33136. for (i = 0; i < sizeof(libpthreadFileNames) / sizeof(libpthreadFileNames[0]); ++i) {
  33137. pContext->posix.pthreadSO = ma_dlopen(pContext, libpthreadFileNames[i]);
  33138. if (pContext->posix.pthreadSO != NULL) {
  33139. break;
  33140. }
  33141. }
  33142. if (pContext->posix.pthreadSO == NULL) {
  33143. return MA_FAILED_TO_INIT_BACKEND;
  33144. }
  33145. pContext->posix.pthread_create = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_create");
  33146. pContext->posix.pthread_join = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_join");
  33147. pContext->posix.pthread_mutex_init = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_mutex_init");
  33148. pContext->posix.pthread_mutex_destroy = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_mutex_destroy");
  33149. pContext->posix.pthread_mutex_lock = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_mutex_lock");
  33150. pContext->posix.pthread_mutex_unlock = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_mutex_unlock");
  33151. pContext->posix.pthread_cond_init = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_cond_init");
  33152. pContext->posix.pthread_cond_destroy = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_cond_destroy");
  33153. pContext->posix.pthread_cond_wait = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_cond_wait");
  33154. pContext->posix.pthread_cond_signal = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_cond_signal");
  33155. pContext->posix.pthread_attr_init = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_attr_init");
  33156. pContext->posix.pthread_attr_destroy = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_attr_destroy");
  33157. pContext->posix.pthread_attr_setschedpolicy = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_attr_setschedpolicy");
  33158. pContext->posix.pthread_attr_getschedparam = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_attr_getschedparam");
  33159. pContext->posix.pthread_attr_setschedparam = (ma_proc)ma_dlsym(pContext, pContext->posix.pthreadSO, "pthread_attr_setschedparam");
  33160. #else
  33161. pContext->posix.pthread_create = (ma_proc)pthread_create;
  33162. pContext->posix.pthread_join = (ma_proc)pthread_join;
  33163. pContext->posix.pthread_mutex_init = (ma_proc)pthread_mutex_init;
  33164. pContext->posix.pthread_mutex_destroy = (ma_proc)pthread_mutex_destroy;
  33165. pContext->posix.pthread_mutex_lock = (ma_proc)pthread_mutex_lock;
  33166. pContext->posix.pthread_mutex_unlock = (ma_proc)pthread_mutex_unlock;
  33167. pContext->posix.pthread_cond_init = (ma_proc)pthread_cond_init;
  33168. pContext->posix.pthread_cond_destroy = (ma_proc)pthread_cond_destroy;
  33169. pContext->posix.pthread_cond_wait = (ma_proc)pthread_cond_wait;
  33170. pContext->posix.pthread_cond_signal = (ma_proc)pthread_cond_signal;
  33171. pContext->posix.pthread_attr_init = (ma_proc)pthread_attr_init;
  33172. pContext->posix.pthread_attr_destroy = (ma_proc)pthread_attr_destroy;
  33173. #if !defined(__EMSCRIPTEN__)
  33174. pContext->posix.pthread_attr_setschedpolicy = (ma_proc)pthread_attr_setschedpolicy;
  33175. pContext->posix.pthread_attr_getschedparam = (ma_proc)pthread_attr_getschedparam;
  33176. pContext->posix.pthread_attr_setschedparam = (ma_proc)pthread_attr_setschedparam;
  33177. #endif
  33178. #endif
  33179. return MA_SUCCESS;
  33180. }
  33181. #endif
  33182. static ma_result ma_context_init_backend_apis(ma_context* pContext)
  33183. {
  33184. ma_result result;
  33185. #ifdef MA_WIN32
  33186. result = ma_context_init_backend_apis__win32(pContext);
  33187. #else
  33188. result = ma_context_init_backend_apis__nix(pContext);
  33189. #endif
  33190. return result;
  33191. }
  33192. static ma_result ma_context_uninit_backend_apis(ma_context* pContext)
  33193. {
  33194. ma_result result;
  33195. #ifdef MA_WIN32
  33196. result = ma_context_uninit_backend_apis__win32(pContext);
  33197. #else
  33198. result = ma_context_uninit_backend_apis__nix(pContext);
  33199. #endif
  33200. return result;
  33201. }
  33202. static ma_bool32 ma_context_is_backend_asynchronous(ma_context* pContext)
  33203. {
  33204. MA_ASSERT(pContext != NULL);
  33205. if (pContext->callbacks.onDeviceRead == NULL && pContext->callbacks.onDeviceWrite == NULL) {
  33206. if (pContext->callbacks.onDeviceDataLoop == NULL) {
  33207. return MA_TRUE;
  33208. } else {
  33209. return MA_FALSE;
  33210. }
  33211. } else {
  33212. return MA_FALSE;
  33213. }
  33214. }
  33215. /* The default capacity doesn't need to be too big. */
  33216. #ifndef MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY
  33217. #define MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY 32
  33218. #endif
  33219. MA_API ma_device_job_thread_config ma_device_job_thread_config_init(void)
  33220. {
  33221. ma_device_job_thread_config config;
  33222. MA_ZERO_OBJECT(&config);
  33223. config.noThread = MA_FALSE;
  33224. config.jobQueueCapacity = MA_DEFAULT_DEVICE_JOB_QUEUE_CAPACITY;
  33225. config.jobQueueFlags = 0;
  33226. return config;
  33227. }
  33228. static ma_thread_result MA_THREADCALL ma_device_job_thread_entry(void* pUserData)
  33229. {
  33230. ma_device_job_thread* pJobThread = (ma_device_job_thread*)pUserData;
  33231. MA_ASSERT(pJobThread != NULL);
  33232. for (;;) {
  33233. ma_result result;
  33234. ma_job job;
  33235. result = ma_device_job_thread_next(pJobThread, &job);
  33236. if (result != MA_SUCCESS) {
  33237. break;
  33238. }
  33239. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  33240. break;
  33241. }
  33242. ma_job_process(&job);
  33243. }
  33244. return (ma_thread_result)0;
  33245. }
  33246. 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)
  33247. {
  33248. ma_result result;
  33249. ma_job_queue_config jobQueueConfig;
  33250. if (pJobThread == NULL) {
  33251. return MA_INVALID_ARGS;
  33252. }
  33253. MA_ZERO_OBJECT(pJobThread);
  33254. if (pConfig == NULL) {
  33255. return MA_INVALID_ARGS;
  33256. }
  33257. /* Initialize the job queue before the thread to ensure it's in a valid state. */
  33258. jobQueueConfig = ma_job_queue_config_init(pConfig->jobQueueFlags, pConfig->jobQueueCapacity);
  33259. result = ma_job_queue_init(&jobQueueConfig, pAllocationCallbacks, &pJobThread->jobQueue);
  33260. if (result != MA_SUCCESS) {
  33261. return result; /* Failed to initialize job queue. */
  33262. }
  33263. /* The thread needs to be initialized after the job queue to ensure the thread doesn't try to access it prematurely. */
  33264. if (pConfig->noThread == MA_FALSE) {
  33265. result = ma_thread_create(&pJobThread->thread, ma_thread_priority_normal, 0, ma_device_job_thread_entry, pJobThread, pAllocationCallbacks);
  33266. if (result != MA_SUCCESS) {
  33267. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  33268. return result; /* Failed to create the job thread. */
  33269. }
  33270. pJobThread->_hasThread = MA_TRUE;
  33271. } else {
  33272. pJobThread->_hasThread = MA_FALSE;
  33273. }
  33274. return MA_SUCCESS;
  33275. }
  33276. MA_API void ma_device_job_thread_uninit(ma_device_job_thread* pJobThread, const ma_allocation_callbacks* pAllocationCallbacks)
  33277. {
  33278. if (pJobThread == NULL) {
  33279. return;
  33280. }
  33281. /* 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. */
  33282. {
  33283. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  33284. ma_device_job_thread_post(pJobThread, &job);
  33285. }
  33286. /* Wait for the thread to terminate naturally. */
  33287. if (pJobThread->_hasThread) {
  33288. ma_thread_wait(&pJobThread->thread);
  33289. }
  33290. /* At this point the thread should be terminated so we can safely uninitialize the job queue. */
  33291. ma_job_queue_uninit(&pJobThread->jobQueue, pAllocationCallbacks);
  33292. }
  33293. MA_API ma_result ma_device_job_thread_post(ma_device_job_thread* pJobThread, const ma_job* pJob)
  33294. {
  33295. if (pJobThread == NULL || pJob == NULL) {
  33296. return MA_INVALID_ARGS;
  33297. }
  33298. return ma_job_queue_post(&pJobThread->jobQueue, pJob);
  33299. }
  33300. MA_API ma_result ma_device_job_thread_next(ma_device_job_thread* pJobThread, ma_job* pJob)
  33301. {
  33302. if (pJob == NULL) {
  33303. return MA_INVALID_ARGS;
  33304. }
  33305. MA_ZERO_OBJECT(pJob);
  33306. if (pJobThread == NULL) {
  33307. return MA_INVALID_ARGS;
  33308. }
  33309. return ma_job_queue_next(&pJobThread->jobQueue, pJob);
  33310. }
  33311. MA_API ma_context_config ma_context_config_init(void)
  33312. {
  33313. ma_context_config config;
  33314. MA_ZERO_OBJECT(&config);
  33315. return config;
  33316. }
  33317. MA_API ma_result ma_context_init(const ma_backend backends[], ma_uint32 backendCount, const ma_context_config* pConfig, ma_context* pContext)
  33318. {
  33319. ma_result result;
  33320. ma_context_config defaultConfig;
  33321. ma_backend defaultBackends[ma_backend_null+1];
  33322. ma_uint32 iBackend;
  33323. ma_backend* pBackendsToIterate;
  33324. ma_uint32 backendsToIterateCount;
  33325. if (pContext == NULL) {
  33326. return MA_INVALID_ARGS;
  33327. }
  33328. MA_ZERO_OBJECT(pContext);
  33329. /* Always make sure the config is set first to ensure properties are available as soon as possible. */
  33330. if (pConfig == NULL) {
  33331. defaultConfig = ma_context_config_init();
  33332. pConfig = &defaultConfig;
  33333. }
  33334. /* Allocation callbacks need to come first because they'll be passed around to other areas. */
  33335. result = ma_allocation_callbacks_init_copy(&pContext->allocationCallbacks, &pConfig->allocationCallbacks);
  33336. if (result != MA_SUCCESS) {
  33337. return result;
  33338. }
  33339. /* Get a lot set up first so we can start logging ASAP. */
  33340. if (pConfig->pLog != NULL) {
  33341. pContext->pLog = pConfig->pLog;
  33342. } else {
  33343. result = ma_log_init(&pContext->allocationCallbacks, &pContext->log);
  33344. if (result == MA_SUCCESS) {
  33345. pContext->pLog = &pContext->log;
  33346. } else {
  33347. pContext->pLog = NULL; /* Logging is not available. */
  33348. }
  33349. }
  33350. pContext->threadPriority = pConfig->threadPriority;
  33351. pContext->threadStackSize = pConfig->threadStackSize;
  33352. pContext->pUserData = pConfig->pUserData;
  33353. /* Backend APIs need to be initialized first. This is where external libraries will be loaded and linked. */
  33354. result = ma_context_init_backend_apis(pContext);
  33355. if (result != MA_SUCCESS) {
  33356. return result;
  33357. }
  33358. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  33359. defaultBackends[iBackend] = (ma_backend)iBackend;
  33360. }
  33361. pBackendsToIterate = (ma_backend*)backends;
  33362. backendsToIterateCount = backendCount;
  33363. if (pBackendsToIterate == NULL) {
  33364. pBackendsToIterate = (ma_backend*)defaultBackends;
  33365. backendsToIterateCount = ma_countof(defaultBackends);
  33366. }
  33367. MA_ASSERT(pBackendsToIterate != NULL);
  33368. for (iBackend = 0; iBackend < backendsToIterateCount; iBackend += 1) {
  33369. ma_backend backend = pBackendsToIterate[iBackend];
  33370. /* Make sure all callbacks are reset so we don't accidentally drag in any from previously failed initialization attempts. */
  33371. MA_ZERO_OBJECT(&pContext->callbacks);
  33372. /* These backends are using the new callback system. */
  33373. switch (backend) {
  33374. #ifdef MA_HAS_WASAPI
  33375. case ma_backend_wasapi:
  33376. {
  33377. pContext->callbacks.onContextInit = ma_context_init__wasapi;
  33378. } break;
  33379. #endif
  33380. #ifdef MA_HAS_DSOUND
  33381. case ma_backend_dsound:
  33382. {
  33383. pContext->callbacks.onContextInit = ma_context_init__dsound;
  33384. } break;
  33385. #endif
  33386. #ifdef MA_HAS_WINMM
  33387. case ma_backend_winmm:
  33388. {
  33389. pContext->callbacks.onContextInit = ma_context_init__winmm;
  33390. } break;
  33391. #endif
  33392. #ifdef MA_HAS_COREAUDIO
  33393. case ma_backend_coreaudio:
  33394. {
  33395. pContext->callbacks.onContextInit = ma_context_init__coreaudio;
  33396. } break;
  33397. #endif
  33398. #ifdef MA_HAS_SNDIO
  33399. case ma_backend_sndio:
  33400. {
  33401. pContext->callbacks.onContextInit = ma_context_init__sndio;
  33402. } break;
  33403. #endif
  33404. #ifdef MA_HAS_AUDIO4
  33405. case ma_backend_audio4:
  33406. {
  33407. pContext->callbacks.onContextInit = ma_context_init__audio4;
  33408. } break;
  33409. #endif
  33410. #ifdef MA_HAS_OSS
  33411. case ma_backend_oss:
  33412. {
  33413. pContext->callbacks.onContextInit = ma_context_init__oss;
  33414. } break;
  33415. #endif
  33416. #ifdef MA_HAS_PULSEAUDIO
  33417. case ma_backend_pulseaudio:
  33418. {
  33419. pContext->callbacks.onContextInit = ma_context_init__pulse;
  33420. } break;
  33421. #endif
  33422. #ifdef MA_HAS_ALSA
  33423. case ma_backend_alsa:
  33424. {
  33425. pContext->callbacks.onContextInit = ma_context_init__alsa;
  33426. } break;
  33427. #endif
  33428. #ifdef MA_HAS_JACK
  33429. case ma_backend_jack:
  33430. {
  33431. pContext->callbacks.onContextInit = ma_context_init__jack;
  33432. } break;
  33433. #endif
  33434. #ifdef MA_HAS_AAUDIO
  33435. case ma_backend_aaudio:
  33436. {
  33437. if (ma_is_backend_enabled(backend)) {
  33438. pContext->callbacks.onContextInit = ma_context_init__aaudio;
  33439. }
  33440. } break;
  33441. #endif
  33442. #ifdef MA_HAS_OPENSL
  33443. case ma_backend_opensl:
  33444. {
  33445. if (ma_is_backend_enabled(backend)) {
  33446. pContext->callbacks.onContextInit = ma_context_init__opensl;
  33447. }
  33448. } break;
  33449. #endif
  33450. #ifdef MA_HAS_WEBAUDIO
  33451. case ma_backend_webaudio:
  33452. {
  33453. pContext->callbacks.onContextInit = ma_context_init__webaudio;
  33454. } break;
  33455. #endif
  33456. #ifdef MA_HAS_CUSTOM
  33457. case ma_backend_custom:
  33458. {
  33459. /* Slightly different logic for custom backends. Custom backends can optionally set all of their callbacks in the config. */
  33460. pContext->callbacks = pConfig->custom;
  33461. } break;
  33462. #endif
  33463. #ifdef MA_HAS_NULL
  33464. case ma_backend_null:
  33465. {
  33466. pContext->callbacks.onContextInit = ma_context_init__null;
  33467. } break;
  33468. #endif
  33469. default: break;
  33470. }
  33471. if (pContext->callbacks.onContextInit != NULL) {
  33472. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Attempting to initialize %s backend...\n", ma_get_backend_name(backend));
  33473. result = pContext->callbacks.onContextInit(pContext, pConfig, &pContext->callbacks);
  33474. } else {
  33475. result = MA_NO_BACKEND;
  33476. }
  33477. /* If this iteration was successful, return. */
  33478. if (result == MA_SUCCESS) {
  33479. result = ma_mutex_init(&pContext->deviceEnumLock);
  33480. if (result != MA_SUCCESS) {
  33481. 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");
  33482. }
  33483. result = ma_mutex_init(&pContext->deviceInfoLock);
  33484. if (result != MA_SUCCESS) {
  33485. 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");
  33486. }
  33487. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "System Architecture:\n");
  33488. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " Endian: %s\n", ma_is_little_endian() ? "LE" : "BE");
  33489. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " SSE2: %s\n", ma_has_sse2() ? "YES" : "NO");
  33490. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " AVX2: %s\n", ma_has_avx2() ? "YES" : "NO");
  33491. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, " NEON: %s\n", ma_has_neon() ? "YES" : "NO");
  33492. pContext->backend = backend;
  33493. return result;
  33494. } else {
  33495. ma_log_postf(ma_context_get_log(pContext), MA_LOG_LEVEL_DEBUG, "Failed to initialize %s backend.\n", ma_get_backend_name(backend));
  33496. }
  33497. }
  33498. /* If we get here it means an error occurred. */
  33499. MA_ZERO_OBJECT(pContext); /* Safety. */
  33500. return MA_NO_BACKEND;
  33501. }
  33502. MA_API ma_result ma_context_uninit(ma_context* pContext)
  33503. {
  33504. if (pContext == NULL) {
  33505. return MA_INVALID_ARGS;
  33506. }
  33507. if (pContext->callbacks.onContextUninit != NULL) {
  33508. pContext->callbacks.onContextUninit(pContext);
  33509. }
  33510. ma_mutex_uninit(&pContext->deviceEnumLock);
  33511. ma_mutex_uninit(&pContext->deviceInfoLock);
  33512. ma_free(pContext->pDeviceInfos, &pContext->allocationCallbacks);
  33513. ma_context_uninit_backend_apis(pContext);
  33514. if (pContext->pLog == &pContext->log) {
  33515. ma_log_uninit(&pContext->log);
  33516. }
  33517. return MA_SUCCESS;
  33518. }
  33519. MA_API size_t ma_context_sizeof()
  33520. {
  33521. return sizeof(ma_context);
  33522. }
  33523. MA_API ma_log* ma_context_get_log(ma_context* pContext)
  33524. {
  33525. if (pContext == NULL) {
  33526. return NULL;
  33527. }
  33528. return pContext->pLog;
  33529. }
  33530. MA_API ma_result ma_context_enumerate_devices(ma_context* pContext, ma_enum_devices_callback_proc callback, void* pUserData)
  33531. {
  33532. ma_result result;
  33533. if (pContext == NULL || callback == NULL) {
  33534. return MA_INVALID_ARGS;
  33535. }
  33536. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  33537. return MA_INVALID_OPERATION;
  33538. }
  33539. ma_mutex_lock(&pContext->deviceEnumLock);
  33540. {
  33541. result = pContext->callbacks.onContextEnumerateDevices(pContext, callback, pUserData);
  33542. }
  33543. ma_mutex_unlock(&pContext->deviceEnumLock);
  33544. return result;
  33545. }
  33546. static ma_bool32 ma_context_get_devices__enum_callback(ma_context* pContext, ma_device_type deviceType, const ma_device_info* pInfo, void* pUserData)
  33547. {
  33548. /*
  33549. 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
  33550. it's just appended to the end. If it's a playback device it's inserted just before the first capture device.
  33551. */
  33552. /*
  33553. 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
  33554. simple fixed size increment for buffer expansion.
  33555. */
  33556. const ma_uint32 bufferExpansionCount = 2;
  33557. const ma_uint32 totalDeviceInfoCount = pContext->playbackDeviceInfoCount + pContext->captureDeviceInfoCount;
  33558. if (totalDeviceInfoCount >= pContext->deviceInfoCapacity) {
  33559. ma_uint32 newCapacity = pContext->deviceInfoCapacity + bufferExpansionCount;
  33560. ma_device_info* pNewInfos = (ma_device_info*)ma_realloc(pContext->pDeviceInfos, sizeof(*pContext->pDeviceInfos)*newCapacity, &pContext->allocationCallbacks);
  33561. if (pNewInfos == NULL) {
  33562. return MA_FALSE; /* Out of memory. */
  33563. }
  33564. pContext->pDeviceInfos = pNewInfos;
  33565. pContext->deviceInfoCapacity = newCapacity;
  33566. }
  33567. if (deviceType == ma_device_type_playback) {
  33568. /* Playback. Insert just before the first capture device. */
  33569. /* The first thing to do is move all of the capture devices down a slot. */
  33570. ma_uint32 iFirstCaptureDevice = pContext->playbackDeviceInfoCount;
  33571. size_t iCaptureDevice;
  33572. for (iCaptureDevice = totalDeviceInfoCount; iCaptureDevice > iFirstCaptureDevice; --iCaptureDevice) {
  33573. pContext->pDeviceInfos[iCaptureDevice] = pContext->pDeviceInfos[iCaptureDevice-1];
  33574. }
  33575. /* Now just insert where the first capture device was before moving it down a slot. */
  33576. pContext->pDeviceInfos[iFirstCaptureDevice] = *pInfo;
  33577. pContext->playbackDeviceInfoCount += 1;
  33578. } else {
  33579. /* Capture. Insert at the end. */
  33580. pContext->pDeviceInfos[totalDeviceInfoCount] = *pInfo;
  33581. pContext->captureDeviceInfoCount += 1;
  33582. }
  33583. (void)pUserData;
  33584. return MA_TRUE;
  33585. }
  33586. 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)
  33587. {
  33588. ma_result result;
  33589. /* Safety. */
  33590. if (ppPlaybackDeviceInfos != NULL) *ppPlaybackDeviceInfos = NULL;
  33591. if (pPlaybackDeviceCount != NULL) *pPlaybackDeviceCount = 0;
  33592. if (ppCaptureDeviceInfos != NULL) *ppCaptureDeviceInfos = NULL;
  33593. if (pCaptureDeviceCount != NULL) *pCaptureDeviceCount = 0;
  33594. if (pContext == NULL) {
  33595. return MA_INVALID_ARGS;
  33596. }
  33597. if (pContext->callbacks.onContextEnumerateDevices == NULL) {
  33598. return MA_INVALID_OPERATION;
  33599. }
  33600. /* Note that we don't use ma_context_enumerate_devices() here because we want to do locking at a higher level. */
  33601. ma_mutex_lock(&pContext->deviceEnumLock);
  33602. {
  33603. /* Reset everything first. */
  33604. pContext->playbackDeviceInfoCount = 0;
  33605. pContext->captureDeviceInfoCount = 0;
  33606. /* Now enumerate over available devices. */
  33607. result = pContext->callbacks.onContextEnumerateDevices(pContext, ma_context_get_devices__enum_callback, NULL);
  33608. if (result == MA_SUCCESS) {
  33609. /* Playback devices. */
  33610. if (ppPlaybackDeviceInfos != NULL) {
  33611. *ppPlaybackDeviceInfos = pContext->pDeviceInfos;
  33612. }
  33613. if (pPlaybackDeviceCount != NULL) {
  33614. *pPlaybackDeviceCount = pContext->playbackDeviceInfoCount;
  33615. }
  33616. /* Capture devices. */
  33617. if (ppCaptureDeviceInfos != NULL) {
  33618. *ppCaptureDeviceInfos = pContext->pDeviceInfos;
  33619. /* Capture devices come after playback devices. */
  33620. if (pContext->playbackDeviceInfoCount > 0) {
  33621. /* Conditional, because NULL+0 is undefined behavior. */
  33622. *ppCaptureDeviceInfos += pContext->playbackDeviceInfoCount;
  33623. }
  33624. }
  33625. if (pCaptureDeviceCount != NULL) {
  33626. *pCaptureDeviceCount = pContext->captureDeviceInfoCount;
  33627. }
  33628. }
  33629. }
  33630. ma_mutex_unlock(&pContext->deviceEnumLock);
  33631. return result;
  33632. }
  33633. 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)
  33634. {
  33635. ma_result result;
  33636. ma_device_info deviceInfo;
  33637. /* NOTE: Do not clear pDeviceInfo on entry. The reason is the pDeviceID may actually point to pDeviceInfo->id which will break things. */
  33638. if (pContext == NULL || pDeviceInfo == NULL) {
  33639. return MA_INVALID_ARGS;
  33640. }
  33641. MA_ZERO_OBJECT(&deviceInfo);
  33642. /* Help the backend out by copying over the device ID if we have one. */
  33643. if (pDeviceID != NULL) {
  33644. MA_COPY_MEMORY(&deviceInfo.id, pDeviceID, sizeof(*pDeviceID));
  33645. }
  33646. if (pContext->callbacks.onContextGetDeviceInfo == NULL) {
  33647. return MA_INVALID_OPERATION;
  33648. }
  33649. ma_mutex_lock(&pContext->deviceInfoLock);
  33650. {
  33651. result = pContext->callbacks.onContextGetDeviceInfo(pContext, deviceType, pDeviceID, &deviceInfo);
  33652. }
  33653. ma_mutex_unlock(&pContext->deviceInfoLock);
  33654. *pDeviceInfo = deviceInfo;
  33655. return result;
  33656. }
  33657. MA_API ma_bool32 ma_context_is_loopback_supported(ma_context* pContext)
  33658. {
  33659. if (pContext == NULL) {
  33660. return MA_FALSE;
  33661. }
  33662. return ma_is_loopback_supported(pContext->backend);
  33663. }
  33664. MA_API ma_device_config ma_device_config_init(ma_device_type deviceType)
  33665. {
  33666. ma_device_config config;
  33667. MA_ZERO_OBJECT(&config);
  33668. config.deviceType = deviceType;
  33669. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate don't matter here. */
  33670. return config;
  33671. }
  33672. MA_API ma_result ma_device_init(ma_context* pContext, const ma_device_config* pConfig, ma_device* pDevice)
  33673. {
  33674. ma_result result;
  33675. ma_device_descriptor descriptorPlayback;
  33676. ma_device_descriptor descriptorCapture;
  33677. /* The context can be null, in which case we self-manage it. */
  33678. if (pContext == NULL) {
  33679. return ma_device_init_ex(NULL, 0, NULL, pConfig, pDevice);
  33680. }
  33681. if (pDevice == NULL) {
  33682. return MA_INVALID_ARGS;
  33683. }
  33684. MA_ZERO_OBJECT(pDevice);
  33685. if (pConfig == NULL) {
  33686. return MA_INVALID_ARGS;
  33687. }
  33688. /* Check that we have our callbacks defined. */
  33689. if (pContext->callbacks.onDeviceInit == NULL) {
  33690. return MA_INVALID_OPERATION;
  33691. }
  33692. /* Basic config validation. */
  33693. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex) {
  33694. if (pConfig->capture.channels > MA_MAX_CHANNELS) {
  33695. return MA_INVALID_ARGS;
  33696. }
  33697. if (!ma__is_channel_map_valid(pConfig->capture.pChannelMap, pConfig->capture.channels)) {
  33698. return MA_INVALID_ARGS;
  33699. }
  33700. }
  33701. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  33702. if (pConfig->playback.channels > MA_MAX_CHANNELS) {
  33703. return MA_INVALID_ARGS;
  33704. }
  33705. if (!ma__is_channel_map_valid(pConfig->playback.pChannelMap, pConfig->playback.channels)) {
  33706. return MA_INVALID_ARGS;
  33707. }
  33708. }
  33709. pDevice->pContext = pContext;
  33710. /* Set the user data and log callback ASAP to ensure it is available for the entire initialization process. */
  33711. pDevice->pUserData = pConfig->pUserData;
  33712. pDevice->onData = pConfig->dataCallback;
  33713. pDevice->onNotification = pConfig->notificationCallback;
  33714. pDevice->onStop = pConfig->stopCallback;
  33715. if (pConfig->playback.pDeviceID != NULL) {
  33716. MA_COPY_MEMORY(&pDevice->playback.id, pConfig->playback.pDeviceID, sizeof(pDevice->playback.id));
  33717. pDevice->playback.pID = &pDevice->playback.id;
  33718. } else {
  33719. pDevice->playback.pID = NULL;
  33720. }
  33721. if (pConfig->capture.pDeviceID != NULL) {
  33722. MA_COPY_MEMORY(&pDevice->capture.id, pConfig->capture.pDeviceID, sizeof(pDevice->capture.id));
  33723. pDevice->capture.pID = &pDevice->capture.id;
  33724. } else {
  33725. pDevice->capture.pID = NULL;
  33726. }
  33727. pDevice->noPreSilencedOutputBuffer = pConfig->noPreSilencedOutputBuffer;
  33728. pDevice->noClip = pConfig->noClip;
  33729. pDevice->noDisableDenormals = pConfig->noDisableDenormals;
  33730. pDevice->noFixedSizedCallback = pConfig->noFixedSizedCallback;
  33731. pDevice->masterVolumeFactor = 1;
  33732. pDevice->type = pConfig->deviceType;
  33733. pDevice->sampleRate = pConfig->sampleRate;
  33734. pDevice->resampling.algorithm = pConfig->resampling.algorithm;
  33735. pDevice->resampling.linear.lpfOrder = pConfig->resampling.linear.lpfOrder;
  33736. pDevice->resampling.pBackendVTable = pConfig->resampling.pBackendVTable;
  33737. pDevice->resampling.pBackendUserData = pConfig->resampling.pBackendUserData;
  33738. pDevice->capture.shareMode = pConfig->capture.shareMode;
  33739. pDevice->capture.format = pConfig->capture.format;
  33740. pDevice->capture.channels = pConfig->capture.channels;
  33741. ma_channel_map_copy_or_default(pDevice->capture.channelMap, ma_countof(pDevice->capture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  33742. pDevice->capture.channelMixMode = pConfig->capture.channelMixMode;
  33743. pDevice->capture.calculateLFEFromSpatialChannels = pConfig->capture.calculateLFEFromSpatialChannels;
  33744. pDevice->playback.shareMode = pConfig->playback.shareMode;
  33745. pDevice->playback.format = pConfig->playback.format;
  33746. pDevice->playback.channels = pConfig->playback.channels;
  33747. ma_channel_map_copy_or_default(pDevice->playback.channelMap, ma_countof(pDevice->playback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  33748. pDevice->playback.channelMixMode = pConfig->playback.channelMixMode;
  33749. pDevice->playback.calculateLFEFromSpatialChannels = pConfig->playback.calculateLFEFromSpatialChannels;
  33750. result = ma_mutex_init(&pDevice->startStopLock);
  33751. if (result != MA_SUCCESS) {
  33752. return result;
  33753. }
  33754. /*
  33755. When the device is started, the worker thread is the one that does the actual startup of the backend device. We
  33756. use a semaphore to wait for the background thread to finish the work. The same applies for stopping the device.
  33757. Each of these semaphores is released internally by the worker thread when the work is completed. The start
  33758. semaphore is also used to wake up the worker thread.
  33759. */
  33760. result = ma_event_init(&pDevice->wakeupEvent);
  33761. if (result != MA_SUCCESS) {
  33762. ma_mutex_uninit(&pDevice->startStopLock);
  33763. return result;
  33764. }
  33765. result = ma_event_init(&pDevice->startEvent);
  33766. if (result != MA_SUCCESS) {
  33767. ma_event_uninit(&pDevice->wakeupEvent);
  33768. ma_mutex_uninit(&pDevice->startStopLock);
  33769. return result;
  33770. }
  33771. result = ma_event_init(&pDevice->stopEvent);
  33772. if (result != MA_SUCCESS) {
  33773. ma_event_uninit(&pDevice->startEvent);
  33774. ma_event_uninit(&pDevice->wakeupEvent);
  33775. ma_mutex_uninit(&pDevice->startStopLock);
  33776. return result;
  33777. }
  33778. MA_ZERO_OBJECT(&descriptorPlayback);
  33779. descriptorPlayback.pDeviceID = pConfig->playback.pDeviceID;
  33780. descriptorPlayback.shareMode = pConfig->playback.shareMode;
  33781. descriptorPlayback.format = pConfig->playback.format;
  33782. descriptorPlayback.channels = pConfig->playback.channels;
  33783. descriptorPlayback.sampleRate = pConfig->sampleRate;
  33784. ma_channel_map_copy_or_default(descriptorPlayback.channelMap, ma_countof(descriptorPlayback.channelMap), pConfig->playback.pChannelMap, pConfig->playback.channels);
  33785. descriptorPlayback.periodSizeInFrames = pConfig->periodSizeInFrames;
  33786. descriptorPlayback.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  33787. descriptorPlayback.periodCount = pConfig->periods;
  33788. if (descriptorPlayback.periodCount == 0) {
  33789. descriptorPlayback.periodCount = MA_DEFAULT_PERIODS;
  33790. }
  33791. MA_ZERO_OBJECT(&descriptorCapture);
  33792. descriptorCapture.pDeviceID = pConfig->capture.pDeviceID;
  33793. descriptorCapture.shareMode = pConfig->capture.shareMode;
  33794. descriptorCapture.format = pConfig->capture.format;
  33795. descriptorCapture.channels = pConfig->capture.channels;
  33796. descriptorCapture.sampleRate = pConfig->sampleRate;
  33797. ma_channel_map_copy_or_default(descriptorCapture.channelMap, ma_countof(descriptorCapture.channelMap), pConfig->capture.pChannelMap, pConfig->capture.channels);
  33798. descriptorCapture.periodSizeInFrames = pConfig->periodSizeInFrames;
  33799. descriptorCapture.periodSizeInMilliseconds = pConfig->periodSizeInMilliseconds;
  33800. descriptorCapture.periodCount = pConfig->periods;
  33801. if (descriptorCapture.periodCount == 0) {
  33802. descriptorCapture.periodCount = MA_DEFAULT_PERIODS;
  33803. }
  33804. result = pContext->callbacks.onDeviceInit(pDevice, pConfig, &descriptorPlayback, &descriptorCapture);
  33805. if (result != MA_SUCCESS) {
  33806. ma_event_uninit(&pDevice->startEvent);
  33807. ma_event_uninit(&pDevice->wakeupEvent);
  33808. ma_mutex_uninit(&pDevice->startStopLock);
  33809. return result;
  33810. }
  33811. #if 0
  33812. /*
  33813. On output the descriptors will contain the *actual* data format of the device. We need this to know how to convert the data between
  33814. the requested format and the internal format.
  33815. */
  33816. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  33817. if (!ma_device_descriptor_is_valid(&descriptorCapture)) {
  33818. ma_device_uninit(pDevice);
  33819. return MA_INVALID_ARGS;
  33820. }
  33821. pDevice->capture.internalFormat = descriptorCapture.format;
  33822. pDevice->capture.internalChannels = descriptorCapture.channels;
  33823. pDevice->capture.internalSampleRate = descriptorCapture.sampleRate;
  33824. ma_channel_map_copy(pDevice->capture.internalChannelMap, descriptorCapture.channelMap, descriptorCapture.channels);
  33825. pDevice->capture.internalPeriodSizeInFrames = descriptorCapture.periodSizeInFrames;
  33826. pDevice->capture.internalPeriods = descriptorCapture.periodCount;
  33827. if (pDevice->capture.internalPeriodSizeInFrames == 0) {
  33828. pDevice->capture.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorCapture.periodSizeInMilliseconds, descriptorCapture.sampleRate);
  33829. }
  33830. }
  33831. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  33832. if (!ma_device_descriptor_is_valid(&descriptorPlayback)) {
  33833. ma_device_uninit(pDevice);
  33834. return MA_INVALID_ARGS;
  33835. }
  33836. pDevice->playback.internalFormat = descriptorPlayback.format;
  33837. pDevice->playback.internalChannels = descriptorPlayback.channels;
  33838. pDevice->playback.internalSampleRate = descriptorPlayback.sampleRate;
  33839. ma_channel_map_copy(pDevice->playback.internalChannelMap, descriptorPlayback.channelMap, descriptorPlayback.channels);
  33840. pDevice->playback.internalPeriodSizeInFrames = descriptorPlayback.periodSizeInFrames;
  33841. pDevice->playback.internalPeriods = descriptorPlayback.periodCount;
  33842. if (pDevice->playback.internalPeriodSizeInFrames == 0) {
  33843. pDevice->playback.internalPeriodSizeInFrames = ma_calculate_buffer_size_in_frames_from_milliseconds(descriptorPlayback.periodSizeInMilliseconds, descriptorPlayback.sampleRate);
  33844. }
  33845. }
  33846. /*
  33847. 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.
  33848. For loopback devices, we need to retrieve the name of the playback device.
  33849. */
  33850. {
  33851. ma_device_info deviceInfo;
  33852. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  33853. result = ma_device_get_info(pDevice, (pConfig->deviceType == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, &deviceInfo);
  33854. if (result == MA_SUCCESS) {
  33855. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), deviceInfo.name, (size_t)-1);
  33856. } else {
  33857. /* We failed to retrieve the device info. Fall back to a default name. */
  33858. if (descriptorCapture.pDeviceID == NULL) {
  33859. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), MA_DEFAULT_CAPTURE_DEVICE_NAME, (size_t)-1);
  33860. } else {
  33861. ma_strncpy_s(pDevice->capture.name, sizeof(pDevice->capture.name), "Capture Device", (size_t)-1);
  33862. }
  33863. }
  33864. }
  33865. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  33866. result = ma_device_get_info(pDevice, ma_device_type_playback, &deviceInfo);
  33867. if (result == MA_SUCCESS) {
  33868. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), deviceInfo.name, (size_t)-1);
  33869. } else {
  33870. /* We failed to retrieve the device info. Fall back to a default name. */
  33871. if (descriptorPlayback.pDeviceID == NULL) {
  33872. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), MA_DEFAULT_PLAYBACK_DEVICE_NAME, (size_t)-1);
  33873. } else {
  33874. ma_strncpy_s(pDevice->playback.name, sizeof(pDevice->playback.name), "Playback Device", (size_t)-1);
  33875. }
  33876. }
  33877. }
  33878. }
  33879. ma_device__post_init_setup(pDevice, pConfig->deviceType);
  33880. #endif
  33881. result = ma_device_post_init(pDevice, pConfig->deviceType, &descriptorPlayback, &descriptorCapture);
  33882. if (result != MA_SUCCESS) {
  33883. ma_device_uninit(pDevice);
  33884. return result;
  33885. }
  33886. /*
  33887. If we're using fixed sized callbacks we'll need to make use of an intermediary buffer. Needs to
  33888. be done after post_init_setup() because we'll need access to the sample rate.
  33889. */
  33890. if (pConfig->noFixedSizedCallback == MA_FALSE) {
  33891. /* We're using a fixed sized data callback so we'll need an intermediary buffer. */
  33892. ma_uint32 intermediaryBufferCap = pConfig->periodSizeInFrames;
  33893. if (intermediaryBufferCap == 0) {
  33894. intermediaryBufferCap = ma_calculate_buffer_size_in_frames_from_milliseconds(pConfig->periodSizeInMilliseconds, pDevice->sampleRate);
  33895. }
  33896. if (pConfig->deviceType == ma_device_type_capture || pConfig->deviceType == ma_device_type_duplex || pConfig->deviceType == ma_device_type_loopback) {
  33897. ma_uint32 intermediaryBufferSizeInBytes;
  33898. pDevice->capture.intermediaryBufferLen = 0;
  33899. pDevice->capture.intermediaryBufferCap = intermediaryBufferCap;
  33900. if (pDevice->capture.intermediaryBufferCap == 0) {
  33901. pDevice->capture.intermediaryBufferCap = pDevice->capture.internalPeriodSizeInFrames;
  33902. }
  33903. intermediaryBufferSizeInBytes = pDevice->capture.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->capture.format, pDevice->capture.channels);
  33904. pDevice->capture.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  33905. if (pDevice->capture.pIntermediaryBuffer == NULL) {
  33906. ma_device_uninit(pDevice);
  33907. return MA_OUT_OF_MEMORY;
  33908. }
  33909. /* Silence the buffer for safety. */
  33910. ma_silence_pcm_frames(pDevice->capture.pIntermediaryBuffer, pDevice->capture.intermediaryBufferCap, pDevice->capture.format, pDevice->capture.channels);
  33911. pDevice->capture.intermediaryBufferLen = pDevice->capture.intermediaryBufferCap;
  33912. }
  33913. if (pConfig->deviceType == ma_device_type_playback || pConfig->deviceType == ma_device_type_duplex) {
  33914. ma_uint64 intermediaryBufferSizeInBytes;
  33915. pDevice->playback.intermediaryBufferLen = 0;
  33916. if (pConfig->deviceType == ma_device_type_duplex) {
  33917. pDevice->playback.intermediaryBufferCap = pDevice->capture.intermediaryBufferCap; /* In duplex mode, make sure the intermediary buffer is always the same size as the capture side. */
  33918. } else {
  33919. pDevice->playback.intermediaryBufferCap = intermediaryBufferCap;
  33920. if (pDevice->playback.intermediaryBufferCap == 0) {
  33921. pDevice->playback.intermediaryBufferCap = pDevice->playback.internalPeriodSizeInFrames;
  33922. }
  33923. }
  33924. intermediaryBufferSizeInBytes = pDevice->playback.intermediaryBufferCap * ma_get_bytes_per_frame(pDevice->playback.format, pDevice->playback.channels);
  33925. pDevice->playback.pIntermediaryBuffer = ma_malloc((size_t)intermediaryBufferSizeInBytes, &pContext->allocationCallbacks);
  33926. if (pDevice->playback.pIntermediaryBuffer == NULL) {
  33927. ma_device_uninit(pDevice);
  33928. return MA_OUT_OF_MEMORY;
  33929. }
  33930. /* Silence the buffer for safety. */
  33931. ma_silence_pcm_frames(pDevice->playback.pIntermediaryBuffer, pDevice->playback.intermediaryBufferCap, pDevice->playback.format, pDevice->playback.channels);
  33932. pDevice->playback.intermediaryBufferLen = 0;
  33933. }
  33934. } else {
  33935. /* Not using a fixed sized data callback so no need for an intermediary buffer. */
  33936. }
  33937. /* Some backends don't require the worker thread. */
  33938. if (!ma_context_is_backend_asynchronous(pContext)) {
  33939. /* The worker thread. */
  33940. result = ma_thread_create(&pDevice->thread, pContext->threadPriority, pContext->threadStackSize, ma_worker_thread, pDevice, &pContext->allocationCallbacks);
  33941. if (result != MA_SUCCESS) {
  33942. ma_device_uninit(pDevice);
  33943. return result;
  33944. }
  33945. /* Wait for the worker thread to put the device into it's stopped state for real. */
  33946. ma_event_wait(&pDevice->stopEvent);
  33947. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  33948. } else {
  33949. /*
  33950. If the backend is asynchronous and the device is duplex, we'll need an intermediary ring buffer. Note that this needs to be done
  33951. after ma_device__post_init_setup().
  33952. */
  33953. if (ma_context_is_backend_asynchronous(pContext)) {
  33954. if (pConfig->deviceType == ma_device_type_duplex) {
  33955. result = ma_duplex_rb_init(pDevice->capture.format, pDevice->capture.channels, pDevice->sampleRate, pDevice->capture.internalSampleRate, pDevice->capture.internalPeriodSizeInFrames, &pDevice->pContext->allocationCallbacks, &pDevice->duplexRB);
  33956. if (result != MA_SUCCESS) {
  33957. ma_device_uninit(pDevice);
  33958. return result;
  33959. }
  33960. }
  33961. }
  33962. ma_device__set_state(pDevice, ma_device_state_stopped);
  33963. }
  33964. /* Log device information. */
  33965. {
  33966. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, "[%s]\n", ma_get_backend_name(pDevice->pContext->backend));
  33967. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  33968. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  33969. ma_device_get_name(pDevice, (pDevice->type == ma_device_type_loopback) ? ma_device_type_playback : ma_device_type_capture, name, sizeof(name), NULL);
  33970. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Capture");
  33971. 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));
  33972. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->capture.internalChannels, pDevice->capture.channels);
  33973. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->capture.internalSampleRate, pDevice->sampleRate);
  33974. 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));
  33975. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  33976. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->capture.converter.hasPreFormatConversion ? "YES" : "NO");
  33977. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->capture.converter.hasPostFormatConversion ? "YES" : "NO");
  33978. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->capture.converter.hasChannelConverter ? "YES" : "NO");
  33979. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->capture.converter.hasResampler ? "YES" : "NO");
  33980. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->capture.converter.isPassthrough ? "YES" : "NO");
  33981. {
  33982. char channelMapStr[1024];
  33983. ma_channel_map_to_string(pDevice->capture.internalChannelMap, pDevice->capture.internalChannels, channelMapStr, sizeof(channelMapStr));
  33984. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  33985. ma_channel_map_to_string(pDevice->capture.channelMap, pDevice->capture.channels, channelMapStr, sizeof(channelMapStr));
  33986. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  33987. }
  33988. }
  33989. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  33990. char name[MA_MAX_DEVICE_NAME_LENGTH + 1];
  33991. ma_device_get_name(pDevice, ma_device_type_playback, name, sizeof(name), NULL);
  33992. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " %s (%s)\n", name, "Playback");
  33993. 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));
  33994. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channels: %d -> %d\n", pDevice->playback.channels, pDevice->playback.internalChannels);
  33995. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Sample Rate: %d -> %d\n", pDevice->sampleRate, pDevice->playback.internalSampleRate);
  33996. 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));
  33997. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Conversion:\n");
  33998. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Pre Format Conversion: %s\n", pDevice->playback.converter.hasPreFormatConversion ? "YES" : "NO");
  33999. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Post Format Conversion: %s\n", pDevice->playback.converter.hasPostFormatConversion ? "YES" : "NO");
  34000. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Routing: %s\n", pDevice->playback.converter.hasChannelConverter ? "YES" : "NO");
  34001. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Resampling: %s\n", pDevice->playback.converter.hasResampler ? "YES" : "NO");
  34002. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Passthrough: %s\n", pDevice->playback.converter.isPassthrough ? "YES" : "NO");
  34003. {
  34004. char channelMapStr[1024];
  34005. ma_channel_map_to_string(pDevice->playback.channelMap, pDevice->playback.channels, channelMapStr, sizeof(channelMapStr));
  34006. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map In: {%s}\n", channelMapStr);
  34007. ma_channel_map_to_string(pDevice->playback.internalChannelMap, pDevice->playback.internalChannels, channelMapStr, sizeof(channelMapStr));
  34008. ma_log_postf(ma_device_get_log(pDevice), MA_LOG_LEVEL_INFO, " Channel Map Out: {%s}\n", channelMapStr);
  34009. }
  34010. }
  34011. }
  34012. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  34013. return MA_SUCCESS;
  34014. }
  34015. 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)
  34016. {
  34017. ma_result result;
  34018. ma_context* pContext;
  34019. ma_backend defaultBackends[ma_backend_null+1];
  34020. ma_uint32 iBackend;
  34021. ma_backend* pBackendsToIterate;
  34022. ma_uint32 backendsToIterateCount;
  34023. ma_allocation_callbacks allocationCallbacks;
  34024. if (pConfig == NULL) {
  34025. return MA_INVALID_ARGS;
  34026. }
  34027. if (pContextConfig != NULL) {
  34028. result = ma_allocation_callbacks_init_copy(&allocationCallbacks, &pContextConfig->allocationCallbacks);
  34029. if (result != MA_SUCCESS) {
  34030. return result;
  34031. }
  34032. } else {
  34033. allocationCallbacks = ma_allocation_callbacks_init_default();
  34034. }
  34035. pContext = (ma_context*)ma_malloc(sizeof(*pContext), &allocationCallbacks);
  34036. if (pContext == NULL) {
  34037. return MA_OUT_OF_MEMORY;
  34038. }
  34039. for (iBackend = 0; iBackend <= ma_backend_null; ++iBackend) {
  34040. defaultBackends[iBackend] = (ma_backend)iBackend;
  34041. }
  34042. pBackendsToIterate = (ma_backend*)backends;
  34043. backendsToIterateCount = backendCount;
  34044. if (pBackendsToIterate == NULL) {
  34045. pBackendsToIterate = (ma_backend*)defaultBackends;
  34046. backendsToIterateCount = ma_countof(defaultBackends);
  34047. }
  34048. result = MA_NO_BACKEND;
  34049. for (iBackend = 0; iBackend < backendsToIterateCount; ++iBackend) {
  34050. /*
  34051. This is a hack for iOS. If the context config is null, there's a good chance the
  34052. `ma_device_init(NULL, &deviceConfig, pDevice);` pattern is being used. In this
  34053. case, set the session category based on the device type.
  34054. */
  34055. #if defined(MA_APPLE_MOBILE)
  34056. ma_context_config contextConfig;
  34057. if (pContextConfig == NULL) {
  34058. contextConfig = ma_context_config_init();
  34059. switch (pConfig->deviceType) {
  34060. case ma_device_type_duplex: {
  34061. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_play_and_record;
  34062. } break;
  34063. case ma_device_type_capture: {
  34064. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_record;
  34065. } break;
  34066. case ma_device_type_playback:
  34067. default: {
  34068. contextConfig.coreaudio.sessionCategory = ma_ios_session_category_playback;
  34069. } break;
  34070. }
  34071. pContextConfig = &contextConfig;
  34072. }
  34073. #endif
  34074. result = ma_context_init(&pBackendsToIterate[iBackend], 1, pContextConfig, pContext);
  34075. if (result == MA_SUCCESS) {
  34076. result = ma_device_init(pContext, pConfig, pDevice);
  34077. if (result == MA_SUCCESS) {
  34078. break; /* Success. */
  34079. } else {
  34080. ma_context_uninit(pContext); /* Failure. */
  34081. }
  34082. }
  34083. }
  34084. if (result != MA_SUCCESS) {
  34085. ma_free(pContext, &allocationCallbacks);
  34086. return result;
  34087. }
  34088. pDevice->isOwnerOfContext = MA_TRUE;
  34089. return result;
  34090. }
  34091. MA_API void ma_device_uninit(ma_device* pDevice)
  34092. {
  34093. if (!ma_device__is_initialized(pDevice)) {
  34094. return;
  34095. }
  34096. /* 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. */
  34097. if (ma_device_is_started(pDevice)) {
  34098. ma_device_stop(pDevice);
  34099. }
  34100. /* Putting the device into an uninitialized state will make the worker thread return. */
  34101. ma_device__set_state(pDevice, ma_device_state_uninitialized);
  34102. /* Wake up the worker thread and wait for it to properly terminate. */
  34103. if (!ma_context_is_backend_asynchronous(pDevice->pContext)) {
  34104. ma_event_signal(&pDevice->wakeupEvent);
  34105. ma_thread_wait(&pDevice->thread);
  34106. }
  34107. if (pDevice->pContext->callbacks.onDeviceUninit != NULL) {
  34108. pDevice->pContext->callbacks.onDeviceUninit(pDevice);
  34109. }
  34110. ma_event_uninit(&pDevice->stopEvent);
  34111. ma_event_uninit(&pDevice->startEvent);
  34112. ma_event_uninit(&pDevice->wakeupEvent);
  34113. ma_mutex_uninit(&pDevice->startStopLock);
  34114. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  34115. if (pDevice->type == ma_device_type_duplex) {
  34116. ma_duplex_rb_uninit(&pDevice->duplexRB);
  34117. }
  34118. }
  34119. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_duplex || pDevice->type == ma_device_type_loopback) {
  34120. ma_data_converter_uninit(&pDevice->capture.converter, &pDevice->pContext->allocationCallbacks);
  34121. }
  34122. if (pDevice->type == ma_device_type_playback || pDevice->type == ma_device_type_duplex) {
  34123. ma_data_converter_uninit(&pDevice->playback.converter, &pDevice->pContext->allocationCallbacks);
  34124. }
  34125. if (pDevice->playback.pInputCache != NULL) {
  34126. ma_free(pDevice->playback.pInputCache, &pDevice->pContext->allocationCallbacks);
  34127. }
  34128. if (pDevice->capture.pIntermediaryBuffer != NULL) {
  34129. ma_free(pDevice->capture.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  34130. }
  34131. if (pDevice->playback.pIntermediaryBuffer != NULL) {
  34132. ma_free(pDevice->playback.pIntermediaryBuffer, &pDevice->pContext->allocationCallbacks);
  34133. }
  34134. if (pDevice->isOwnerOfContext) {
  34135. ma_allocation_callbacks allocationCallbacks = pDevice->pContext->allocationCallbacks;
  34136. ma_context_uninit(pDevice->pContext);
  34137. ma_free(pDevice->pContext, &allocationCallbacks);
  34138. }
  34139. MA_ZERO_OBJECT(pDevice);
  34140. }
  34141. MA_API ma_context* ma_device_get_context(ma_device* pDevice)
  34142. {
  34143. if (pDevice == NULL) {
  34144. return NULL;
  34145. }
  34146. return pDevice->pContext;
  34147. }
  34148. MA_API ma_log* ma_device_get_log(ma_device* pDevice)
  34149. {
  34150. return ma_context_get_log(ma_device_get_context(pDevice));
  34151. }
  34152. MA_API ma_result ma_device_get_info(ma_device* pDevice, ma_device_type type, ma_device_info* pDeviceInfo)
  34153. {
  34154. if (pDeviceInfo == NULL) {
  34155. return MA_INVALID_ARGS;
  34156. }
  34157. MA_ZERO_OBJECT(pDeviceInfo);
  34158. if (pDevice == NULL) {
  34159. return MA_INVALID_ARGS;
  34160. }
  34161. /* If the onDeviceGetInfo() callback is set, use that. Otherwise we'll fall back to ma_context_get_device_info(). */
  34162. if (pDevice->pContext->callbacks.onDeviceGetInfo != NULL) {
  34163. return pDevice->pContext->callbacks.onDeviceGetInfo(pDevice, type, pDeviceInfo);
  34164. }
  34165. /* Getting here means onDeviceGetInfo is not implemented so we need to fall back to an alternative. */
  34166. if (type == ma_device_type_playback) {
  34167. return ma_context_get_device_info(pDevice->pContext, type, pDevice->playback.pID, pDeviceInfo);
  34168. } else {
  34169. return ma_context_get_device_info(pDevice->pContext, type, pDevice->capture.pID, pDeviceInfo);
  34170. }
  34171. }
  34172. MA_API ma_result ma_device_get_name(ma_device* pDevice, ma_device_type type, char* pName, size_t nameCap, size_t* pLengthNotIncludingNullTerminator)
  34173. {
  34174. ma_result result;
  34175. ma_device_info deviceInfo;
  34176. if (pLengthNotIncludingNullTerminator != NULL) {
  34177. *pLengthNotIncludingNullTerminator = 0;
  34178. }
  34179. if (pName != NULL && nameCap > 0) {
  34180. pName[0] = '\0';
  34181. }
  34182. result = ma_device_get_info(pDevice, type, &deviceInfo);
  34183. if (result != MA_SUCCESS) {
  34184. return result;
  34185. }
  34186. if (pName != NULL) {
  34187. ma_strncpy_s(pName, nameCap, deviceInfo.name, (size_t)-1);
  34188. /*
  34189. For safety, make sure the length is based on the truncated output string rather than the
  34190. source. Otherwise the caller might assume the output buffer contains more content than it
  34191. actually does.
  34192. */
  34193. if (pLengthNotIncludingNullTerminator != NULL) {
  34194. *pLengthNotIncludingNullTerminator = strlen(pName);
  34195. }
  34196. } else {
  34197. /* Name not specified. Just report the length of the source string. */
  34198. if (pLengthNotIncludingNullTerminator != NULL) {
  34199. *pLengthNotIncludingNullTerminator = strlen(deviceInfo.name);
  34200. }
  34201. }
  34202. return MA_SUCCESS;
  34203. }
  34204. MA_API ma_result ma_device_start(ma_device* pDevice)
  34205. {
  34206. ma_result result;
  34207. if (pDevice == NULL) {
  34208. return MA_INVALID_ARGS;
  34209. }
  34210. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  34211. return MA_INVALID_OPERATION; /* Not initialized. */
  34212. }
  34213. if (ma_device_get_state(pDevice) == ma_device_state_started) {
  34214. return MA_SUCCESS; /* Already started. */
  34215. }
  34216. ma_mutex_lock(&pDevice->startStopLock);
  34217. {
  34218. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a stopped or paused state. */
  34219. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_stopped);
  34220. ma_device__set_state(pDevice, ma_device_state_starting);
  34221. /* Asynchronous backends need to be handled differently. */
  34222. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  34223. if (pDevice->pContext->callbacks.onDeviceStart != NULL) {
  34224. result = pDevice->pContext->callbacks.onDeviceStart(pDevice);
  34225. } else {
  34226. result = MA_INVALID_OPERATION;
  34227. }
  34228. if (result == MA_SUCCESS) {
  34229. ma_device__set_state(pDevice, ma_device_state_started);
  34230. ma_device__on_notification_started(pDevice);
  34231. }
  34232. } else {
  34233. /*
  34234. Synchronous backends are started by signaling an event that's being waited on in the worker thread. We first wake up the
  34235. thread and then wait for the start event.
  34236. */
  34237. ma_event_signal(&pDevice->wakeupEvent);
  34238. /*
  34239. Wait for the worker thread to finish starting the device. Note that the worker thread will be the one who puts the device
  34240. into the started state. Don't call ma_device__set_state() here.
  34241. */
  34242. ma_event_wait(&pDevice->startEvent);
  34243. result = pDevice->workResult;
  34244. }
  34245. /* We changed the state from stopped to started, so if we failed, make sure we put the state back to stopped. */
  34246. if (result != MA_SUCCESS) {
  34247. ma_device__set_state(pDevice, ma_device_state_stopped);
  34248. }
  34249. }
  34250. ma_mutex_unlock(&pDevice->startStopLock);
  34251. return result;
  34252. }
  34253. MA_API ma_result ma_device_stop(ma_device* pDevice)
  34254. {
  34255. ma_result result;
  34256. if (pDevice == NULL) {
  34257. return MA_INVALID_ARGS;
  34258. }
  34259. if (ma_device_get_state(pDevice) == ma_device_state_uninitialized) {
  34260. return MA_INVALID_OPERATION; /* Not initialized. */
  34261. }
  34262. if (ma_device_get_state(pDevice) == ma_device_state_stopped) {
  34263. return MA_SUCCESS; /* Already stopped. */
  34264. }
  34265. ma_mutex_lock(&pDevice->startStopLock);
  34266. {
  34267. /* Starting and stopping are wrapped in a mutex which means we can assert that the device is in a started or paused state. */
  34268. MA_ASSERT(ma_device_get_state(pDevice) == ma_device_state_started);
  34269. ma_device__set_state(pDevice, ma_device_state_stopping);
  34270. /* Asynchronous backends need to be handled differently. */
  34271. if (ma_context_is_backend_asynchronous(pDevice->pContext)) {
  34272. /* Asynchronous backends must have a stop operation. */
  34273. if (pDevice->pContext->callbacks.onDeviceStop != NULL) {
  34274. result = pDevice->pContext->callbacks.onDeviceStop(pDevice);
  34275. } else {
  34276. result = MA_INVALID_OPERATION;
  34277. }
  34278. ma_device__set_state(pDevice, ma_device_state_stopped);
  34279. } else {
  34280. /*
  34281. Synchronous backends. The stop callback is always called from the worker thread. Do not call the stop callback here. If
  34282. 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
  34283. sure the state of the device is *not* playing right now, which it shouldn't be since we set it above. This is super
  34284. important though, so I'm asserting it here as well for extra safety in case we accidentally change something later.
  34285. */
  34286. MA_ASSERT(ma_device_get_state(pDevice) != ma_device_state_started);
  34287. if (pDevice->pContext->callbacks.onDeviceDataLoopWakeup != NULL) {
  34288. pDevice->pContext->callbacks.onDeviceDataLoopWakeup(pDevice);
  34289. }
  34290. /*
  34291. We need to wait for the worker thread to become available for work before returning. Note that the worker thread will be
  34292. the one who puts the device into the stopped state. Don't call ma_device__set_state() here.
  34293. */
  34294. ma_event_wait(&pDevice->stopEvent);
  34295. result = MA_SUCCESS;
  34296. }
  34297. /*
  34298. This is a safety measure to ensure the internal buffer has been cleared so any leftover
  34299. does not get played the next time the device starts. Ideally this should be drained by
  34300. the backend first.
  34301. */
  34302. pDevice->playback.intermediaryBufferLen = 0;
  34303. pDevice->playback.inputCacheConsumed = 0;
  34304. pDevice->playback.inputCacheRemaining = 0;
  34305. }
  34306. ma_mutex_unlock(&pDevice->startStopLock);
  34307. return result;
  34308. }
  34309. MA_API ma_bool32 ma_device_is_started(const ma_device* pDevice)
  34310. {
  34311. return ma_device_get_state(pDevice) == ma_device_state_started;
  34312. }
  34313. MA_API ma_device_state ma_device_get_state(const ma_device* pDevice)
  34314. {
  34315. if (pDevice == NULL) {
  34316. return ma_device_state_uninitialized;
  34317. }
  34318. return (ma_device_state)c89atomic_load_i32((ma_int32*)&pDevice->state); /* Naughty cast to get rid of a const warning. */
  34319. }
  34320. MA_API ma_result ma_device_set_master_volume(ma_device* pDevice, float volume)
  34321. {
  34322. if (pDevice == NULL) {
  34323. return MA_INVALID_ARGS;
  34324. }
  34325. if (volume < 0.0f) {
  34326. return MA_INVALID_ARGS;
  34327. }
  34328. c89atomic_exchange_f32(&pDevice->masterVolumeFactor, volume);
  34329. return MA_SUCCESS;
  34330. }
  34331. MA_API ma_result ma_device_get_master_volume(ma_device* pDevice, float* pVolume)
  34332. {
  34333. if (pVolume == NULL) {
  34334. return MA_INVALID_ARGS;
  34335. }
  34336. if (pDevice == NULL) {
  34337. *pVolume = 0;
  34338. return MA_INVALID_ARGS;
  34339. }
  34340. *pVolume = c89atomic_load_f32(&pDevice->masterVolumeFactor);
  34341. return MA_SUCCESS;
  34342. }
  34343. MA_API ma_result ma_device_set_master_volume_db(ma_device* pDevice, float gainDB)
  34344. {
  34345. if (gainDB > 0) {
  34346. return MA_INVALID_ARGS;
  34347. }
  34348. return ma_device_set_master_volume(pDevice, ma_volume_db_to_linear(gainDB));
  34349. }
  34350. MA_API ma_result ma_device_get_master_volume_db(ma_device* pDevice, float* pGainDB)
  34351. {
  34352. float factor;
  34353. ma_result result;
  34354. if (pGainDB == NULL) {
  34355. return MA_INVALID_ARGS;
  34356. }
  34357. result = ma_device_get_master_volume(pDevice, &factor);
  34358. if (result != MA_SUCCESS) {
  34359. *pGainDB = 0;
  34360. return result;
  34361. }
  34362. *pGainDB = ma_volume_linear_to_db(factor);
  34363. return MA_SUCCESS;
  34364. }
  34365. MA_API ma_result ma_device_handle_backend_data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount)
  34366. {
  34367. if (pDevice == NULL) {
  34368. return MA_INVALID_ARGS;
  34369. }
  34370. if (pOutput == NULL && pInput == NULL) {
  34371. return MA_INVALID_ARGS;
  34372. }
  34373. if (pDevice->type == ma_device_type_duplex) {
  34374. if (pInput != NULL) {
  34375. ma_device__handle_duplex_callback_capture(pDevice, frameCount, pInput, &pDevice->duplexRB.rb);
  34376. }
  34377. if (pOutput != NULL) {
  34378. ma_device__handle_duplex_callback_playback(pDevice, frameCount, pOutput, &pDevice->duplexRB.rb);
  34379. }
  34380. } else {
  34381. if (pDevice->type == ma_device_type_capture || pDevice->type == ma_device_type_loopback) {
  34382. if (pInput == NULL) {
  34383. return MA_INVALID_ARGS;
  34384. }
  34385. ma_device__send_frames_to_client(pDevice, frameCount, pInput);
  34386. }
  34387. if (pDevice->type == ma_device_type_playback) {
  34388. if (pOutput == NULL) {
  34389. return MA_INVALID_ARGS;
  34390. }
  34391. ma_device__read_frames_from_client(pDevice, frameCount, pOutput);
  34392. }
  34393. }
  34394. return MA_SUCCESS;
  34395. }
  34396. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_descriptor(const ma_device_descriptor* pDescriptor, ma_uint32 nativeSampleRate, ma_performance_profile performanceProfile)
  34397. {
  34398. if (pDescriptor == NULL) {
  34399. return 0;
  34400. }
  34401. /*
  34402. We must have a non-0 native sample rate, but some backends don't allow retrieval of this at the
  34403. time when the size of the buffer needs to be determined. In this case we need to just take a best
  34404. guess and move on. We'll try using the sample rate in pDescriptor first. If that's not set we'll
  34405. just fall back to MA_DEFAULT_SAMPLE_RATE.
  34406. */
  34407. if (nativeSampleRate == 0) {
  34408. nativeSampleRate = pDescriptor->sampleRate;
  34409. }
  34410. if (nativeSampleRate == 0) {
  34411. nativeSampleRate = MA_DEFAULT_SAMPLE_RATE;
  34412. }
  34413. MA_ASSERT(nativeSampleRate != 0);
  34414. if (pDescriptor->periodSizeInFrames == 0) {
  34415. if (pDescriptor->periodSizeInMilliseconds == 0) {
  34416. if (performanceProfile == ma_performance_profile_low_latency) {
  34417. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_LOW_LATENCY, nativeSampleRate);
  34418. } else {
  34419. return ma_calculate_buffer_size_in_frames_from_milliseconds(MA_DEFAULT_PERIOD_SIZE_IN_MILLISECONDS_CONSERVATIVE, nativeSampleRate);
  34420. }
  34421. } else {
  34422. return ma_calculate_buffer_size_in_frames_from_milliseconds(pDescriptor->periodSizeInMilliseconds, nativeSampleRate);
  34423. }
  34424. } else {
  34425. return pDescriptor->periodSizeInFrames;
  34426. }
  34427. }
  34428. #endif /* MA_NO_DEVICE_IO */
  34429. MA_API ma_uint32 ma_calculate_buffer_size_in_milliseconds_from_frames(ma_uint32 bufferSizeInFrames, ma_uint32 sampleRate)
  34430. {
  34431. /* Prevent a division by zero. */
  34432. if (sampleRate == 0) {
  34433. return 0;
  34434. }
  34435. return bufferSizeInFrames*1000 / sampleRate;
  34436. }
  34437. MA_API ma_uint32 ma_calculate_buffer_size_in_frames_from_milliseconds(ma_uint32 bufferSizeInMilliseconds, ma_uint32 sampleRate)
  34438. {
  34439. /* Prevent a division by zero. */
  34440. if (sampleRate == 0) {
  34441. return 0;
  34442. }
  34443. return bufferSizeInMilliseconds*sampleRate / 1000;
  34444. }
  34445. MA_API void ma_copy_pcm_frames(void* dst, const void* src, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  34446. {
  34447. if (dst == src) {
  34448. return; /* No-op. */
  34449. }
  34450. ma_copy_memory_64(dst, src, frameCount * ma_get_bytes_per_frame(format, channels));
  34451. }
  34452. MA_API void ma_silence_pcm_frames(void* p, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  34453. {
  34454. if (format == ma_format_u8) {
  34455. ma_uint64 sampleCount = frameCount * channels;
  34456. ma_uint64 iSample;
  34457. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34458. ((ma_uint8*)p)[iSample] = 128;
  34459. }
  34460. } else {
  34461. ma_zero_memory_64(p, frameCount * ma_get_bytes_per_frame(format, channels));
  34462. }
  34463. }
  34464. MA_API void* ma_offset_pcm_frames_ptr(void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  34465. {
  34466. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  34467. }
  34468. MA_API const void* ma_offset_pcm_frames_const_ptr(const void* p, ma_uint64 offsetInFrames, ma_format format, ma_uint32 channels)
  34469. {
  34470. return ma_offset_ptr(p, offsetInFrames * ma_get_bytes_per_frame(format, channels));
  34471. }
  34472. MA_API void ma_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count)
  34473. {
  34474. ma_uint64 iSample;
  34475. MA_ASSERT(pDst != NULL);
  34476. MA_ASSERT(pSrc != NULL);
  34477. for (iSample = 0; iSample < count; iSample += 1) {
  34478. pDst[iSample] = ma_clip_u8(pSrc[iSample]);
  34479. }
  34480. }
  34481. MA_API void ma_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count)
  34482. {
  34483. ma_uint64 iSample;
  34484. MA_ASSERT(pDst != NULL);
  34485. MA_ASSERT(pSrc != NULL);
  34486. for (iSample = 0; iSample < count; iSample += 1) {
  34487. pDst[iSample] = ma_clip_s16(pSrc[iSample]);
  34488. }
  34489. }
  34490. MA_API void ma_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count)
  34491. {
  34492. ma_uint64 iSample;
  34493. MA_ASSERT(pDst != NULL);
  34494. MA_ASSERT(pSrc != NULL);
  34495. for (iSample = 0; iSample < count; iSample += 1) {
  34496. ma_int64 s = ma_clip_s24(pSrc[iSample]);
  34497. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  34498. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  34499. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  34500. }
  34501. }
  34502. MA_API void ma_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count)
  34503. {
  34504. ma_uint64 iSample;
  34505. MA_ASSERT(pDst != NULL);
  34506. MA_ASSERT(pSrc != NULL);
  34507. for (iSample = 0; iSample < count; iSample += 1) {
  34508. pDst[iSample] = ma_clip_s32(pSrc[iSample]);
  34509. }
  34510. }
  34511. MA_API void ma_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count)
  34512. {
  34513. ma_uint64 iSample;
  34514. MA_ASSERT(pDst != NULL);
  34515. MA_ASSERT(pSrc != NULL);
  34516. for (iSample = 0; iSample < count; iSample += 1) {
  34517. pDst[iSample] = ma_clip_f32(pSrc[iSample]);
  34518. }
  34519. }
  34520. MA_API void ma_clip_pcm_frames(void* pDst, const void* pSrc, ma_uint64 frameCount, ma_format format, ma_uint32 channels)
  34521. {
  34522. ma_uint64 sampleCount;
  34523. MA_ASSERT(pDst != NULL);
  34524. MA_ASSERT(pSrc != NULL);
  34525. sampleCount = frameCount * channels;
  34526. switch (format) {
  34527. case ma_format_u8: ma_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount); break;
  34528. case ma_format_s16: ma_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount); break;
  34529. case ma_format_s24: ma_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  34530. case ma_format_s32: ma_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount); break;
  34531. case ma_format_f32: ma_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount); break;
  34532. /* 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. */
  34533. case ma_format_unknown:
  34534. case ma_format_count:
  34535. break;
  34536. }
  34537. }
  34538. MA_API void ma_copy_and_apply_volume_factor_u8(ma_uint8* pSamplesOut, const ma_uint8* pSamplesIn, ma_uint64 sampleCount, float factor)
  34539. {
  34540. ma_uint64 iSample;
  34541. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  34542. return;
  34543. }
  34544. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34545. pSamplesOut[iSample] = (ma_uint8)(pSamplesIn[iSample] * factor);
  34546. }
  34547. }
  34548. MA_API void ma_copy_and_apply_volume_factor_s16(ma_int16* pSamplesOut, const ma_int16* pSamplesIn, ma_uint64 sampleCount, float factor)
  34549. {
  34550. ma_uint64 iSample;
  34551. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  34552. return;
  34553. }
  34554. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34555. pSamplesOut[iSample] = (ma_int16)(pSamplesIn[iSample] * factor);
  34556. }
  34557. }
  34558. MA_API void ma_copy_and_apply_volume_factor_s24(void* pSamplesOut, const void* pSamplesIn, ma_uint64 sampleCount, float factor)
  34559. {
  34560. ma_uint64 iSample;
  34561. ma_uint8* pSamplesOut8;
  34562. ma_uint8* pSamplesIn8;
  34563. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  34564. return;
  34565. }
  34566. pSamplesOut8 = (ma_uint8*)pSamplesOut;
  34567. pSamplesIn8 = (ma_uint8*)pSamplesIn;
  34568. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34569. ma_int32 sampleS32;
  34570. sampleS32 = (ma_int32)(((ma_uint32)(pSamplesIn8[iSample*3+0]) << 8) | ((ma_uint32)(pSamplesIn8[iSample*3+1]) << 16) | ((ma_uint32)(pSamplesIn8[iSample*3+2])) << 24);
  34571. sampleS32 = (ma_int32)(sampleS32 * factor);
  34572. pSamplesOut8[iSample*3+0] = (ma_uint8)(((ma_uint32)sampleS32 & 0x0000FF00) >> 8);
  34573. pSamplesOut8[iSample*3+1] = (ma_uint8)(((ma_uint32)sampleS32 & 0x00FF0000) >> 16);
  34574. pSamplesOut8[iSample*3+2] = (ma_uint8)(((ma_uint32)sampleS32 & 0xFF000000) >> 24);
  34575. }
  34576. }
  34577. MA_API void ma_copy_and_apply_volume_factor_s32(ma_int32* pSamplesOut, const ma_int32* pSamplesIn, ma_uint64 sampleCount, float factor)
  34578. {
  34579. ma_uint64 iSample;
  34580. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  34581. return;
  34582. }
  34583. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34584. pSamplesOut[iSample] = (ma_int32)(pSamplesIn[iSample] * factor);
  34585. }
  34586. }
  34587. MA_API void ma_copy_and_apply_volume_factor_f32(float* pSamplesOut, const float* pSamplesIn, ma_uint64 sampleCount, float factor)
  34588. {
  34589. ma_uint64 iSample;
  34590. if (pSamplesOut == NULL || pSamplesIn == NULL) {
  34591. return;
  34592. }
  34593. if (factor == 1) {
  34594. if (pSamplesOut == pSamplesIn) {
  34595. /* In place. No-op. */
  34596. } else {
  34597. /* Just a copy. */
  34598. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34599. pSamplesOut[iSample] = pSamplesIn[iSample];
  34600. }
  34601. }
  34602. } else {
  34603. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  34604. pSamplesOut[iSample] = pSamplesIn[iSample] * factor;
  34605. }
  34606. }
  34607. }
  34608. MA_API void ma_apply_volume_factor_u8(ma_uint8* pSamples, ma_uint64 sampleCount, float factor)
  34609. {
  34610. ma_copy_and_apply_volume_factor_u8(pSamples, pSamples, sampleCount, factor);
  34611. }
  34612. MA_API void ma_apply_volume_factor_s16(ma_int16* pSamples, ma_uint64 sampleCount, float factor)
  34613. {
  34614. ma_copy_and_apply_volume_factor_s16(pSamples, pSamples, sampleCount, factor);
  34615. }
  34616. MA_API void ma_apply_volume_factor_s24(void* pSamples, ma_uint64 sampleCount, float factor)
  34617. {
  34618. ma_copy_and_apply_volume_factor_s24(pSamples, pSamples, sampleCount, factor);
  34619. }
  34620. MA_API void ma_apply_volume_factor_s32(ma_int32* pSamples, ma_uint64 sampleCount, float factor)
  34621. {
  34622. ma_copy_and_apply_volume_factor_s32(pSamples, pSamples, sampleCount, factor);
  34623. }
  34624. MA_API void ma_apply_volume_factor_f32(float* pSamples, ma_uint64 sampleCount, float factor)
  34625. {
  34626. ma_copy_and_apply_volume_factor_f32(pSamples, pSamples, sampleCount, factor);
  34627. }
  34628. 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)
  34629. {
  34630. ma_copy_and_apply_volume_factor_u8(pFramesOut, pFramesIn, frameCount*channels, factor);
  34631. }
  34632. 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)
  34633. {
  34634. ma_copy_and_apply_volume_factor_s16(pFramesOut, pFramesIn, frameCount*channels, factor);
  34635. }
  34636. 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)
  34637. {
  34638. ma_copy_and_apply_volume_factor_s24(pFramesOut, pFramesIn, frameCount*channels, factor);
  34639. }
  34640. 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)
  34641. {
  34642. ma_copy_and_apply_volume_factor_s32(pFramesOut, pFramesIn, frameCount*channels, factor);
  34643. }
  34644. 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)
  34645. {
  34646. ma_copy_and_apply_volume_factor_f32(pFramesOut, pFramesIn, frameCount*channels, factor);
  34647. }
  34648. 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)
  34649. {
  34650. switch (format)
  34651. {
  34652. case ma_format_u8: ma_copy_and_apply_volume_factor_pcm_frames_u8 ((ma_uint8*)pFramesOut, (const ma_uint8*)pFramesIn, frameCount, channels, factor); return;
  34653. case ma_format_s16: ma_copy_and_apply_volume_factor_pcm_frames_s16((ma_int16*)pFramesOut, (const ma_int16*)pFramesIn, frameCount, channels, factor); return;
  34654. case ma_format_s24: ma_copy_and_apply_volume_factor_pcm_frames_s24( pFramesOut, pFramesIn, frameCount, channels, factor); return;
  34655. case ma_format_s32: ma_copy_and_apply_volume_factor_pcm_frames_s32((ma_int32*)pFramesOut, (const ma_int32*)pFramesIn, frameCount, channels, factor); return;
  34656. case ma_format_f32: ma_copy_and_apply_volume_factor_pcm_frames_f32( (float*)pFramesOut, (const float*)pFramesIn, frameCount, channels, factor); return;
  34657. default: return; /* Do nothing. */
  34658. }
  34659. }
  34660. MA_API void ma_apply_volume_factor_pcm_frames_u8(ma_uint8* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  34661. {
  34662. ma_copy_and_apply_volume_factor_pcm_frames_u8(pFrames, pFrames, frameCount, channels, factor);
  34663. }
  34664. MA_API void ma_apply_volume_factor_pcm_frames_s16(ma_int16* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  34665. {
  34666. ma_copy_and_apply_volume_factor_pcm_frames_s16(pFrames, pFrames, frameCount, channels, factor);
  34667. }
  34668. MA_API void ma_apply_volume_factor_pcm_frames_s24(void* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  34669. {
  34670. ma_copy_and_apply_volume_factor_pcm_frames_s24(pFrames, pFrames, frameCount, channels, factor);
  34671. }
  34672. MA_API void ma_apply_volume_factor_pcm_frames_s32(ma_int32* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  34673. {
  34674. ma_copy_and_apply_volume_factor_pcm_frames_s32(pFrames, pFrames, frameCount, channels, factor);
  34675. }
  34676. MA_API void ma_apply_volume_factor_pcm_frames_f32(float* pFrames, ma_uint64 frameCount, ma_uint32 channels, float factor)
  34677. {
  34678. ma_copy_and_apply_volume_factor_pcm_frames_f32(pFrames, pFrames, frameCount, channels, factor);
  34679. }
  34680. MA_API void ma_apply_volume_factor_pcm_frames(void* pFramesOut, ma_uint64 frameCount, ma_format format, ma_uint32 channels, float factor)
  34681. {
  34682. ma_copy_and_apply_volume_factor_pcm_frames(pFramesOut, pFramesOut, frameCount, format, channels, factor);
  34683. }
  34684. 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)
  34685. {
  34686. ma_uint64 iFrame;
  34687. if (channels == 2) {
  34688. /* TODO: Do an optimized implementation for stereo and mono. Can do a SIMD optimized implementation as well. */
  34689. }
  34690. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  34691. ma_uint32 iChannel;
  34692. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  34693. pFramesOut[iFrame * channels + iChannel] = pFramesIn[iFrame * channels + iChannel] * pChannelGains[iChannel];
  34694. }
  34695. }
  34696. }
  34697. static MA_INLINE ma_int16 ma_apply_volume_unclipped_u8(ma_int16 x, ma_int16 volume)
  34698. {
  34699. return (ma_int16)(((ma_int32)x * (ma_int32)volume) >> 8);
  34700. }
  34701. static MA_INLINE ma_int32 ma_apply_volume_unclipped_s16(ma_int32 x, ma_int16 volume)
  34702. {
  34703. return (ma_int32)((x * volume) >> 8);
  34704. }
  34705. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s24(ma_int64 x, ma_int16 volume)
  34706. {
  34707. return (ma_int64)((x * volume) >> 8);
  34708. }
  34709. static MA_INLINE ma_int64 ma_apply_volume_unclipped_s32(ma_int64 x, ma_int16 volume)
  34710. {
  34711. return (ma_int64)((x * volume) >> 8);
  34712. }
  34713. static MA_INLINE float ma_apply_volume_unclipped_f32(float x, float volume)
  34714. {
  34715. return x * volume;
  34716. }
  34717. MA_API void ma_copy_and_apply_volume_and_clip_samples_u8(ma_uint8* pDst, const ma_int16* pSrc, ma_uint64 count, float volume)
  34718. {
  34719. ma_uint64 iSample;
  34720. ma_int16 volumeFixed;
  34721. MA_ASSERT(pDst != NULL);
  34722. MA_ASSERT(pSrc != NULL);
  34723. volumeFixed = ma_float_to_fixed_16(volume);
  34724. for (iSample = 0; iSample < count; iSample += 1) {
  34725. pDst[iSample] = ma_clip_u8(ma_apply_volume_unclipped_u8(pSrc[iSample], volumeFixed));
  34726. }
  34727. }
  34728. MA_API void ma_copy_and_apply_volume_and_clip_samples_s16(ma_int16* pDst, const ma_int32* pSrc, ma_uint64 count, float volume)
  34729. {
  34730. ma_uint64 iSample;
  34731. ma_int16 volumeFixed;
  34732. MA_ASSERT(pDst != NULL);
  34733. MA_ASSERT(pSrc != NULL);
  34734. volumeFixed = ma_float_to_fixed_16(volume);
  34735. for (iSample = 0; iSample < count; iSample += 1) {
  34736. pDst[iSample] = ma_clip_s16(ma_apply_volume_unclipped_s16(pSrc[iSample], volumeFixed));
  34737. }
  34738. }
  34739. MA_API void ma_copy_and_apply_volume_and_clip_samples_s24(ma_uint8* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  34740. {
  34741. ma_uint64 iSample;
  34742. ma_int16 volumeFixed;
  34743. MA_ASSERT(pDst != NULL);
  34744. MA_ASSERT(pSrc != NULL);
  34745. volumeFixed = ma_float_to_fixed_16(volume);
  34746. for (iSample = 0; iSample < count; iSample += 1) {
  34747. ma_int64 s = ma_clip_s24(ma_apply_volume_unclipped_s24(pSrc[iSample], volumeFixed));
  34748. pDst[iSample*3 + 0] = (ma_uint8)((s & 0x000000FF) >> 0);
  34749. pDst[iSample*3 + 1] = (ma_uint8)((s & 0x0000FF00) >> 8);
  34750. pDst[iSample*3 + 2] = (ma_uint8)((s & 0x00FF0000) >> 16);
  34751. }
  34752. }
  34753. MA_API void ma_copy_and_apply_volume_and_clip_samples_s32(ma_int32* pDst, const ma_int64* pSrc, ma_uint64 count, float volume)
  34754. {
  34755. ma_uint64 iSample;
  34756. ma_int16 volumeFixed;
  34757. MA_ASSERT(pDst != NULL);
  34758. MA_ASSERT(pSrc != NULL);
  34759. volumeFixed = ma_float_to_fixed_16(volume);
  34760. for (iSample = 0; iSample < count; iSample += 1) {
  34761. pDst[iSample] = ma_clip_s32(ma_apply_volume_unclipped_s32(pSrc[iSample], volumeFixed));
  34762. }
  34763. }
  34764. MA_API void ma_copy_and_apply_volume_and_clip_samples_f32(float* pDst, const float* pSrc, ma_uint64 count, float volume)
  34765. {
  34766. ma_uint64 iSample;
  34767. MA_ASSERT(pDst != NULL);
  34768. MA_ASSERT(pSrc != NULL);
  34769. /* For the f32 case we need to make sure this supports in-place processing where the input and output buffers are the same. */
  34770. for (iSample = 0; iSample < count; iSample += 1) {
  34771. pDst[iSample] = ma_clip_f32(ma_apply_volume_unclipped_f32(pSrc[iSample], volume));
  34772. }
  34773. }
  34774. 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)
  34775. {
  34776. MA_ASSERT(pDst != NULL);
  34777. MA_ASSERT(pSrc != NULL);
  34778. if (volume == 1) {
  34779. ma_clip_pcm_frames(pDst, pSrc, frameCount, format, channels); /* Optimized case for volume = 1. */
  34780. } else if (volume == 0) {
  34781. ma_silence_pcm_frames(pDst, frameCount, format, channels); /* Optimized case for volume = 0. */
  34782. } else {
  34783. ma_uint64 sampleCount = frameCount * channels;
  34784. switch (format) {
  34785. case ma_format_u8: ma_copy_and_apply_volume_and_clip_samples_u8( (ma_uint8*)pDst, (const ma_int16*)pSrc, sampleCount, volume); break;
  34786. case ma_format_s16: ma_copy_and_apply_volume_and_clip_samples_s16((ma_int16*)pDst, (const ma_int32*)pSrc, sampleCount, volume); break;
  34787. case ma_format_s24: ma_copy_and_apply_volume_and_clip_samples_s24((ma_uint8*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  34788. case ma_format_s32: ma_copy_and_apply_volume_and_clip_samples_s32((ma_int32*)pDst, (const ma_int64*)pSrc, sampleCount, volume); break;
  34789. case ma_format_f32: ma_copy_and_apply_volume_and_clip_samples_f32(( float*)pDst, (const float*)pSrc, sampleCount, volume); break;
  34790. /* 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. */
  34791. case ma_format_unknown:
  34792. case ma_format_count:
  34793. break;
  34794. }
  34795. }
  34796. }
  34797. MA_API float ma_volume_linear_to_db(float factor)
  34798. {
  34799. return 20*ma_log10f(factor);
  34800. }
  34801. MA_API float ma_volume_db_to_linear(float gain)
  34802. {
  34803. return ma_powf(10, gain/20.0f);
  34804. }
  34805. /**************************************************************************************************************************************************************
  34806. Format Conversion
  34807. **************************************************************************************************************************************************************/
  34808. static MA_INLINE ma_int16 ma_pcm_sample_f32_to_s16(float x)
  34809. {
  34810. return (ma_int16)(x * 32767.0f);
  34811. }
  34812. static MA_INLINE ma_int16 ma_pcm_sample_u8_to_s16_no_scale(ma_uint8 x)
  34813. {
  34814. return (ma_int16)((ma_int16)x - 128);
  34815. }
  34816. static MA_INLINE ma_int64 ma_pcm_sample_s24_to_s32_no_scale(const ma_uint8* x)
  34817. {
  34818. 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. */
  34819. }
  34820. static MA_INLINE void ma_pcm_sample_s32_to_s24_no_scale(ma_int64 x, ma_uint8* s24)
  34821. {
  34822. s24[0] = (ma_uint8)((x & 0x000000FF) >> 0);
  34823. s24[1] = (ma_uint8)((x & 0x0000FF00) >> 8);
  34824. s24[2] = (ma_uint8)((x & 0x00FF0000) >> 16);
  34825. }
  34826. /* u8 */
  34827. MA_API void ma_pcm_u8_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34828. {
  34829. (void)ditherMode;
  34830. ma_copy_memory_64(dst, src, count * sizeof(ma_uint8));
  34831. }
  34832. static MA_INLINE void ma_pcm_u8_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34833. {
  34834. ma_int16* dst_s16 = (ma_int16*)dst;
  34835. const ma_uint8* src_u8 = (const ma_uint8*)src;
  34836. ma_uint64 i;
  34837. for (i = 0; i < count; i += 1) {
  34838. ma_int16 x = src_u8[i];
  34839. x = (ma_int16)(x - 128);
  34840. x = (ma_int16)(x << 8);
  34841. dst_s16[i] = x;
  34842. }
  34843. (void)ditherMode;
  34844. }
  34845. static MA_INLINE void ma_pcm_u8_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34846. {
  34847. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  34848. }
  34849. #if defined(MA_SUPPORT_SSE2)
  34850. static MA_INLINE void ma_pcm_u8_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34851. {
  34852. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  34853. }
  34854. #endif
  34855. #if defined(MA_SUPPORT_AVX2)
  34856. static MA_INLINE void ma_pcm_u8_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34857. {
  34858. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  34859. }
  34860. #endif
  34861. #if defined(MA_SUPPORT_NEON)
  34862. static MA_INLINE void ma_pcm_u8_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34863. {
  34864. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  34865. }
  34866. #endif
  34867. MA_API void ma_pcm_u8_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34868. {
  34869. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  34870. ma_pcm_u8_to_s16__reference(dst, src, count, ditherMode);
  34871. #else
  34872. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  34873. if (ma_has_avx2()) {
  34874. ma_pcm_u8_to_s16__avx2(dst, src, count, ditherMode);
  34875. } else
  34876. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  34877. if (ma_has_sse2()) {
  34878. ma_pcm_u8_to_s16__sse2(dst, src, count, ditherMode);
  34879. } else
  34880. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  34881. if (ma_has_neon()) {
  34882. ma_pcm_u8_to_s16__neon(dst, src, count, ditherMode);
  34883. } else
  34884. #endif
  34885. {
  34886. ma_pcm_u8_to_s16__optimized(dst, src, count, ditherMode);
  34887. }
  34888. #endif
  34889. }
  34890. static MA_INLINE void ma_pcm_u8_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34891. {
  34892. ma_uint8* dst_s24 = (ma_uint8*)dst;
  34893. const ma_uint8* src_u8 = (const ma_uint8*)src;
  34894. ma_uint64 i;
  34895. for (i = 0; i < count; i += 1) {
  34896. ma_int16 x = src_u8[i];
  34897. x = (ma_int16)(x - 128);
  34898. dst_s24[i*3+0] = 0;
  34899. dst_s24[i*3+1] = 0;
  34900. dst_s24[i*3+2] = (ma_uint8)((ma_int8)x);
  34901. }
  34902. (void)ditherMode;
  34903. }
  34904. static MA_INLINE void ma_pcm_u8_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34905. {
  34906. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  34907. }
  34908. #if defined(MA_SUPPORT_SSE2)
  34909. static MA_INLINE void ma_pcm_u8_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34910. {
  34911. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  34912. }
  34913. #endif
  34914. #if defined(MA_SUPPORT_AVX2)
  34915. static MA_INLINE void ma_pcm_u8_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34916. {
  34917. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  34918. }
  34919. #endif
  34920. #if defined(MA_SUPPORT_NEON)
  34921. static MA_INLINE void ma_pcm_u8_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34922. {
  34923. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  34924. }
  34925. #endif
  34926. MA_API void ma_pcm_u8_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34927. {
  34928. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  34929. ma_pcm_u8_to_s24__reference(dst, src, count, ditherMode);
  34930. #else
  34931. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  34932. if (ma_has_avx2()) {
  34933. ma_pcm_u8_to_s24__avx2(dst, src, count, ditherMode);
  34934. } else
  34935. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  34936. if (ma_has_sse2()) {
  34937. ma_pcm_u8_to_s24__sse2(dst, src, count, ditherMode);
  34938. } else
  34939. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  34940. if (ma_has_neon()) {
  34941. ma_pcm_u8_to_s24__neon(dst, src, count, ditherMode);
  34942. } else
  34943. #endif
  34944. {
  34945. ma_pcm_u8_to_s24__optimized(dst, src, count, ditherMode);
  34946. }
  34947. #endif
  34948. }
  34949. static MA_INLINE void ma_pcm_u8_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34950. {
  34951. ma_int32* dst_s32 = (ma_int32*)dst;
  34952. const ma_uint8* src_u8 = (const ma_uint8*)src;
  34953. ma_uint64 i;
  34954. for (i = 0; i < count; i += 1) {
  34955. ma_int32 x = src_u8[i];
  34956. x = x - 128;
  34957. x = x << 24;
  34958. dst_s32[i] = x;
  34959. }
  34960. (void)ditherMode;
  34961. }
  34962. static MA_INLINE void ma_pcm_u8_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34963. {
  34964. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  34965. }
  34966. #if defined(MA_SUPPORT_SSE2)
  34967. static MA_INLINE void ma_pcm_u8_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34968. {
  34969. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  34970. }
  34971. #endif
  34972. #if defined(MA_SUPPORT_AVX2)
  34973. static MA_INLINE void ma_pcm_u8_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34974. {
  34975. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  34976. }
  34977. #endif
  34978. #if defined(MA_SUPPORT_NEON)
  34979. static MA_INLINE void ma_pcm_u8_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34980. {
  34981. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  34982. }
  34983. #endif
  34984. MA_API void ma_pcm_u8_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  34985. {
  34986. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  34987. ma_pcm_u8_to_s32__reference(dst, src, count, ditherMode);
  34988. #else
  34989. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  34990. if (ma_has_avx2()) {
  34991. ma_pcm_u8_to_s32__avx2(dst, src, count, ditherMode);
  34992. } else
  34993. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  34994. if (ma_has_sse2()) {
  34995. ma_pcm_u8_to_s32__sse2(dst, src, count, ditherMode);
  34996. } else
  34997. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  34998. if (ma_has_neon()) {
  34999. ma_pcm_u8_to_s32__neon(dst, src, count, ditherMode);
  35000. } else
  35001. #endif
  35002. {
  35003. ma_pcm_u8_to_s32__optimized(dst, src, count, ditherMode);
  35004. }
  35005. #endif
  35006. }
  35007. static MA_INLINE void ma_pcm_u8_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35008. {
  35009. float* dst_f32 = (float*)dst;
  35010. const ma_uint8* src_u8 = (const ma_uint8*)src;
  35011. ma_uint64 i;
  35012. for (i = 0; i < count; i += 1) {
  35013. float x = (float)src_u8[i];
  35014. x = x * 0.00784313725490196078f; /* 0..255 to 0..2 */
  35015. x = x - 1; /* 0..2 to -1..1 */
  35016. dst_f32[i] = x;
  35017. }
  35018. (void)ditherMode;
  35019. }
  35020. static MA_INLINE void ma_pcm_u8_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35021. {
  35022. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  35023. }
  35024. #if defined(MA_SUPPORT_SSE2)
  35025. static MA_INLINE void ma_pcm_u8_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35026. {
  35027. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  35028. }
  35029. #endif
  35030. #if defined(MA_SUPPORT_AVX2)
  35031. static MA_INLINE void ma_pcm_u8_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35032. {
  35033. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  35034. }
  35035. #endif
  35036. #if defined(MA_SUPPORT_NEON)
  35037. static MA_INLINE void ma_pcm_u8_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35038. {
  35039. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  35040. }
  35041. #endif
  35042. MA_API void ma_pcm_u8_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35043. {
  35044. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35045. ma_pcm_u8_to_f32__reference(dst, src, count, ditherMode);
  35046. #else
  35047. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35048. if (ma_has_avx2()) {
  35049. ma_pcm_u8_to_f32__avx2(dst, src, count, ditherMode);
  35050. } else
  35051. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35052. if (ma_has_sse2()) {
  35053. ma_pcm_u8_to_f32__sse2(dst, src, count, ditherMode);
  35054. } else
  35055. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35056. if (ma_has_neon()) {
  35057. ma_pcm_u8_to_f32__neon(dst, src, count, ditherMode);
  35058. } else
  35059. #endif
  35060. {
  35061. ma_pcm_u8_to_f32__optimized(dst, src, count, ditherMode);
  35062. }
  35063. #endif
  35064. }
  35065. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35066. static MA_INLINE void ma_pcm_interleave_u8__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35067. {
  35068. ma_uint8* dst_u8 = (ma_uint8*)dst;
  35069. const ma_uint8** src_u8 = (const ma_uint8**)src;
  35070. ma_uint64 iFrame;
  35071. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35072. ma_uint32 iChannel;
  35073. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35074. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  35075. }
  35076. }
  35077. }
  35078. #else
  35079. static MA_INLINE void ma_pcm_interleave_u8__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35080. {
  35081. ma_uint8* dst_u8 = (ma_uint8*)dst;
  35082. const ma_uint8** src_u8 = (const ma_uint8**)src;
  35083. if (channels == 1) {
  35084. ma_copy_memory_64(dst, src[0], frameCount * sizeof(ma_uint8));
  35085. } else if (channels == 2) {
  35086. ma_uint64 iFrame;
  35087. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35088. dst_u8[iFrame*2 + 0] = src_u8[0][iFrame];
  35089. dst_u8[iFrame*2 + 1] = src_u8[1][iFrame];
  35090. }
  35091. } else {
  35092. ma_uint64 iFrame;
  35093. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35094. ma_uint32 iChannel;
  35095. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35096. dst_u8[iFrame*channels + iChannel] = src_u8[iChannel][iFrame];
  35097. }
  35098. }
  35099. }
  35100. }
  35101. #endif
  35102. MA_API void ma_pcm_interleave_u8(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35103. {
  35104. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35105. ma_pcm_interleave_u8__reference(dst, src, frameCount, channels);
  35106. #else
  35107. ma_pcm_interleave_u8__optimized(dst, src, frameCount, channels);
  35108. #endif
  35109. }
  35110. static MA_INLINE void ma_pcm_deinterleave_u8__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35111. {
  35112. ma_uint8** dst_u8 = (ma_uint8**)dst;
  35113. const ma_uint8* src_u8 = (const ma_uint8*)src;
  35114. ma_uint64 iFrame;
  35115. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35116. ma_uint32 iChannel;
  35117. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35118. dst_u8[iChannel][iFrame] = src_u8[iFrame*channels + iChannel];
  35119. }
  35120. }
  35121. }
  35122. static MA_INLINE void ma_pcm_deinterleave_u8__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35123. {
  35124. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  35125. }
  35126. MA_API void ma_pcm_deinterleave_u8(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35127. {
  35128. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35129. ma_pcm_deinterleave_u8__reference(dst, src, frameCount, channels);
  35130. #else
  35131. ma_pcm_deinterleave_u8__optimized(dst, src, frameCount, channels);
  35132. #endif
  35133. }
  35134. /* s16 */
  35135. static MA_INLINE void ma_pcm_s16_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35136. {
  35137. ma_uint8* dst_u8 = (ma_uint8*)dst;
  35138. const ma_int16* src_s16 = (const ma_int16*)src;
  35139. if (ditherMode == ma_dither_mode_none) {
  35140. ma_uint64 i;
  35141. for (i = 0; i < count; i += 1) {
  35142. ma_int16 x = src_s16[i];
  35143. x = (ma_int16)(x >> 8);
  35144. x = (ma_int16)(x + 128);
  35145. dst_u8[i] = (ma_uint8)x;
  35146. }
  35147. } else {
  35148. ma_uint64 i;
  35149. for (i = 0; i < count; i += 1) {
  35150. ma_int16 x = src_s16[i];
  35151. /* Dither. Don't overflow. */
  35152. ma_int32 dither = ma_dither_s32(ditherMode, -0x80, 0x7F);
  35153. if ((x + dither) <= 0x7FFF) {
  35154. x = (ma_int16)(x + dither);
  35155. } else {
  35156. x = 0x7FFF;
  35157. }
  35158. x = (ma_int16)(x >> 8);
  35159. x = (ma_int16)(x + 128);
  35160. dst_u8[i] = (ma_uint8)x;
  35161. }
  35162. }
  35163. }
  35164. static MA_INLINE void ma_pcm_s16_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35165. {
  35166. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  35167. }
  35168. #if defined(MA_SUPPORT_SSE2)
  35169. static MA_INLINE void ma_pcm_s16_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35170. {
  35171. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  35172. }
  35173. #endif
  35174. #if defined(MA_SUPPORT_AVX2)
  35175. static MA_INLINE void ma_pcm_s16_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35176. {
  35177. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  35178. }
  35179. #endif
  35180. #if defined(MA_SUPPORT_NEON)
  35181. static MA_INLINE void ma_pcm_s16_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35182. {
  35183. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  35184. }
  35185. #endif
  35186. MA_API void ma_pcm_s16_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35187. {
  35188. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35189. ma_pcm_s16_to_u8__reference(dst, src, count, ditherMode);
  35190. #else
  35191. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35192. if (ma_has_avx2()) {
  35193. ma_pcm_s16_to_u8__avx2(dst, src, count, ditherMode);
  35194. } else
  35195. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35196. if (ma_has_sse2()) {
  35197. ma_pcm_s16_to_u8__sse2(dst, src, count, ditherMode);
  35198. } else
  35199. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35200. if (ma_has_neon()) {
  35201. ma_pcm_s16_to_u8__neon(dst, src, count, ditherMode);
  35202. } else
  35203. #endif
  35204. {
  35205. ma_pcm_s16_to_u8__optimized(dst, src, count, ditherMode);
  35206. }
  35207. #endif
  35208. }
  35209. MA_API void ma_pcm_s16_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35210. {
  35211. (void)ditherMode;
  35212. ma_copy_memory_64(dst, src, count * sizeof(ma_int16));
  35213. }
  35214. static MA_INLINE void ma_pcm_s16_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35215. {
  35216. ma_uint8* dst_s24 = (ma_uint8*)dst;
  35217. const ma_int16* src_s16 = (const ma_int16*)src;
  35218. ma_uint64 i;
  35219. for (i = 0; i < count; i += 1) {
  35220. dst_s24[i*3+0] = 0;
  35221. dst_s24[i*3+1] = (ma_uint8)(src_s16[i] & 0xFF);
  35222. dst_s24[i*3+2] = (ma_uint8)(src_s16[i] >> 8);
  35223. }
  35224. (void)ditherMode;
  35225. }
  35226. static MA_INLINE void ma_pcm_s16_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35227. {
  35228. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  35229. }
  35230. #if defined(MA_SUPPORT_SSE2)
  35231. static MA_INLINE void ma_pcm_s16_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35232. {
  35233. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  35234. }
  35235. #endif
  35236. #if defined(MA_SUPPORT_AVX2)
  35237. static MA_INLINE void ma_pcm_s16_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35238. {
  35239. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  35240. }
  35241. #endif
  35242. #if defined(MA_SUPPORT_NEON)
  35243. static MA_INLINE void ma_pcm_s16_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35244. {
  35245. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  35246. }
  35247. #endif
  35248. MA_API void ma_pcm_s16_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35249. {
  35250. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35251. ma_pcm_s16_to_s24__reference(dst, src, count, ditherMode);
  35252. #else
  35253. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35254. if (ma_has_avx2()) {
  35255. ma_pcm_s16_to_s24__avx2(dst, src, count, ditherMode);
  35256. } else
  35257. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35258. if (ma_has_sse2()) {
  35259. ma_pcm_s16_to_s24__sse2(dst, src, count, ditherMode);
  35260. } else
  35261. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35262. if (ma_has_neon()) {
  35263. ma_pcm_s16_to_s24__neon(dst, src, count, ditherMode);
  35264. } else
  35265. #endif
  35266. {
  35267. ma_pcm_s16_to_s24__optimized(dst, src, count, ditherMode);
  35268. }
  35269. #endif
  35270. }
  35271. static MA_INLINE void ma_pcm_s16_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35272. {
  35273. ma_int32* dst_s32 = (ma_int32*)dst;
  35274. const ma_int16* src_s16 = (const ma_int16*)src;
  35275. ma_uint64 i;
  35276. for (i = 0; i < count; i += 1) {
  35277. dst_s32[i] = src_s16[i] << 16;
  35278. }
  35279. (void)ditherMode;
  35280. }
  35281. static MA_INLINE void ma_pcm_s16_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35282. {
  35283. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  35284. }
  35285. #if defined(MA_SUPPORT_SSE2)
  35286. static MA_INLINE void ma_pcm_s16_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35287. {
  35288. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  35289. }
  35290. #endif
  35291. #if defined(MA_SUPPORT_AVX2)
  35292. static MA_INLINE void ma_pcm_s16_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35293. {
  35294. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  35295. }
  35296. #endif
  35297. #if defined(MA_SUPPORT_NEON)
  35298. static MA_INLINE void ma_pcm_s16_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35299. {
  35300. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  35301. }
  35302. #endif
  35303. MA_API void ma_pcm_s16_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35304. {
  35305. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35306. ma_pcm_s16_to_s32__reference(dst, src, count, ditherMode);
  35307. #else
  35308. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35309. if (ma_has_avx2()) {
  35310. ma_pcm_s16_to_s32__avx2(dst, src, count, ditherMode);
  35311. } else
  35312. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35313. if (ma_has_sse2()) {
  35314. ma_pcm_s16_to_s32__sse2(dst, src, count, ditherMode);
  35315. } else
  35316. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35317. if (ma_has_neon()) {
  35318. ma_pcm_s16_to_s32__neon(dst, src, count, ditherMode);
  35319. } else
  35320. #endif
  35321. {
  35322. ma_pcm_s16_to_s32__optimized(dst, src, count, ditherMode);
  35323. }
  35324. #endif
  35325. }
  35326. static MA_INLINE void ma_pcm_s16_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35327. {
  35328. float* dst_f32 = (float*)dst;
  35329. const ma_int16* src_s16 = (const ma_int16*)src;
  35330. ma_uint64 i;
  35331. for (i = 0; i < count; i += 1) {
  35332. float x = (float)src_s16[i];
  35333. #if 0
  35334. /* The accurate way. */
  35335. x = x + 32768.0f; /* -32768..32767 to 0..65535 */
  35336. x = x * 0.00003051804379339284f; /* 0..65535 to 0..2 */
  35337. x = x - 1; /* 0..2 to -1..1 */
  35338. #else
  35339. /* The fast way. */
  35340. x = x * 0.000030517578125f; /* -32768..32767 to -1..0.999969482421875 */
  35341. #endif
  35342. dst_f32[i] = x;
  35343. }
  35344. (void)ditherMode;
  35345. }
  35346. static MA_INLINE void ma_pcm_s16_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35347. {
  35348. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  35349. }
  35350. #if defined(MA_SUPPORT_SSE2)
  35351. static MA_INLINE void ma_pcm_s16_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35352. {
  35353. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  35354. }
  35355. #endif
  35356. #if defined(MA_SUPPORT_AVX2)
  35357. static MA_INLINE void ma_pcm_s16_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35358. {
  35359. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  35360. }
  35361. #endif
  35362. #if defined(MA_SUPPORT_NEON)
  35363. static MA_INLINE void ma_pcm_s16_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35364. {
  35365. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  35366. }
  35367. #endif
  35368. MA_API void ma_pcm_s16_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35369. {
  35370. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35371. ma_pcm_s16_to_f32__reference(dst, src, count, ditherMode);
  35372. #else
  35373. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35374. if (ma_has_avx2()) {
  35375. ma_pcm_s16_to_f32__avx2(dst, src, count, ditherMode);
  35376. } else
  35377. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35378. if (ma_has_sse2()) {
  35379. ma_pcm_s16_to_f32__sse2(dst, src, count, ditherMode);
  35380. } else
  35381. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35382. if (ma_has_neon()) {
  35383. ma_pcm_s16_to_f32__neon(dst, src, count, ditherMode);
  35384. } else
  35385. #endif
  35386. {
  35387. ma_pcm_s16_to_f32__optimized(dst, src, count, ditherMode);
  35388. }
  35389. #endif
  35390. }
  35391. static MA_INLINE void ma_pcm_interleave_s16__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35392. {
  35393. ma_int16* dst_s16 = (ma_int16*)dst;
  35394. const ma_int16** src_s16 = (const ma_int16**)src;
  35395. ma_uint64 iFrame;
  35396. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35397. ma_uint32 iChannel;
  35398. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35399. dst_s16[iFrame*channels + iChannel] = src_s16[iChannel][iFrame];
  35400. }
  35401. }
  35402. }
  35403. static MA_INLINE void ma_pcm_interleave_s16__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35404. {
  35405. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  35406. }
  35407. MA_API void ma_pcm_interleave_s16(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35408. {
  35409. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35410. ma_pcm_interleave_s16__reference(dst, src, frameCount, channels);
  35411. #else
  35412. ma_pcm_interleave_s16__optimized(dst, src, frameCount, channels);
  35413. #endif
  35414. }
  35415. static MA_INLINE void ma_pcm_deinterleave_s16__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35416. {
  35417. ma_int16** dst_s16 = (ma_int16**)dst;
  35418. const ma_int16* src_s16 = (const ma_int16*)src;
  35419. ma_uint64 iFrame;
  35420. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35421. ma_uint32 iChannel;
  35422. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35423. dst_s16[iChannel][iFrame] = src_s16[iFrame*channels + iChannel];
  35424. }
  35425. }
  35426. }
  35427. static MA_INLINE void ma_pcm_deinterleave_s16__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35428. {
  35429. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  35430. }
  35431. MA_API void ma_pcm_deinterleave_s16(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35432. {
  35433. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35434. ma_pcm_deinterleave_s16__reference(dst, src, frameCount, channels);
  35435. #else
  35436. ma_pcm_deinterleave_s16__optimized(dst, src, frameCount, channels);
  35437. #endif
  35438. }
  35439. /* s24 */
  35440. static MA_INLINE void ma_pcm_s24_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35441. {
  35442. ma_uint8* dst_u8 = (ma_uint8*)dst;
  35443. const ma_uint8* src_s24 = (const ma_uint8*)src;
  35444. if (ditherMode == ma_dither_mode_none) {
  35445. ma_uint64 i;
  35446. for (i = 0; i < count; i += 1) {
  35447. dst_u8[i] = (ma_uint8)((ma_int8)src_s24[i*3 + 2] + 128);
  35448. }
  35449. } else {
  35450. ma_uint64 i;
  35451. for (i = 0; i < count; i += 1) {
  35452. 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);
  35453. /* Dither. Don't overflow. */
  35454. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  35455. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  35456. x = x + dither;
  35457. } else {
  35458. x = 0x7FFFFFFF;
  35459. }
  35460. x = x >> 24;
  35461. x = x + 128;
  35462. dst_u8[i] = (ma_uint8)x;
  35463. }
  35464. }
  35465. }
  35466. static MA_INLINE void ma_pcm_s24_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35467. {
  35468. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  35469. }
  35470. #if defined(MA_SUPPORT_SSE2)
  35471. static MA_INLINE void ma_pcm_s24_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35472. {
  35473. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  35474. }
  35475. #endif
  35476. #if defined(MA_SUPPORT_AVX2)
  35477. static MA_INLINE void ma_pcm_s24_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35478. {
  35479. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  35480. }
  35481. #endif
  35482. #if defined(MA_SUPPORT_NEON)
  35483. static MA_INLINE void ma_pcm_s24_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35484. {
  35485. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  35486. }
  35487. #endif
  35488. MA_API void ma_pcm_s24_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35489. {
  35490. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35491. ma_pcm_s24_to_u8__reference(dst, src, count, ditherMode);
  35492. #else
  35493. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35494. if (ma_has_avx2()) {
  35495. ma_pcm_s24_to_u8__avx2(dst, src, count, ditherMode);
  35496. } else
  35497. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35498. if (ma_has_sse2()) {
  35499. ma_pcm_s24_to_u8__sse2(dst, src, count, ditherMode);
  35500. } else
  35501. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35502. if (ma_has_neon()) {
  35503. ma_pcm_s24_to_u8__neon(dst, src, count, ditherMode);
  35504. } else
  35505. #endif
  35506. {
  35507. ma_pcm_s24_to_u8__optimized(dst, src, count, ditherMode);
  35508. }
  35509. #endif
  35510. }
  35511. static MA_INLINE void ma_pcm_s24_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35512. {
  35513. ma_int16* dst_s16 = (ma_int16*)dst;
  35514. const ma_uint8* src_s24 = (const ma_uint8*)src;
  35515. if (ditherMode == ma_dither_mode_none) {
  35516. ma_uint64 i;
  35517. for (i = 0; i < count; i += 1) {
  35518. ma_uint16 dst_lo = ((ma_uint16)src_s24[i*3 + 1]);
  35519. ma_uint16 dst_hi = (ma_uint16)((ma_uint16)src_s24[i*3 + 2] << 8);
  35520. dst_s16[i] = (ma_int16)(dst_lo | dst_hi);
  35521. }
  35522. } else {
  35523. ma_uint64 i;
  35524. for (i = 0; i < count; i += 1) {
  35525. 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);
  35526. /* Dither. Don't overflow. */
  35527. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  35528. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  35529. x = x + dither;
  35530. } else {
  35531. x = 0x7FFFFFFF;
  35532. }
  35533. x = x >> 16;
  35534. dst_s16[i] = (ma_int16)x;
  35535. }
  35536. }
  35537. }
  35538. static MA_INLINE void ma_pcm_s24_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35539. {
  35540. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  35541. }
  35542. #if defined(MA_SUPPORT_SSE2)
  35543. static MA_INLINE void ma_pcm_s24_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35544. {
  35545. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  35546. }
  35547. #endif
  35548. #if defined(MA_SUPPORT_AVX2)
  35549. static MA_INLINE void ma_pcm_s24_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35550. {
  35551. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  35552. }
  35553. #endif
  35554. #if defined(MA_SUPPORT_NEON)
  35555. static MA_INLINE void ma_pcm_s24_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35556. {
  35557. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  35558. }
  35559. #endif
  35560. MA_API void ma_pcm_s24_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35561. {
  35562. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35563. ma_pcm_s24_to_s16__reference(dst, src, count, ditherMode);
  35564. #else
  35565. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35566. if (ma_has_avx2()) {
  35567. ma_pcm_s24_to_s16__avx2(dst, src, count, ditherMode);
  35568. } else
  35569. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35570. if (ma_has_sse2()) {
  35571. ma_pcm_s24_to_s16__sse2(dst, src, count, ditherMode);
  35572. } else
  35573. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35574. if (ma_has_neon()) {
  35575. ma_pcm_s24_to_s16__neon(dst, src, count, ditherMode);
  35576. } else
  35577. #endif
  35578. {
  35579. ma_pcm_s24_to_s16__optimized(dst, src, count, ditherMode);
  35580. }
  35581. #endif
  35582. }
  35583. MA_API void ma_pcm_s24_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35584. {
  35585. (void)ditherMode;
  35586. ma_copy_memory_64(dst, src, count * 3);
  35587. }
  35588. static MA_INLINE void ma_pcm_s24_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35589. {
  35590. ma_int32* dst_s32 = (ma_int32*)dst;
  35591. const ma_uint8* src_s24 = (const ma_uint8*)src;
  35592. ma_uint64 i;
  35593. for (i = 0; i < count; i += 1) {
  35594. 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);
  35595. }
  35596. (void)ditherMode;
  35597. }
  35598. static MA_INLINE void ma_pcm_s24_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35599. {
  35600. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  35601. }
  35602. #if defined(MA_SUPPORT_SSE2)
  35603. static MA_INLINE void ma_pcm_s24_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35604. {
  35605. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  35606. }
  35607. #endif
  35608. #if defined(MA_SUPPORT_AVX2)
  35609. static MA_INLINE void ma_pcm_s24_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35610. {
  35611. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  35612. }
  35613. #endif
  35614. #if defined(MA_SUPPORT_NEON)
  35615. static MA_INLINE void ma_pcm_s24_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35616. {
  35617. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  35618. }
  35619. #endif
  35620. MA_API void ma_pcm_s24_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35621. {
  35622. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35623. ma_pcm_s24_to_s32__reference(dst, src, count, ditherMode);
  35624. #else
  35625. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35626. if (ma_has_avx2()) {
  35627. ma_pcm_s24_to_s32__avx2(dst, src, count, ditherMode);
  35628. } else
  35629. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35630. if (ma_has_sse2()) {
  35631. ma_pcm_s24_to_s32__sse2(dst, src, count, ditherMode);
  35632. } else
  35633. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35634. if (ma_has_neon()) {
  35635. ma_pcm_s24_to_s32__neon(dst, src, count, ditherMode);
  35636. } else
  35637. #endif
  35638. {
  35639. ma_pcm_s24_to_s32__optimized(dst, src, count, ditherMode);
  35640. }
  35641. #endif
  35642. }
  35643. static MA_INLINE void ma_pcm_s24_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35644. {
  35645. float* dst_f32 = (float*)dst;
  35646. const ma_uint8* src_s24 = (const ma_uint8*)src;
  35647. ma_uint64 i;
  35648. for (i = 0; i < count; i += 1) {
  35649. 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);
  35650. #if 0
  35651. /* The accurate way. */
  35652. x = x + 8388608.0f; /* -8388608..8388607 to 0..16777215 */
  35653. x = x * 0.00000011920929665621f; /* 0..16777215 to 0..2 */
  35654. x = x - 1; /* 0..2 to -1..1 */
  35655. #else
  35656. /* The fast way. */
  35657. x = x * 0.00000011920928955078125f; /* -8388608..8388607 to -1..0.999969482421875 */
  35658. #endif
  35659. dst_f32[i] = x;
  35660. }
  35661. (void)ditherMode;
  35662. }
  35663. static MA_INLINE void ma_pcm_s24_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35664. {
  35665. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  35666. }
  35667. #if defined(MA_SUPPORT_SSE2)
  35668. static MA_INLINE void ma_pcm_s24_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35669. {
  35670. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  35671. }
  35672. #endif
  35673. #if defined(MA_SUPPORT_AVX2)
  35674. static MA_INLINE void ma_pcm_s24_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35675. {
  35676. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  35677. }
  35678. #endif
  35679. #if defined(MA_SUPPORT_NEON)
  35680. static MA_INLINE void ma_pcm_s24_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35681. {
  35682. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  35683. }
  35684. #endif
  35685. MA_API void ma_pcm_s24_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35686. {
  35687. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35688. ma_pcm_s24_to_f32__reference(dst, src, count, ditherMode);
  35689. #else
  35690. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35691. if (ma_has_avx2()) {
  35692. ma_pcm_s24_to_f32__avx2(dst, src, count, ditherMode);
  35693. } else
  35694. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35695. if (ma_has_sse2()) {
  35696. ma_pcm_s24_to_f32__sse2(dst, src, count, ditherMode);
  35697. } else
  35698. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35699. if (ma_has_neon()) {
  35700. ma_pcm_s24_to_f32__neon(dst, src, count, ditherMode);
  35701. } else
  35702. #endif
  35703. {
  35704. ma_pcm_s24_to_f32__optimized(dst, src, count, ditherMode);
  35705. }
  35706. #endif
  35707. }
  35708. static MA_INLINE void ma_pcm_interleave_s24__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35709. {
  35710. ma_uint8* dst8 = (ma_uint8*)dst;
  35711. const ma_uint8** src8 = (const ma_uint8**)src;
  35712. ma_uint64 iFrame;
  35713. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35714. ma_uint32 iChannel;
  35715. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35716. dst8[iFrame*3*channels + iChannel*3 + 0] = src8[iChannel][iFrame*3 + 0];
  35717. dst8[iFrame*3*channels + iChannel*3 + 1] = src8[iChannel][iFrame*3 + 1];
  35718. dst8[iFrame*3*channels + iChannel*3 + 2] = src8[iChannel][iFrame*3 + 2];
  35719. }
  35720. }
  35721. }
  35722. static MA_INLINE void ma_pcm_interleave_s24__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35723. {
  35724. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  35725. }
  35726. MA_API void ma_pcm_interleave_s24(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  35727. {
  35728. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35729. ma_pcm_interleave_s24__reference(dst, src, frameCount, channels);
  35730. #else
  35731. ma_pcm_interleave_s24__optimized(dst, src, frameCount, channels);
  35732. #endif
  35733. }
  35734. static MA_INLINE void ma_pcm_deinterleave_s24__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35735. {
  35736. ma_uint8** dst8 = (ma_uint8**)dst;
  35737. const ma_uint8* src8 = (const ma_uint8*)src;
  35738. ma_uint32 iFrame;
  35739. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  35740. ma_uint32 iChannel;
  35741. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  35742. dst8[iChannel][iFrame*3 + 0] = src8[iFrame*3*channels + iChannel*3 + 0];
  35743. dst8[iChannel][iFrame*3 + 1] = src8[iFrame*3*channels + iChannel*3 + 1];
  35744. dst8[iChannel][iFrame*3 + 2] = src8[iFrame*3*channels + iChannel*3 + 2];
  35745. }
  35746. }
  35747. }
  35748. static MA_INLINE void ma_pcm_deinterleave_s24__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35749. {
  35750. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  35751. }
  35752. MA_API void ma_pcm_deinterleave_s24(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  35753. {
  35754. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35755. ma_pcm_deinterleave_s24__reference(dst, src, frameCount, channels);
  35756. #else
  35757. ma_pcm_deinterleave_s24__optimized(dst, src, frameCount, channels);
  35758. #endif
  35759. }
  35760. /* s32 */
  35761. static MA_INLINE void ma_pcm_s32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35762. {
  35763. ma_uint8* dst_u8 = (ma_uint8*)dst;
  35764. const ma_int32* src_s32 = (const ma_int32*)src;
  35765. if (ditherMode == ma_dither_mode_none) {
  35766. ma_uint64 i;
  35767. for (i = 0; i < count; i += 1) {
  35768. ma_int32 x = src_s32[i];
  35769. x = x >> 24;
  35770. x = x + 128;
  35771. dst_u8[i] = (ma_uint8)x;
  35772. }
  35773. } else {
  35774. ma_uint64 i;
  35775. for (i = 0; i < count; i += 1) {
  35776. ma_int32 x = src_s32[i];
  35777. /* Dither. Don't overflow. */
  35778. ma_int32 dither = ma_dither_s32(ditherMode, -0x800000, 0x7FFFFF);
  35779. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  35780. x = x + dither;
  35781. } else {
  35782. x = 0x7FFFFFFF;
  35783. }
  35784. x = x >> 24;
  35785. x = x + 128;
  35786. dst_u8[i] = (ma_uint8)x;
  35787. }
  35788. }
  35789. }
  35790. static MA_INLINE void ma_pcm_s32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35791. {
  35792. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  35793. }
  35794. #if defined(MA_SUPPORT_SSE2)
  35795. static MA_INLINE void ma_pcm_s32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35796. {
  35797. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  35798. }
  35799. #endif
  35800. #if defined(MA_SUPPORT_AVX2)
  35801. static MA_INLINE void ma_pcm_s32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35802. {
  35803. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  35804. }
  35805. #endif
  35806. #if defined(MA_SUPPORT_NEON)
  35807. static MA_INLINE void ma_pcm_s32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35808. {
  35809. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  35810. }
  35811. #endif
  35812. MA_API void ma_pcm_s32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35813. {
  35814. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35815. ma_pcm_s32_to_u8__reference(dst, src, count, ditherMode);
  35816. #else
  35817. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35818. if (ma_has_avx2()) {
  35819. ma_pcm_s32_to_u8__avx2(dst, src, count, ditherMode);
  35820. } else
  35821. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35822. if (ma_has_sse2()) {
  35823. ma_pcm_s32_to_u8__sse2(dst, src, count, ditherMode);
  35824. } else
  35825. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35826. if (ma_has_neon()) {
  35827. ma_pcm_s32_to_u8__neon(dst, src, count, ditherMode);
  35828. } else
  35829. #endif
  35830. {
  35831. ma_pcm_s32_to_u8__optimized(dst, src, count, ditherMode);
  35832. }
  35833. #endif
  35834. }
  35835. static MA_INLINE void ma_pcm_s32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35836. {
  35837. ma_int16* dst_s16 = (ma_int16*)dst;
  35838. const ma_int32* src_s32 = (const ma_int32*)src;
  35839. if (ditherMode == ma_dither_mode_none) {
  35840. ma_uint64 i;
  35841. for (i = 0; i < count; i += 1) {
  35842. ma_int32 x = src_s32[i];
  35843. x = x >> 16;
  35844. dst_s16[i] = (ma_int16)x;
  35845. }
  35846. } else {
  35847. ma_uint64 i;
  35848. for (i = 0; i < count; i += 1) {
  35849. ma_int32 x = src_s32[i];
  35850. /* Dither. Don't overflow. */
  35851. ma_int32 dither = ma_dither_s32(ditherMode, -0x8000, 0x7FFF);
  35852. if ((ma_int64)x + dither <= 0x7FFFFFFF) {
  35853. x = x + dither;
  35854. } else {
  35855. x = 0x7FFFFFFF;
  35856. }
  35857. x = x >> 16;
  35858. dst_s16[i] = (ma_int16)x;
  35859. }
  35860. }
  35861. }
  35862. static MA_INLINE void ma_pcm_s32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35863. {
  35864. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  35865. }
  35866. #if defined(MA_SUPPORT_SSE2)
  35867. static MA_INLINE void ma_pcm_s32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35868. {
  35869. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  35870. }
  35871. #endif
  35872. #if defined(MA_SUPPORT_AVX2)
  35873. static MA_INLINE void ma_pcm_s32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35874. {
  35875. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  35876. }
  35877. #endif
  35878. #if defined(MA_SUPPORT_NEON)
  35879. static MA_INLINE void ma_pcm_s32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35880. {
  35881. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  35882. }
  35883. #endif
  35884. MA_API void ma_pcm_s32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35885. {
  35886. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35887. ma_pcm_s32_to_s16__reference(dst, src, count, ditherMode);
  35888. #else
  35889. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35890. if (ma_has_avx2()) {
  35891. ma_pcm_s32_to_s16__avx2(dst, src, count, ditherMode);
  35892. } else
  35893. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35894. if (ma_has_sse2()) {
  35895. ma_pcm_s32_to_s16__sse2(dst, src, count, ditherMode);
  35896. } else
  35897. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35898. if (ma_has_neon()) {
  35899. ma_pcm_s32_to_s16__neon(dst, src, count, ditherMode);
  35900. } else
  35901. #endif
  35902. {
  35903. ma_pcm_s32_to_s16__optimized(dst, src, count, ditherMode);
  35904. }
  35905. #endif
  35906. }
  35907. static MA_INLINE void ma_pcm_s32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35908. {
  35909. ma_uint8* dst_s24 = (ma_uint8*)dst;
  35910. const ma_int32* src_s32 = (const ma_int32*)src;
  35911. ma_uint64 i;
  35912. for (i = 0; i < count; i += 1) {
  35913. ma_uint32 x = (ma_uint32)src_s32[i];
  35914. dst_s24[i*3+0] = (ma_uint8)((x & 0x0000FF00) >> 8);
  35915. dst_s24[i*3+1] = (ma_uint8)((x & 0x00FF0000) >> 16);
  35916. dst_s24[i*3+2] = (ma_uint8)((x & 0xFF000000) >> 24);
  35917. }
  35918. (void)ditherMode; /* No dithering for s32 -> s24. */
  35919. }
  35920. static MA_INLINE void ma_pcm_s32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35921. {
  35922. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  35923. }
  35924. #if defined(MA_SUPPORT_SSE2)
  35925. static MA_INLINE void ma_pcm_s32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35926. {
  35927. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  35928. }
  35929. #endif
  35930. #if defined(MA_SUPPORT_AVX2)
  35931. static MA_INLINE void ma_pcm_s32_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35932. {
  35933. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  35934. }
  35935. #endif
  35936. #if defined(MA_SUPPORT_NEON)
  35937. static MA_INLINE void ma_pcm_s32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35938. {
  35939. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  35940. }
  35941. #endif
  35942. MA_API void ma_pcm_s32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35943. {
  35944. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  35945. ma_pcm_s32_to_s24__reference(dst, src, count, ditherMode);
  35946. #else
  35947. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  35948. if (ma_has_avx2()) {
  35949. ma_pcm_s32_to_s24__avx2(dst, src, count, ditherMode);
  35950. } else
  35951. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  35952. if (ma_has_sse2()) {
  35953. ma_pcm_s32_to_s24__sse2(dst, src, count, ditherMode);
  35954. } else
  35955. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  35956. if (ma_has_neon()) {
  35957. ma_pcm_s32_to_s24__neon(dst, src, count, ditherMode);
  35958. } else
  35959. #endif
  35960. {
  35961. ma_pcm_s32_to_s24__optimized(dst, src, count, ditherMode);
  35962. }
  35963. #endif
  35964. }
  35965. MA_API void ma_pcm_s32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35966. {
  35967. (void)ditherMode;
  35968. ma_copy_memory_64(dst, src, count * sizeof(ma_int32));
  35969. }
  35970. static MA_INLINE void ma_pcm_s32_to_f32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35971. {
  35972. float* dst_f32 = (float*)dst;
  35973. const ma_int32* src_s32 = (const ma_int32*)src;
  35974. ma_uint64 i;
  35975. for (i = 0; i < count; i += 1) {
  35976. double x = src_s32[i];
  35977. #if 0
  35978. x = x + 2147483648.0;
  35979. x = x * 0.0000000004656612873077392578125;
  35980. x = x - 1;
  35981. #else
  35982. x = x / 2147483648.0;
  35983. #endif
  35984. dst_f32[i] = (float)x;
  35985. }
  35986. (void)ditherMode; /* No dithering for s32 -> f32. */
  35987. }
  35988. static MA_INLINE void ma_pcm_s32_to_f32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35989. {
  35990. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  35991. }
  35992. #if defined(MA_SUPPORT_SSE2)
  35993. static MA_INLINE void ma_pcm_s32_to_f32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  35994. {
  35995. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  35996. }
  35997. #endif
  35998. #if defined(MA_SUPPORT_AVX2)
  35999. static MA_INLINE void ma_pcm_s32_to_f32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36000. {
  36001. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  36002. }
  36003. #endif
  36004. #if defined(MA_SUPPORT_NEON)
  36005. static MA_INLINE void ma_pcm_s32_to_f32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36006. {
  36007. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  36008. }
  36009. #endif
  36010. MA_API void ma_pcm_s32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36011. {
  36012. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36013. ma_pcm_s32_to_f32__reference(dst, src, count, ditherMode);
  36014. #else
  36015. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  36016. if (ma_has_avx2()) {
  36017. ma_pcm_s32_to_f32__avx2(dst, src, count, ditherMode);
  36018. } else
  36019. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  36020. if (ma_has_sse2()) {
  36021. ma_pcm_s32_to_f32__sse2(dst, src, count, ditherMode);
  36022. } else
  36023. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  36024. if (ma_has_neon()) {
  36025. ma_pcm_s32_to_f32__neon(dst, src, count, ditherMode);
  36026. } else
  36027. #endif
  36028. {
  36029. ma_pcm_s32_to_f32__optimized(dst, src, count, ditherMode);
  36030. }
  36031. #endif
  36032. }
  36033. static MA_INLINE void ma_pcm_interleave_s32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36034. {
  36035. ma_int32* dst_s32 = (ma_int32*)dst;
  36036. const ma_int32** src_s32 = (const ma_int32**)src;
  36037. ma_uint64 iFrame;
  36038. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36039. ma_uint32 iChannel;
  36040. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36041. dst_s32[iFrame*channels + iChannel] = src_s32[iChannel][iFrame];
  36042. }
  36043. }
  36044. }
  36045. static MA_INLINE void ma_pcm_interleave_s32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36046. {
  36047. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  36048. }
  36049. MA_API void ma_pcm_interleave_s32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36050. {
  36051. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36052. ma_pcm_interleave_s32__reference(dst, src, frameCount, channels);
  36053. #else
  36054. ma_pcm_interleave_s32__optimized(dst, src, frameCount, channels);
  36055. #endif
  36056. }
  36057. static MA_INLINE void ma_pcm_deinterleave_s32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36058. {
  36059. ma_int32** dst_s32 = (ma_int32**)dst;
  36060. const ma_int32* src_s32 = (const ma_int32*)src;
  36061. ma_uint64 iFrame;
  36062. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36063. ma_uint32 iChannel;
  36064. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36065. dst_s32[iChannel][iFrame] = src_s32[iFrame*channels + iChannel];
  36066. }
  36067. }
  36068. }
  36069. static MA_INLINE void ma_pcm_deinterleave_s32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36070. {
  36071. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  36072. }
  36073. MA_API void ma_pcm_deinterleave_s32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36074. {
  36075. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36076. ma_pcm_deinterleave_s32__reference(dst, src, frameCount, channels);
  36077. #else
  36078. ma_pcm_deinterleave_s32__optimized(dst, src, frameCount, channels);
  36079. #endif
  36080. }
  36081. /* f32 */
  36082. static MA_INLINE void ma_pcm_f32_to_u8__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36083. {
  36084. ma_uint64 i;
  36085. ma_uint8* dst_u8 = (ma_uint8*)dst;
  36086. const float* src_f32 = (const float*)src;
  36087. float ditherMin = 0;
  36088. float ditherMax = 0;
  36089. if (ditherMode != ma_dither_mode_none) {
  36090. ditherMin = 1.0f / -128;
  36091. ditherMax = 1.0f / 127;
  36092. }
  36093. for (i = 0; i < count; i += 1) {
  36094. float x = src_f32[i];
  36095. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36096. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36097. x = x + 1; /* -1..1 to 0..2 */
  36098. x = x * 127.5f; /* 0..2 to 0..255 */
  36099. dst_u8[i] = (ma_uint8)x;
  36100. }
  36101. }
  36102. static MA_INLINE void ma_pcm_f32_to_u8__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36103. {
  36104. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  36105. }
  36106. #if defined(MA_SUPPORT_SSE2)
  36107. static MA_INLINE void ma_pcm_f32_to_u8__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36108. {
  36109. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  36110. }
  36111. #endif
  36112. #if defined(MA_SUPPORT_AVX2)
  36113. static MA_INLINE void ma_pcm_f32_to_u8__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36114. {
  36115. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  36116. }
  36117. #endif
  36118. #if defined(MA_SUPPORT_NEON)
  36119. static MA_INLINE void ma_pcm_f32_to_u8__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36120. {
  36121. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  36122. }
  36123. #endif
  36124. MA_API void ma_pcm_f32_to_u8(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36125. {
  36126. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36127. ma_pcm_f32_to_u8__reference(dst, src, count, ditherMode);
  36128. #else
  36129. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  36130. if (ma_has_avx2()) {
  36131. ma_pcm_f32_to_u8__avx2(dst, src, count, ditherMode);
  36132. } else
  36133. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  36134. if (ma_has_sse2()) {
  36135. ma_pcm_f32_to_u8__sse2(dst, src, count, ditherMode);
  36136. } else
  36137. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  36138. if (ma_has_neon()) {
  36139. ma_pcm_f32_to_u8__neon(dst, src, count, ditherMode);
  36140. } else
  36141. #endif
  36142. {
  36143. ma_pcm_f32_to_u8__optimized(dst, src, count, ditherMode);
  36144. }
  36145. #endif
  36146. }
  36147. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36148. static MA_INLINE void ma_pcm_f32_to_s16__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36149. {
  36150. ma_uint64 i;
  36151. ma_int16* dst_s16 = (ma_int16*)dst;
  36152. const float* src_f32 = (const float*)src;
  36153. float ditherMin = 0;
  36154. float ditherMax = 0;
  36155. if (ditherMode != ma_dither_mode_none) {
  36156. ditherMin = 1.0f / -32768;
  36157. ditherMax = 1.0f / 32767;
  36158. }
  36159. for (i = 0; i < count; i += 1) {
  36160. float x = src_f32[i];
  36161. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36162. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36163. #if 0
  36164. /* The accurate way. */
  36165. x = x + 1; /* -1..1 to 0..2 */
  36166. x = x * 32767.5f; /* 0..2 to 0..65535 */
  36167. x = x - 32768.0f; /* 0...65535 to -32768..32767 */
  36168. #else
  36169. /* The fast way. */
  36170. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  36171. #endif
  36172. dst_s16[i] = (ma_int16)x;
  36173. }
  36174. }
  36175. #else
  36176. static MA_INLINE void ma_pcm_f32_to_s16__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36177. {
  36178. ma_uint64 i;
  36179. ma_uint64 i4;
  36180. ma_uint64 count4;
  36181. ma_int16* dst_s16 = (ma_int16*)dst;
  36182. const float* src_f32 = (const float*)src;
  36183. float ditherMin = 0;
  36184. float ditherMax = 0;
  36185. if (ditherMode != ma_dither_mode_none) {
  36186. ditherMin = 1.0f / -32768;
  36187. ditherMax = 1.0f / 32767;
  36188. }
  36189. /* Unrolled. */
  36190. i = 0;
  36191. count4 = count >> 2;
  36192. for (i4 = 0; i4 < count4; i4 += 1) {
  36193. float d0 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36194. float d1 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36195. float d2 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36196. float d3 = ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36197. float x0 = src_f32[i+0];
  36198. float x1 = src_f32[i+1];
  36199. float x2 = src_f32[i+2];
  36200. float x3 = src_f32[i+3];
  36201. x0 = x0 + d0;
  36202. x1 = x1 + d1;
  36203. x2 = x2 + d2;
  36204. x3 = x3 + d3;
  36205. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  36206. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  36207. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  36208. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  36209. x0 = x0 * 32767.0f;
  36210. x1 = x1 * 32767.0f;
  36211. x2 = x2 * 32767.0f;
  36212. x3 = x3 * 32767.0f;
  36213. dst_s16[i+0] = (ma_int16)x0;
  36214. dst_s16[i+1] = (ma_int16)x1;
  36215. dst_s16[i+2] = (ma_int16)x2;
  36216. dst_s16[i+3] = (ma_int16)x3;
  36217. i += 4;
  36218. }
  36219. /* Leftover. */
  36220. for (; i < count; i += 1) {
  36221. float x = src_f32[i];
  36222. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36223. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36224. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  36225. dst_s16[i] = (ma_int16)x;
  36226. }
  36227. }
  36228. #if defined(MA_SUPPORT_SSE2)
  36229. static MA_INLINE void ma_pcm_f32_to_s16__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36230. {
  36231. ma_uint64 i;
  36232. ma_uint64 i8;
  36233. ma_uint64 count8;
  36234. ma_int16* dst_s16;
  36235. const float* src_f32;
  36236. float ditherMin;
  36237. float ditherMax;
  36238. /* Both the input and output buffers need to be aligned to 16 bytes. */
  36239. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  36240. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  36241. return;
  36242. }
  36243. dst_s16 = (ma_int16*)dst;
  36244. src_f32 = (const float*)src;
  36245. ditherMin = 0;
  36246. ditherMax = 0;
  36247. if (ditherMode != ma_dither_mode_none) {
  36248. ditherMin = 1.0f / -32768;
  36249. ditherMax = 1.0f / 32767;
  36250. }
  36251. i = 0;
  36252. /* SSE2. SSE allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  36253. count8 = count >> 3;
  36254. for (i8 = 0; i8 < count8; i8 += 1) {
  36255. __m128 d0;
  36256. __m128 d1;
  36257. __m128 x0;
  36258. __m128 x1;
  36259. if (ditherMode == ma_dither_mode_none) {
  36260. d0 = _mm_set1_ps(0);
  36261. d1 = _mm_set1_ps(0);
  36262. } else if (ditherMode == ma_dither_mode_rectangle) {
  36263. d0 = _mm_set_ps(
  36264. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36265. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36266. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36267. ma_dither_f32_rectangle(ditherMin, ditherMax)
  36268. );
  36269. d1 = _mm_set_ps(
  36270. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36271. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36272. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36273. ma_dither_f32_rectangle(ditherMin, ditherMax)
  36274. );
  36275. } else {
  36276. d0 = _mm_set_ps(
  36277. ma_dither_f32_triangle(ditherMin, ditherMax),
  36278. ma_dither_f32_triangle(ditherMin, ditherMax),
  36279. ma_dither_f32_triangle(ditherMin, ditherMax),
  36280. ma_dither_f32_triangle(ditherMin, ditherMax)
  36281. );
  36282. d1 = _mm_set_ps(
  36283. ma_dither_f32_triangle(ditherMin, ditherMax),
  36284. ma_dither_f32_triangle(ditherMin, ditherMax),
  36285. ma_dither_f32_triangle(ditherMin, ditherMax),
  36286. ma_dither_f32_triangle(ditherMin, ditherMax)
  36287. );
  36288. }
  36289. x0 = *((__m128*)(src_f32 + i) + 0);
  36290. x1 = *((__m128*)(src_f32 + i) + 1);
  36291. x0 = _mm_add_ps(x0, d0);
  36292. x1 = _mm_add_ps(x1, d1);
  36293. x0 = _mm_mul_ps(x0, _mm_set1_ps(32767.0f));
  36294. x1 = _mm_mul_ps(x1, _mm_set1_ps(32767.0f));
  36295. _mm_stream_si128(((__m128i*)(dst_s16 + i)), _mm_packs_epi32(_mm_cvttps_epi32(x0), _mm_cvttps_epi32(x1)));
  36296. i += 8;
  36297. }
  36298. /* Leftover. */
  36299. for (; i < count; i += 1) {
  36300. float x = src_f32[i];
  36301. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36302. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36303. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  36304. dst_s16[i] = (ma_int16)x;
  36305. }
  36306. }
  36307. #endif /* SSE2 */
  36308. #if defined(MA_SUPPORT_AVX2)
  36309. static MA_INLINE void ma_pcm_f32_to_s16__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36310. {
  36311. ma_uint64 i;
  36312. ma_uint64 i16;
  36313. ma_uint64 count16;
  36314. ma_int16* dst_s16;
  36315. const float* src_f32;
  36316. float ditherMin;
  36317. float ditherMax;
  36318. /* Both the input and output buffers need to be aligned to 32 bytes. */
  36319. if ((((ma_uintptr)dst & 31) != 0) || (((ma_uintptr)src & 31) != 0)) {
  36320. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  36321. return;
  36322. }
  36323. dst_s16 = (ma_int16*)dst;
  36324. src_f32 = (const float*)src;
  36325. ditherMin = 0;
  36326. ditherMax = 0;
  36327. if (ditherMode != ma_dither_mode_none) {
  36328. ditherMin = 1.0f / -32768;
  36329. ditherMax = 1.0f / 32767;
  36330. }
  36331. i = 0;
  36332. /* AVX2. AVX2 allows us to output 16 s16's at a time which means our loop is unrolled 16 times. */
  36333. count16 = count >> 4;
  36334. for (i16 = 0; i16 < count16; i16 += 1) {
  36335. __m256 d0;
  36336. __m256 d1;
  36337. __m256 x0;
  36338. __m256 x1;
  36339. __m256i i0;
  36340. __m256i i1;
  36341. __m256i p0;
  36342. __m256i p1;
  36343. __m256i r;
  36344. if (ditherMode == ma_dither_mode_none) {
  36345. d0 = _mm256_set1_ps(0);
  36346. d1 = _mm256_set1_ps(0);
  36347. } else if (ditherMode == ma_dither_mode_rectangle) {
  36348. d0 = _mm256_set_ps(
  36349. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36350. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36351. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36352. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36353. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36354. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36355. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36356. ma_dither_f32_rectangle(ditherMin, ditherMax)
  36357. );
  36358. d1 = _mm256_set_ps(
  36359. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36360. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36361. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36362. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36363. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36364. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36365. ma_dither_f32_rectangle(ditherMin, ditherMax),
  36366. ma_dither_f32_rectangle(ditherMin, ditherMax)
  36367. );
  36368. } else {
  36369. d0 = _mm256_set_ps(
  36370. ma_dither_f32_triangle(ditherMin, ditherMax),
  36371. ma_dither_f32_triangle(ditherMin, ditherMax),
  36372. ma_dither_f32_triangle(ditherMin, ditherMax),
  36373. ma_dither_f32_triangle(ditherMin, ditherMax),
  36374. ma_dither_f32_triangle(ditherMin, ditherMax),
  36375. ma_dither_f32_triangle(ditherMin, ditherMax),
  36376. ma_dither_f32_triangle(ditherMin, ditherMax),
  36377. ma_dither_f32_triangle(ditherMin, ditherMax)
  36378. );
  36379. d1 = _mm256_set_ps(
  36380. ma_dither_f32_triangle(ditherMin, ditherMax),
  36381. ma_dither_f32_triangle(ditherMin, ditherMax),
  36382. ma_dither_f32_triangle(ditherMin, ditherMax),
  36383. ma_dither_f32_triangle(ditherMin, ditherMax),
  36384. ma_dither_f32_triangle(ditherMin, ditherMax),
  36385. ma_dither_f32_triangle(ditherMin, ditherMax),
  36386. ma_dither_f32_triangle(ditherMin, ditherMax),
  36387. ma_dither_f32_triangle(ditherMin, ditherMax)
  36388. );
  36389. }
  36390. x0 = *((__m256*)(src_f32 + i) + 0);
  36391. x1 = *((__m256*)(src_f32 + i) + 1);
  36392. x0 = _mm256_add_ps(x0, d0);
  36393. x1 = _mm256_add_ps(x1, d1);
  36394. x0 = _mm256_mul_ps(x0, _mm256_set1_ps(32767.0f));
  36395. x1 = _mm256_mul_ps(x1, _mm256_set1_ps(32767.0f));
  36396. /* Computing the final result is a little more complicated for AVX2 than SSE2. */
  36397. i0 = _mm256_cvttps_epi32(x0);
  36398. i1 = _mm256_cvttps_epi32(x1);
  36399. p0 = _mm256_permute2x128_si256(i0, i1, 0 | 32);
  36400. p1 = _mm256_permute2x128_si256(i0, i1, 1 | 48);
  36401. r = _mm256_packs_epi32(p0, p1);
  36402. _mm256_stream_si256(((__m256i*)(dst_s16 + i)), r);
  36403. i += 16;
  36404. }
  36405. /* Leftover. */
  36406. for (; i < count; i += 1) {
  36407. float x = src_f32[i];
  36408. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36409. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36410. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  36411. dst_s16[i] = (ma_int16)x;
  36412. }
  36413. }
  36414. #endif /* AVX2 */
  36415. #if defined(MA_SUPPORT_NEON)
  36416. static MA_INLINE void ma_pcm_f32_to_s16__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36417. {
  36418. ma_uint64 i;
  36419. ma_uint64 i8;
  36420. ma_uint64 count8;
  36421. ma_int16* dst_s16;
  36422. const float* src_f32;
  36423. float ditherMin;
  36424. float ditherMax;
  36425. if (!ma_has_neon()) {
  36426. return ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  36427. }
  36428. /* Both the input and output buffers need to be aligned to 16 bytes. */
  36429. if ((((ma_uintptr)dst & 15) != 0) || (((ma_uintptr)src & 15) != 0)) {
  36430. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  36431. return;
  36432. }
  36433. dst_s16 = (ma_int16*)dst;
  36434. src_f32 = (const float*)src;
  36435. ditherMin = 0;
  36436. ditherMax = 0;
  36437. if (ditherMode != ma_dither_mode_none) {
  36438. ditherMin = 1.0f / -32768;
  36439. ditherMax = 1.0f / 32767;
  36440. }
  36441. i = 0;
  36442. /* NEON. NEON allows us to output 8 s16's at a time which means our loop is unrolled 8 times. */
  36443. count8 = count >> 3;
  36444. for (i8 = 0; i8 < count8; i8 += 1) {
  36445. float32x4_t d0;
  36446. float32x4_t d1;
  36447. float32x4_t x0;
  36448. float32x4_t x1;
  36449. int32x4_t i0;
  36450. int32x4_t i1;
  36451. if (ditherMode == ma_dither_mode_none) {
  36452. d0 = vmovq_n_f32(0);
  36453. d1 = vmovq_n_f32(0);
  36454. } else if (ditherMode == ma_dither_mode_rectangle) {
  36455. float d0v[4];
  36456. d0v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36457. d0v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36458. d0v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36459. d0v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36460. d0 = vld1q_f32(d0v);
  36461. float d1v[4];
  36462. d1v[0] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36463. d1v[1] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36464. d1v[2] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36465. d1v[3] = ma_dither_f32_rectangle(ditherMin, ditherMax);
  36466. d1 = vld1q_f32(d1v);
  36467. } else {
  36468. float d0v[4];
  36469. d0v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36470. d0v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36471. d0v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36472. d0v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36473. d0 = vld1q_f32(d0v);
  36474. float d1v[4];
  36475. d1v[0] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36476. d1v[1] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36477. d1v[2] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36478. d1v[3] = ma_dither_f32_triangle(ditherMin, ditherMax);
  36479. d1 = vld1q_f32(d1v);
  36480. }
  36481. x0 = *((float32x4_t*)(src_f32 + i) + 0);
  36482. x1 = *((float32x4_t*)(src_f32 + i) + 1);
  36483. x0 = vaddq_f32(x0, d0);
  36484. x1 = vaddq_f32(x1, d1);
  36485. x0 = vmulq_n_f32(x0, 32767.0f);
  36486. x1 = vmulq_n_f32(x1, 32767.0f);
  36487. i0 = vcvtq_s32_f32(x0);
  36488. i1 = vcvtq_s32_f32(x1);
  36489. *((int16x8_t*)(dst_s16 + i)) = vcombine_s16(vqmovn_s32(i0), vqmovn_s32(i1));
  36490. i += 8;
  36491. }
  36492. /* Leftover. */
  36493. for (; i < count; i += 1) {
  36494. float x = src_f32[i];
  36495. x = x + ma_dither_f32(ditherMode, ditherMin, ditherMax);
  36496. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36497. x = x * 32767.0f; /* -1..1 to -32767..32767 */
  36498. dst_s16[i] = (ma_int16)x;
  36499. }
  36500. }
  36501. #endif /* Neon */
  36502. #endif /* MA_USE_REFERENCE_CONVERSION_APIS */
  36503. MA_API void ma_pcm_f32_to_s16(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36504. {
  36505. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36506. ma_pcm_f32_to_s16__reference(dst, src, count, ditherMode);
  36507. #else
  36508. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  36509. if (ma_has_avx2()) {
  36510. ma_pcm_f32_to_s16__avx2(dst, src, count, ditherMode);
  36511. } else
  36512. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  36513. if (ma_has_sse2()) {
  36514. ma_pcm_f32_to_s16__sse2(dst, src, count, ditherMode);
  36515. } else
  36516. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  36517. if (ma_has_neon()) {
  36518. ma_pcm_f32_to_s16__neon(dst, src, count, ditherMode);
  36519. } else
  36520. #endif
  36521. {
  36522. ma_pcm_f32_to_s16__optimized(dst, src, count, ditherMode);
  36523. }
  36524. #endif
  36525. }
  36526. static MA_INLINE void ma_pcm_f32_to_s24__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36527. {
  36528. ma_uint8* dst_s24 = (ma_uint8*)dst;
  36529. const float* src_f32 = (const float*)src;
  36530. ma_uint64 i;
  36531. for (i = 0; i < count; i += 1) {
  36532. ma_int32 r;
  36533. float x = src_f32[i];
  36534. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36535. #if 0
  36536. /* The accurate way. */
  36537. x = x + 1; /* -1..1 to 0..2 */
  36538. x = x * 8388607.5f; /* 0..2 to 0..16777215 */
  36539. x = x - 8388608.0f; /* 0..16777215 to -8388608..8388607 */
  36540. #else
  36541. /* The fast way. */
  36542. x = x * 8388607.0f; /* -1..1 to -8388607..8388607 */
  36543. #endif
  36544. r = (ma_int32)x;
  36545. dst_s24[(i*3)+0] = (ma_uint8)((r & 0x0000FF) >> 0);
  36546. dst_s24[(i*3)+1] = (ma_uint8)((r & 0x00FF00) >> 8);
  36547. dst_s24[(i*3)+2] = (ma_uint8)((r & 0xFF0000) >> 16);
  36548. }
  36549. (void)ditherMode; /* No dithering for f32 -> s24. */
  36550. }
  36551. static MA_INLINE void ma_pcm_f32_to_s24__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36552. {
  36553. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  36554. }
  36555. #if defined(MA_SUPPORT_SSE2)
  36556. static MA_INLINE void ma_pcm_f32_to_s24__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36557. {
  36558. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  36559. }
  36560. #endif
  36561. #if defined(MA_SUPPORT_AVX2)
  36562. static MA_INLINE void ma_pcm_f32_to_s24__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36563. {
  36564. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  36565. }
  36566. #endif
  36567. #if defined(MA_SUPPORT_NEON)
  36568. static MA_INLINE void ma_pcm_f32_to_s24__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36569. {
  36570. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  36571. }
  36572. #endif
  36573. MA_API void ma_pcm_f32_to_s24(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36574. {
  36575. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36576. ma_pcm_f32_to_s24__reference(dst, src, count, ditherMode);
  36577. #else
  36578. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  36579. if (ma_has_avx2()) {
  36580. ma_pcm_f32_to_s24__avx2(dst, src, count, ditherMode);
  36581. } else
  36582. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  36583. if (ma_has_sse2()) {
  36584. ma_pcm_f32_to_s24__sse2(dst, src, count, ditherMode);
  36585. } else
  36586. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  36587. if (ma_has_neon()) {
  36588. ma_pcm_f32_to_s24__neon(dst, src, count, ditherMode);
  36589. } else
  36590. #endif
  36591. {
  36592. ma_pcm_f32_to_s24__optimized(dst, src, count, ditherMode);
  36593. }
  36594. #endif
  36595. }
  36596. static MA_INLINE void ma_pcm_f32_to_s32__reference(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36597. {
  36598. ma_int32* dst_s32 = (ma_int32*)dst;
  36599. const float* src_f32 = (const float*)src;
  36600. ma_uint32 i;
  36601. for (i = 0; i < count; i += 1) {
  36602. double x = src_f32[i];
  36603. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x)); /* clip */
  36604. #if 0
  36605. /* The accurate way. */
  36606. x = x + 1; /* -1..1 to 0..2 */
  36607. x = x * 2147483647.5; /* 0..2 to 0..4294967295 */
  36608. x = x - 2147483648.0; /* 0...4294967295 to -2147483648..2147483647 */
  36609. #else
  36610. /* The fast way. */
  36611. x = x * 2147483647.0; /* -1..1 to -2147483647..2147483647 */
  36612. #endif
  36613. dst_s32[i] = (ma_int32)x;
  36614. }
  36615. (void)ditherMode; /* No dithering for f32 -> s32. */
  36616. }
  36617. static MA_INLINE void ma_pcm_f32_to_s32__optimized(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36618. {
  36619. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  36620. }
  36621. #if defined(MA_SUPPORT_SSE2)
  36622. static MA_INLINE void ma_pcm_f32_to_s32__sse2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36623. {
  36624. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  36625. }
  36626. #endif
  36627. #if defined(MA_SUPPORT_AVX2)
  36628. static MA_INLINE void ma_pcm_f32_to_s32__avx2(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36629. {
  36630. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  36631. }
  36632. #endif
  36633. #if defined(MA_SUPPORT_NEON)
  36634. static MA_INLINE void ma_pcm_f32_to_s32__neon(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36635. {
  36636. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  36637. }
  36638. #endif
  36639. MA_API void ma_pcm_f32_to_s32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36640. {
  36641. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36642. ma_pcm_f32_to_s32__reference(dst, src, count, ditherMode);
  36643. #else
  36644. # if MA_PREFERRED_SIMD == MA_SIMD_AVX2
  36645. if (ma_has_avx2()) {
  36646. ma_pcm_f32_to_s32__avx2(dst, src, count, ditherMode);
  36647. } else
  36648. #elif MA_PREFERRED_SIMD == MA_SIMD_SSE2
  36649. if (ma_has_sse2()) {
  36650. ma_pcm_f32_to_s32__sse2(dst, src, count, ditherMode);
  36651. } else
  36652. #elif MA_PREFERRED_SIMD == MA_SIMD_NEON
  36653. if (ma_has_neon()) {
  36654. ma_pcm_f32_to_s32__neon(dst, src, count, ditherMode);
  36655. } else
  36656. #endif
  36657. {
  36658. ma_pcm_f32_to_s32__optimized(dst, src, count, ditherMode);
  36659. }
  36660. #endif
  36661. }
  36662. MA_API void ma_pcm_f32_to_f32(void* dst, const void* src, ma_uint64 count, ma_dither_mode ditherMode)
  36663. {
  36664. (void)ditherMode;
  36665. ma_copy_memory_64(dst, src, count * sizeof(float));
  36666. }
  36667. static void ma_pcm_interleave_f32__reference(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36668. {
  36669. float* dst_f32 = (float*)dst;
  36670. const float** src_f32 = (const float**)src;
  36671. ma_uint64 iFrame;
  36672. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36673. ma_uint32 iChannel;
  36674. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36675. dst_f32[iFrame*channels + iChannel] = src_f32[iChannel][iFrame];
  36676. }
  36677. }
  36678. }
  36679. static void ma_pcm_interleave_f32__optimized(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36680. {
  36681. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  36682. }
  36683. MA_API void ma_pcm_interleave_f32(void* dst, const void** src, ma_uint64 frameCount, ma_uint32 channels)
  36684. {
  36685. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36686. ma_pcm_interleave_f32__reference(dst, src, frameCount, channels);
  36687. #else
  36688. ma_pcm_interleave_f32__optimized(dst, src, frameCount, channels);
  36689. #endif
  36690. }
  36691. static void ma_pcm_deinterleave_f32__reference(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36692. {
  36693. float** dst_f32 = (float**)dst;
  36694. const float* src_f32 = (const float*)src;
  36695. ma_uint64 iFrame;
  36696. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  36697. ma_uint32 iChannel;
  36698. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  36699. dst_f32[iChannel][iFrame] = src_f32[iFrame*channels + iChannel];
  36700. }
  36701. }
  36702. }
  36703. static void ma_pcm_deinterleave_f32__optimized(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36704. {
  36705. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  36706. }
  36707. MA_API void ma_pcm_deinterleave_f32(void** dst, const void* src, ma_uint64 frameCount, ma_uint32 channels)
  36708. {
  36709. #ifdef MA_USE_REFERENCE_CONVERSION_APIS
  36710. ma_pcm_deinterleave_f32__reference(dst, src, frameCount, channels);
  36711. #else
  36712. ma_pcm_deinterleave_f32__optimized(dst, src, frameCount, channels);
  36713. #endif
  36714. }
  36715. MA_API void ma_pcm_convert(void* pOut, ma_format formatOut, const void* pIn, ma_format formatIn, ma_uint64 sampleCount, ma_dither_mode ditherMode)
  36716. {
  36717. if (formatOut == formatIn) {
  36718. ma_copy_memory_64(pOut, pIn, sampleCount * ma_get_bytes_per_sample(formatOut));
  36719. return;
  36720. }
  36721. switch (formatIn)
  36722. {
  36723. case ma_format_u8:
  36724. {
  36725. switch (formatOut)
  36726. {
  36727. case ma_format_s16: ma_pcm_u8_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  36728. case ma_format_s24: ma_pcm_u8_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  36729. case ma_format_s32: ma_pcm_u8_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  36730. case ma_format_f32: ma_pcm_u8_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  36731. default: break;
  36732. }
  36733. } break;
  36734. case ma_format_s16:
  36735. {
  36736. switch (formatOut)
  36737. {
  36738. case ma_format_u8: ma_pcm_s16_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  36739. case ma_format_s24: ma_pcm_s16_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  36740. case ma_format_s32: ma_pcm_s16_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  36741. case ma_format_f32: ma_pcm_s16_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  36742. default: break;
  36743. }
  36744. } break;
  36745. case ma_format_s24:
  36746. {
  36747. switch (formatOut)
  36748. {
  36749. case ma_format_u8: ma_pcm_s24_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  36750. case ma_format_s16: ma_pcm_s24_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  36751. case ma_format_s32: ma_pcm_s24_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  36752. case ma_format_f32: ma_pcm_s24_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  36753. default: break;
  36754. }
  36755. } break;
  36756. case ma_format_s32:
  36757. {
  36758. switch (formatOut)
  36759. {
  36760. case ma_format_u8: ma_pcm_s32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  36761. case ma_format_s16: ma_pcm_s32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  36762. case ma_format_s24: ma_pcm_s32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  36763. case ma_format_f32: ma_pcm_s32_to_f32(pOut, pIn, sampleCount, ditherMode); return;
  36764. default: break;
  36765. }
  36766. } break;
  36767. case ma_format_f32:
  36768. {
  36769. switch (formatOut)
  36770. {
  36771. case ma_format_u8: ma_pcm_f32_to_u8( pOut, pIn, sampleCount, ditherMode); return;
  36772. case ma_format_s16: ma_pcm_f32_to_s16(pOut, pIn, sampleCount, ditherMode); return;
  36773. case ma_format_s24: ma_pcm_f32_to_s24(pOut, pIn, sampleCount, ditherMode); return;
  36774. case ma_format_s32: ma_pcm_f32_to_s32(pOut, pIn, sampleCount, ditherMode); return;
  36775. default: break;
  36776. }
  36777. } break;
  36778. default: break;
  36779. }
  36780. }
  36781. 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)
  36782. {
  36783. ma_pcm_convert(pOut, formatOut, pIn, formatIn, frameCount * channels, ditherMode);
  36784. }
  36785. MA_API void ma_deinterleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void* pInterleavedPCMFrames, void** ppDeinterleavedPCMFrames)
  36786. {
  36787. if (pInterleavedPCMFrames == NULL || ppDeinterleavedPCMFrames == NULL) {
  36788. return; /* Invalid args. */
  36789. }
  36790. /* For efficiency we do this per format. */
  36791. switch (format) {
  36792. case ma_format_s16:
  36793. {
  36794. const ma_int16* pSrcS16 = (const ma_int16*)pInterleavedPCMFrames;
  36795. ma_uint64 iPCMFrame;
  36796. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36797. ma_uint32 iChannel;
  36798. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36799. ma_int16* pDstS16 = (ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  36800. pDstS16[iPCMFrame] = pSrcS16[iPCMFrame*channels+iChannel];
  36801. }
  36802. }
  36803. } break;
  36804. case ma_format_f32:
  36805. {
  36806. const float* pSrcF32 = (const float*)pInterleavedPCMFrames;
  36807. ma_uint64 iPCMFrame;
  36808. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36809. ma_uint32 iChannel;
  36810. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36811. float* pDstF32 = (float*)ppDeinterleavedPCMFrames[iChannel];
  36812. pDstF32[iPCMFrame] = pSrcF32[iPCMFrame*channels+iChannel];
  36813. }
  36814. }
  36815. } break;
  36816. default:
  36817. {
  36818. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  36819. ma_uint64 iPCMFrame;
  36820. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36821. ma_uint32 iChannel;
  36822. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36823. void* pDst = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  36824. const void* pSrc = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  36825. memcpy(pDst, pSrc, sampleSizeInBytes);
  36826. }
  36827. }
  36828. } break;
  36829. }
  36830. }
  36831. MA_API void ma_interleave_pcm_frames(ma_format format, ma_uint32 channels, ma_uint64 frameCount, const void** ppDeinterleavedPCMFrames, void* pInterleavedPCMFrames)
  36832. {
  36833. switch (format)
  36834. {
  36835. case ma_format_s16:
  36836. {
  36837. ma_int16* pDstS16 = (ma_int16*)pInterleavedPCMFrames;
  36838. ma_uint64 iPCMFrame;
  36839. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36840. ma_uint32 iChannel;
  36841. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36842. const ma_int16* pSrcS16 = (const ma_int16*)ppDeinterleavedPCMFrames[iChannel];
  36843. pDstS16[iPCMFrame*channels+iChannel] = pSrcS16[iPCMFrame];
  36844. }
  36845. }
  36846. } break;
  36847. case ma_format_f32:
  36848. {
  36849. float* pDstF32 = (float*)pInterleavedPCMFrames;
  36850. ma_uint64 iPCMFrame;
  36851. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36852. ma_uint32 iChannel;
  36853. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36854. const float* pSrcF32 = (const float*)ppDeinterleavedPCMFrames[iChannel];
  36855. pDstF32[iPCMFrame*channels+iChannel] = pSrcF32[iPCMFrame];
  36856. }
  36857. }
  36858. } break;
  36859. default:
  36860. {
  36861. ma_uint32 sampleSizeInBytes = ma_get_bytes_per_sample(format);
  36862. ma_uint64 iPCMFrame;
  36863. for (iPCMFrame = 0; iPCMFrame < frameCount; ++iPCMFrame) {
  36864. ma_uint32 iChannel;
  36865. for (iChannel = 0; iChannel < channels; ++iChannel) {
  36866. void* pDst = ma_offset_ptr(pInterleavedPCMFrames, (iPCMFrame*channels+iChannel)*sampleSizeInBytes);
  36867. const void* pSrc = ma_offset_ptr(ppDeinterleavedPCMFrames[iChannel], iPCMFrame*sampleSizeInBytes);
  36868. memcpy(pDst, pSrc, sampleSizeInBytes);
  36869. }
  36870. }
  36871. } break;
  36872. }
  36873. }
  36874. /**************************************************************************************************************************************************************
  36875. Biquad Filter
  36876. **************************************************************************************************************************************************************/
  36877. #ifndef MA_BIQUAD_FIXED_POINT_SHIFT
  36878. #define MA_BIQUAD_FIXED_POINT_SHIFT 14
  36879. #endif
  36880. static ma_int32 ma_biquad_float_to_fp(double x)
  36881. {
  36882. return (ma_int32)(x * (1 << MA_BIQUAD_FIXED_POINT_SHIFT));
  36883. }
  36884. 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)
  36885. {
  36886. ma_biquad_config config;
  36887. MA_ZERO_OBJECT(&config);
  36888. config.format = format;
  36889. config.channels = channels;
  36890. config.b0 = b0;
  36891. config.b1 = b1;
  36892. config.b2 = b2;
  36893. config.a0 = a0;
  36894. config.a1 = a1;
  36895. config.a2 = a2;
  36896. return config;
  36897. }
  36898. typedef struct
  36899. {
  36900. size_t sizeInBytes;
  36901. size_t r1Offset;
  36902. size_t r2Offset;
  36903. } ma_biquad_heap_layout;
  36904. static ma_result ma_biquad_get_heap_layout(const ma_biquad_config* pConfig, ma_biquad_heap_layout* pHeapLayout)
  36905. {
  36906. MA_ASSERT(pHeapLayout != NULL);
  36907. MA_ZERO_OBJECT(pHeapLayout);
  36908. if (pConfig == NULL) {
  36909. return MA_INVALID_ARGS;
  36910. }
  36911. if (pConfig->channels == 0) {
  36912. return MA_INVALID_ARGS;
  36913. }
  36914. pHeapLayout->sizeInBytes = 0;
  36915. /* R0 */
  36916. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  36917. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  36918. /* R1 */
  36919. pHeapLayout->r2Offset = pHeapLayout->sizeInBytes;
  36920. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  36921. /* Make sure allocation size is aligned. */
  36922. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  36923. return MA_SUCCESS;
  36924. }
  36925. MA_API ma_result ma_biquad_get_heap_size(const ma_biquad_config* pConfig, size_t* pHeapSizeInBytes)
  36926. {
  36927. ma_result result;
  36928. ma_biquad_heap_layout heapLayout;
  36929. if (pHeapSizeInBytes == NULL) {
  36930. return MA_INVALID_ARGS;
  36931. }
  36932. *pHeapSizeInBytes = 0;
  36933. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  36934. if (result != MA_SUCCESS) {
  36935. return result;
  36936. }
  36937. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  36938. return MA_SUCCESS;
  36939. }
  36940. MA_API ma_result ma_biquad_init_preallocated(const ma_biquad_config* pConfig, void* pHeap, ma_biquad* pBQ)
  36941. {
  36942. ma_result result;
  36943. ma_biquad_heap_layout heapLayout;
  36944. if (pBQ == NULL) {
  36945. return MA_INVALID_ARGS;
  36946. }
  36947. MA_ZERO_OBJECT(pBQ);
  36948. result = ma_biquad_get_heap_layout(pConfig, &heapLayout);
  36949. if (result != MA_SUCCESS) {
  36950. return result;
  36951. }
  36952. pBQ->_pHeap = pHeap;
  36953. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  36954. pBQ->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  36955. pBQ->pR2 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r2Offset);
  36956. return ma_biquad_reinit(pConfig, pBQ);
  36957. }
  36958. MA_API ma_result ma_biquad_init(const ma_biquad_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_biquad* pBQ)
  36959. {
  36960. ma_result result;
  36961. size_t heapSizeInBytes;
  36962. void* pHeap;
  36963. result = ma_biquad_get_heap_size(pConfig, &heapSizeInBytes);
  36964. if (result != MA_SUCCESS) {
  36965. return result;
  36966. }
  36967. if (heapSizeInBytes > 0) {
  36968. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  36969. if (pHeap == NULL) {
  36970. return MA_OUT_OF_MEMORY;
  36971. }
  36972. } else {
  36973. pHeap = NULL;
  36974. }
  36975. result = ma_biquad_init_preallocated(pConfig, pHeap, pBQ);
  36976. if (result != MA_SUCCESS) {
  36977. ma_free(pHeap, pAllocationCallbacks);
  36978. return result;
  36979. }
  36980. pBQ->_ownsHeap = MA_TRUE;
  36981. return MA_SUCCESS;
  36982. }
  36983. MA_API void ma_biquad_uninit(ma_biquad* pBQ, const ma_allocation_callbacks* pAllocationCallbacks)
  36984. {
  36985. if (pBQ == NULL) {
  36986. return;
  36987. }
  36988. if (pBQ->_ownsHeap) {
  36989. ma_free(pBQ->_pHeap, pAllocationCallbacks);
  36990. }
  36991. }
  36992. MA_API ma_result ma_biquad_reinit(const ma_biquad_config* pConfig, ma_biquad* pBQ)
  36993. {
  36994. if (pBQ == NULL || pConfig == NULL) {
  36995. return MA_INVALID_ARGS;
  36996. }
  36997. if (pConfig->a0 == 0) {
  36998. return MA_INVALID_ARGS; /* Division by zero. */
  36999. }
  37000. /* Only supporting f32 and s16. */
  37001. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37002. return MA_INVALID_ARGS;
  37003. }
  37004. /* The format cannot be changed after initialization. */
  37005. if (pBQ->format != ma_format_unknown && pBQ->format != pConfig->format) {
  37006. return MA_INVALID_OPERATION;
  37007. }
  37008. /* The channel count cannot be changed after initialization. */
  37009. if (pBQ->channels != 0 && pBQ->channels != pConfig->channels) {
  37010. return MA_INVALID_OPERATION;
  37011. }
  37012. pBQ->format = pConfig->format;
  37013. pBQ->channels = pConfig->channels;
  37014. /* Normalize. */
  37015. if (pConfig->format == ma_format_f32) {
  37016. pBQ->b0.f32 = (float)(pConfig->b0 / pConfig->a0);
  37017. pBQ->b1.f32 = (float)(pConfig->b1 / pConfig->a0);
  37018. pBQ->b2.f32 = (float)(pConfig->b2 / pConfig->a0);
  37019. pBQ->a1.f32 = (float)(pConfig->a1 / pConfig->a0);
  37020. pBQ->a2.f32 = (float)(pConfig->a2 / pConfig->a0);
  37021. } else {
  37022. pBQ->b0.s32 = ma_biquad_float_to_fp(pConfig->b0 / pConfig->a0);
  37023. pBQ->b1.s32 = ma_biquad_float_to_fp(pConfig->b1 / pConfig->a0);
  37024. pBQ->b2.s32 = ma_biquad_float_to_fp(pConfig->b2 / pConfig->a0);
  37025. pBQ->a1.s32 = ma_biquad_float_to_fp(pConfig->a1 / pConfig->a0);
  37026. pBQ->a2.s32 = ma_biquad_float_to_fp(pConfig->a2 / pConfig->a0);
  37027. }
  37028. return MA_SUCCESS;
  37029. }
  37030. MA_API ma_result ma_biquad_clear_cache(ma_biquad* pBQ)
  37031. {
  37032. if (pBQ == NULL) {
  37033. return MA_INVALID_ARGS;
  37034. }
  37035. if (pBQ->format == ma_format_f32) {
  37036. pBQ->pR1->f32 = 0;
  37037. pBQ->pR2->f32 = 0;
  37038. } else {
  37039. pBQ->pR1->s32 = 0;
  37040. pBQ->pR2->s32 = 0;
  37041. }
  37042. return MA_SUCCESS;
  37043. }
  37044. static MA_INLINE void ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(ma_biquad* pBQ, float* pY, const float* pX)
  37045. {
  37046. ma_uint32 c;
  37047. const ma_uint32 channels = pBQ->channels;
  37048. const float b0 = pBQ->b0.f32;
  37049. const float b1 = pBQ->b1.f32;
  37050. const float b2 = pBQ->b2.f32;
  37051. const float a1 = pBQ->a1.f32;
  37052. const float a2 = pBQ->a2.f32;
  37053. MA_ASSUME(channels > 0);
  37054. for (c = 0; c < channels; c += 1) {
  37055. float r1 = pBQ->pR1[c].f32;
  37056. float r2 = pBQ->pR2[c].f32;
  37057. float x = pX[c];
  37058. float y;
  37059. y = b0*x + r1;
  37060. r1 = b1*x - a1*y + r2;
  37061. r2 = b2*x - a2*y;
  37062. pY[c] = y;
  37063. pBQ->pR1[c].f32 = r1;
  37064. pBQ->pR2[c].f32 = r2;
  37065. }
  37066. }
  37067. static MA_INLINE void ma_biquad_process_pcm_frame_f32(ma_biquad* pBQ, float* pY, const float* pX)
  37068. {
  37069. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  37070. }
  37071. static MA_INLINE void ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  37072. {
  37073. ma_uint32 c;
  37074. const ma_uint32 channels = pBQ->channels;
  37075. const ma_int32 b0 = pBQ->b0.s32;
  37076. const ma_int32 b1 = pBQ->b1.s32;
  37077. const ma_int32 b2 = pBQ->b2.s32;
  37078. const ma_int32 a1 = pBQ->a1.s32;
  37079. const ma_int32 a2 = pBQ->a2.s32;
  37080. MA_ASSUME(channels > 0);
  37081. for (c = 0; c < channels; c += 1) {
  37082. ma_int32 r1 = pBQ->pR1[c].s32;
  37083. ma_int32 r2 = pBQ->pR2[c].s32;
  37084. ma_int32 x = pX[c];
  37085. ma_int32 y;
  37086. y = (b0*x + r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  37087. r1 = (b1*x - a1*y + r2);
  37088. r2 = (b2*x - a2*y);
  37089. pY[c] = (ma_int16)ma_clamp(y, -32768, 32767);
  37090. pBQ->pR1[c].s32 = r1;
  37091. pBQ->pR2[c].s32 = r2;
  37092. }
  37093. }
  37094. static MA_INLINE void ma_biquad_process_pcm_frame_s16(ma_biquad* pBQ, ma_int16* pY, const ma_int16* pX)
  37095. {
  37096. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  37097. }
  37098. MA_API ma_result ma_biquad_process_pcm_frames(ma_biquad* pBQ, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  37099. {
  37100. ma_uint32 n;
  37101. if (pBQ == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  37102. return MA_INVALID_ARGS;
  37103. }
  37104. /* 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. */
  37105. if (pBQ->format == ma_format_f32) {
  37106. /* */ float* pY = ( float*)pFramesOut;
  37107. const float* pX = (const float*)pFramesIn;
  37108. for (n = 0; n < frameCount; n += 1) {
  37109. ma_biquad_process_pcm_frame_f32__direct_form_2_transposed(pBQ, pY, pX);
  37110. pY += pBQ->channels;
  37111. pX += pBQ->channels;
  37112. }
  37113. } else if (pBQ->format == ma_format_s16) {
  37114. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  37115. const ma_int16* pX = (const ma_int16*)pFramesIn;
  37116. for (n = 0; n < frameCount; n += 1) {
  37117. ma_biquad_process_pcm_frame_s16__direct_form_2_transposed(pBQ, pY, pX);
  37118. pY += pBQ->channels;
  37119. pX += pBQ->channels;
  37120. }
  37121. } else {
  37122. MA_ASSERT(MA_FALSE);
  37123. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  37124. }
  37125. return MA_SUCCESS;
  37126. }
  37127. MA_API ma_uint32 ma_biquad_get_latency(const ma_biquad* pBQ)
  37128. {
  37129. if (pBQ == NULL) {
  37130. return 0;
  37131. }
  37132. return 2;
  37133. }
  37134. /**************************************************************************************************************************************************************
  37135. Low-Pass Filter
  37136. **************************************************************************************************************************************************************/
  37137. MA_API ma_lpf1_config ma_lpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  37138. {
  37139. ma_lpf1_config config;
  37140. MA_ZERO_OBJECT(&config);
  37141. config.format = format;
  37142. config.channels = channels;
  37143. config.sampleRate = sampleRate;
  37144. config.cutoffFrequency = cutoffFrequency;
  37145. config.q = 0.5;
  37146. return config;
  37147. }
  37148. MA_API ma_lpf2_config ma_lpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  37149. {
  37150. ma_lpf2_config config;
  37151. MA_ZERO_OBJECT(&config);
  37152. config.format = format;
  37153. config.channels = channels;
  37154. config.sampleRate = sampleRate;
  37155. config.cutoffFrequency = cutoffFrequency;
  37156. config.q = q;
  37157. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  37158. if (config.q == 0) {
  37159. config.q = 0.707107;
  37160. }
  37161. return config;
  37162. }
  37163. typedef struct
  37164. {
  37165. size_t sizeInBytes;
  37166. size_t r1Offset;
  37167. } ma_lpf1_heap_layout;
  37168. static ma_result ma_lpf1_get_heap_layout(const ma_lpf1_config* pConfig, ma_lpf1_heap_layout* pHeapLayout)
  37169. {
  37170. MA_ASSERT(pHeapLayout != NULL);
  37171. MA_ZERO_OBJECT(pHeapLayout);
  37172. if (pConfig == NULL) {
  37173. return MA_INVALID_ARGS;
  37174. }
  37175. if (pConfig->channels == 0) {
  37176. return MA_INVALID_ARGS;
  37177. }
  37178. pHeapLayout->sizeInBytes = 0;
  37179. /* R1 */
  37180. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  37181. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37182. /* Make sure allocation size is aligned. */
  37183. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  37184. return MA_SUCCESS;
  37185. }
  37186. MA_API ma_result ma_lpf1_get_heap_size(const ma_lpf1_config* pConfig, size_t* pHeapSizeInBytes)
  37187. {
  37188. ma_result result;
  37189. ma_lpf1_heap_layout heapLayout;
  37190. if (pHeapSizeInBytes == NULL) {
  37191. return MA_INVALID_ARGS;
  37192. }
  37193. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  37194. if (result != MA_SUCCESS) {
  37195. return result;
  37196. }
  37197. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  37198. return MA_SUCCESS;
  37199. }
  37200. MA_API ma_result ma_lpf1_init_preallocated(const ma_lpf1_config* pConfig, void* pHeap, ma_lpf1* pLPF)
  37201. {
  37202. ma_result result;
  37203. ma_lpf1_heap_layout heapLayout;
  37204. if (pLPF == NULL) {
  37205. return MA_INVALID_ARGS;
  37206. }
  37207. MA_ZERO_OBJECT(pLPF);
  37208. result = ma_lpf1_get_heap_layout(pConfig, &heapLayout);
  37209. if (result != MA_SUCCESS) {
  37210. return result;
  37211. }
  37212. pLPF->_pHeap = pHeap;
  37213. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  37214. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  37215. return ma_lpf1_reinit(pConfig, pLPF);
  37216. }
  37217. MA_API ma_result ma_lpf1_init(const ma_lpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf1* pLPF)
  37218. {
  37219. ma_result result;
  37220. size_t heapSizeInBytes;
  37221. void* pHeap;
  37222. result = ma_lpf1_get_heap_size(pConfig, &heapSizeInBytes);
  37223. if (result != MA_SUCCESS) {
  37224. return result;
  37225. }
  37226. if (heapSizeInBytes > 0) {
  37227. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37228. if (pHeap == NULL) {
  37229. return MA_OUT_OF_MEMORY;
  37230. }
  37231. } else {
  37232. pHeap = NULL;
  37233. }
  37234. result = ma_lpf1_init_preallocated(pConfig, pHeap, pLPF);
  37235. if (result != MA_SUCCESS) {
  37236. ma_free(pHeap, pAllocationCallbacks);
  37237. return result;
  37238. }
  37239. pLPF->_ownsHeap = MA_TRUE;
  37240. return MA_SUCCESS;
  37241. }
  37242. MA_API void ma_lpf1_uninit(ma_lpf1* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  37243. {
  37244. if (pLPF == NULL) {
  37245. return;
  37246. }
  37247. if (pLPF->_ownsHeap) {
  37248. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  37249. }
  37250. }
  37251. MA_API ma_result ma_lpf1_reinit(const ma_lpf1_config* pConfig, ma_lpf1* pLPF)
  37252. {
  37253. double a;
  37254. if (pLPF == NULL || pConfig == NULL) {
  37255. return MA_INVALID_ARGS;
  37256. }
  37257. /* Only supporting f32 and s16. */
  37258. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37259. return MA_INVALID_ARGS;
  37260. }
  37261. /* The format cannot be changed after initialization. */
  37262. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  37263. return MA_INVALID_OPERATION;
  37264. }
  37265. /* The channel count cannot be changed after initialization. */
  37266. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  37267. return MA_INVALID_OPERATION;
  37268. }
  37269. pLPF->format = pConfig->format;
  37270. pLPF->channels = pConfig->channels;
  37271. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  37272. if (pConfig->format == ma_format_f32) {
  37273. pLPF->a.f32 = (float)a;
  37274. } else {
  37275. pLPF->a.s32 = ma_biquad_float_to_fp(a);
  37276. }
  37277. return MA_SUCCESS;
  37278. }
  37279. MA_API ma_result ma_lpf1_clear_cache(ma_lpf1* pLPF)
  37280. {
  37281. if (pLPF == NULL) {
  37282. return MA_INVALID_ARGS;
  37283. }
  37284. if (pLPF->format == ma_format_f32) {
  37285. pLPF->a.f32 = 0;
  37286. } else {
  37287. pLPF->a.s32 = 0;
  37288. }
  37289. return MA_SUCCESS;
  37290. }
  37291. static MA_INLINE void ma_lpf1_process_pcm_frame_f32(ma_lpf1* pLPF, float* pY, const float* pX)
  37292. {
  37293. ma_uint32 c;
  37294. const ma_uint32 channels = pLPF->channels;
  37295. const float a = pLPF->a.f32;
  37296. const float b = 1 - a;
  37297. MA_ASSUME(channels > 0);
  37298. for (c = 0; c < channels; c += 1) {
  37299. float r1 = pLPF->pR1[c].f32;
  37300. float x = pX[c];
  37301. float y;
  37302. y = b*x + a*r1;
  37303. pY[c] = y;
  37304. pLPF->pR1[c].f32 = y;
  37305. }
  37306. }
  37307. static MA_INLINE void ma_lpf1_process_pcm_frame_s16(ma_lpf1* pLPF, ma_int16* pY, const ma_int16* pX)
  37308. {
  37309. ma_uint32 c;
  37310. const ma_uint32 channels = pLPF->channels;
  37311. const ma_int32 a = pLPF->a.s32;
  37312. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  37313. MA_ASSUME(channels > 0);
  37314. for (c = 0; c < channels; c += 1) {
  37315. ma_int32 r1 = pLPF->pR1[c].s32;
  37316. ma_int32 x = pX[c];
  37317. ma_int32 y;
  37318. y = (b*x + a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  37319. pY[c] = (ma_int16)y;
  37320. pLPF->pR1[c].s32 = (ma_int32)y;
  37321. }
  37322. }
  37323. MA_API ma_result ma_lpf1_process_pcm_frames(ma_lpf1* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  37324. {
  37325. ma_uint32 n;
  37326. if (pLPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  37327. return MA_INVALID_ARGS;
  37328. }
  37329. /* 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. */
  37330. if (pLPF->format == ma_format_f32) {
  37331. /* */ float* pY = ( float*)pFramesOut;
  37332. const float* pX = (const float*)pFramesIn;
  37333. for (n = 0; n < frameCount; n += 1) {
  37334. ma_lpf1_process_pcm_frame_f32(pLPF, pY, pX);
  37335. pY += pLPF->channels;
  37336. pX += pLPF->channels;
  37337. }
  37338. } else if (pLPF->format == ma_format_s16) {
  37339. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  37340. const ma_int16* pX = (const ma_int16*)pFramesIn;
  37341. for (n = 0; n < frameCount; n += 1) {
  37342. ma_lpf1_process_pcm_frame_s16(pLPF, pY, pX);
  37343. pY += pLPF->channels;
  37344. pX += pLPF->channels;
  37345. }
  37346. } else {
  37347. MA_ASSERT(MA_FALSE);
  37348. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  37349. }
  37350. return MA_SUCCESS;
  37351. }
  37352. MA_API ma_uint32 ma_lpf1_get_latency(const ma_lpf1* pLPF)
  37353. {
  37354. if (pLPF == NULL) {
  37355. return 0;
  37356. }
  37357. return 1;
  37358. }
  37359. static MA_INLINE ma_biquad_config ma_lpf2__get_biquad_config(const ma_lpf2_config* pConfig)
  37360. {
  37361. ma_biquad_config bqConfig;
  37362. double q;
  37363. double w;
  37364. double s;
  37365. double c;
  37366. double a;
  37367. MA_ASSERT(pConfig != NULL);
  37368. q = pConfig->q;
  37369. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  37370. s = ma_sind(w);
  37371. c = ma_cosd(w);
  37372. a = s / (2*q);
  37373. bqConfig.b0 = (1 - c) / 2;
  37374. bqConfig.b1 = 1 - c;
  37375. bqConfig.b2 = (1 - c) / 2;
  37376. bqConfig.a0 = 1 + a;
  37377. bqConfig.a1 = -2 * c;
  37378. bqConfig.a2 = 1 - a;
  37379. bqConfig.format = pConfig->format;
  37380. bqConfig.channels = pConfig->channels;
  37381. return bqConfig;
  37382. }
  37383. MA_API ma_result ma_lpf2_get_heap_size(const ma_lpf2_config* pConfig, size_t* pHeapSizeInBytes)
  37384. {
  37385. ma_biquad_config bqConfig;
  37386. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  37387. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  37388. }
  37389. MA_API ma_result ma_lpf2_init_preallocated(const ma_lpf2_config* pConfig, void* pHeap, ma_lpf2* pLPF)
  37390. {
  37391. ma_result result;
  37392. ma_biquad_config bqConfig;
  37393. if (pLPF == NULL) {
  37394. return MA_INVALID_ARGS;
  37395. }
  37396. MA_ZERO_OBJECT(pLPF);
  37397. if (pConfig == NULL) {
  37398. return MA_INVALID_ARGS;
  37399. }
  37400. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  37401. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pLPF->bq);
  37402. if (result != MA_SUCCESS) {
  37403. return result;
  37404. }
  37405. return MA_SUCCESS;
  37406. }
  37407. MA_API ma_result ma_lpf2_init(const ma_lpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf2* pLPF)
  37408. {
  37409. ma_result result;
  37410. size_t heapSizeInBytes;
  37411. void* pHeap;
  37412. result = ma_lpf2_get_heap_size(pConfig, &heapSizeInBytes);
  37413. if (result != MA_SUCCESS) {
  37414. return result;
  37415. }
  37416. if (heapSizeInBytes > 0) {
  37417. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37418. if (pHeap == NULL) {
  37419. return MA_OUT_OF_MEMORY;
  37420. }
  37421. } else {
  37422. pHeap = NULL;
  37423. }
  37424. result = ma_lpf2_init_preallocated(pConfig, pHeap, pLPF);
  37425. if (result != MA_SUCCESS) {
  37426. ma_free(pHeap, pAllocationCallbacks);
  37427. return result;
  37428. }
  37429. pLPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  37430. return MA_SUCCESS;
  37431. }
  37432. MA_API void ma_lpf2_uninit(ma_lpf2* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  37433. {
  37434. if (pLPF == NULL) {
  37435. return;
  37436. }
  37437. ma_biquad_uninit(&pLPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  37438. }
  37439. MA_API ma_result ma_lpf2_reinit(const ma_lpf2_config* pConfig, ma_lpf2* pLPF)
  37440. {
  37441. ma_result result;
  37442. ma_biquad_config bqConfig;
  37443. if (pLPF == NULL || pConfig == NULL) {
  37444. return MA_INVALID_ARGS;
  37445. }
  37446. bqConfig = ma_lpf2__get_biquad_config(pConfig);
  37447. result = ma_biquad_reinit(&bqConfig, &pLPF->bq);
  37448. if (result != MA_SUCCESS) {
  37449. return result;
  37450. }
  37451. return MA_SUCCESS;
  37452. }
  37453. MA_API ma_result ma_lpf2_clear_cache(ma_lpf2* pLPF)
  37454. {
  37455. if (pLPF == NULL) {
  37456. return MA_INVALID_ARGS;
  37457. }
  37458. ma_biquad_clear_cache(&pLPF->bq);
  37459. return MA_SUCCESS;
  37460. }
  37461. static MA_INLINE void ma_lpf2_process_pcm_frame_s16(ma_lpf2* pLPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  37462. {
  37463. ma_biquad_process_pcm_frame_s16(&pLPF->bq, pFrameOut, pFrameIn);
  37464. }
  37465. static MA_INLINE void ma_lpf2_process_pcm_frame_f32(ma_lpf2* pLPF, float* pFrameOut, const float* pFrameIn)
  37466. {
  37467. ma_biquad_process_pcm_frame_f32(&pLPF->bq, pFrameOut, pFrameIn);
  37468. }
  37469. MA_API ma_result ma_lpf2_process_pcm_frames(ma_lpf2* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  37470. {
  37471. if (pLPF == NULL) {
  37472. return MA_INVALID_ARGS;
  37473. }
  37474. return ma_biquad_process_pcm_frames(&pLPF->bq, pFramesOut, pFramesIn, frameCount);
  37475. }
  37476. MA_API ma_uint32 ma_lpf2_get_latency(const ma_lpf2* pLPF)
  37477. {
  37478. if (pLPF == NULL) {
  37479. return 0;
  37480. }
  37481. return ma_biquad_get_latency(&pLPF->bq);
  37482. }
  37483. MA_API ma_lpf_config ma_lpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  37484. {
  37485. ma_lpf_config config;
  37486. MA_ZERO_OBJECT(&config);
  37487. config.format = format;
  37488. config.channels = channels;
  37489. config.sampleRate = sampleRate;
  37490. config.cutoffFrequency = cutoffFrequency;
  37491. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  37492. return config;
  37493. }
  37494. typedef struct
  37495. {
  37496. size_t sizeInBytes;
  37497. size_t lpf1Offset;
  37498. size_t lpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  37499. } ma_lpf_heap_layout;
  37500. static void ma_lpf_calculate_sub_lpf_counts(ma_uint32 order, ma_uint32* pLPF1Count, ma_uint32* pLPF2Count)
  37501. {
  37502. MA_ASSERT(pLPF1Count != NULL);
  37503. MA_ASSERT(pLPF2Count != NULL);
  37504. *pLPF1Count = order % 2;
  37505. *pLPF2Count = order / 2;
  37506. }
  37507. static ma_result ma_lpf_get_heap_layout(const ma_lpf_config* pConfig, ma_lpf_heap_layout* pHeapLayout)
  37508. {
  37509. ma_result result;
  37510. ma_uint32 lpf1Count;
  37511. ma_uint32 lpf2Count;
  37512. ma_uint32 ilpf1;
  37513. ma_uint32 ilpf2;
  37514. MA_ASSERT(pHeapLayout != NULL);
  37515. MA_ZERO_OBJECT(pHeapLayout);
  37516. if (pConfig == NULL) {
  37517. return MA_INVALID_ARGS;
  37518. }
  37519. if (pConfig->channels == 0) {
  37520. return MA_INVALID_ARGS;
  37521. }
  37522. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  37523. return MA_INVALID_ARGS;
  37524. }
  37525. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  37526. pHeapLayout->sizeInBytes = 0;
  37527. /* LPF 1 */
  37528. pHeapLayout->lpf1Offset = pHeapLayout->sizeInBytes;
  37529. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  37530. size_t lpf1HeapSizeInBytes;
  37531. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  37532. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  37533. if (result != MA_SUCCESS) {
  37534. return result;
  37535. }
  37536. pHeapLayout->sizeInBytes += sizeof(ma_lpf1) + lpf1HeapSizeInBytes;
  37537. }
  37538. /* LPF 2*/
  37539. pHeapLayout->lpf2Offset = pHeapLayout->sizeInBytes;
  37540. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  37541. size_t lpf2HeapSizeInBytes;
  37542. 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. */
  37543. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  37544. if (result != MA_SUCCESS) {
  37545. return result;
  37546. }
  37547. pHeapLayout->sizeInBytes += sizeof(ma_lpf2) + lpf2HeapSizeInBytes;
  37548. }
  37549. /* Make sure allocation size is aligned. */
  37550. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  37551. return MA_SUCCESS;
  37552. }
  37553. static ma_result ma_lpf_reinit__internal(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF, ma_bool32 isNew)
  37554. {
  37555. ma_result result;
  37556. ma_uint32 lpf1Count;
  37557. ma_uint32 lpf2Count;
  37558. ma_uint32 ilpf1;
  37559. ma_uint32 ilpf2;
  37560. ma_lpf_heap_layout heapLayout; /* Only used if isNew is true. */
  37561. if (pLPF == NULL || pConfig == NULL) {
  37562. return MA_INVALID_ARGS;
  37563. }
  37564. /* Only supporting f32 and s16. */
  37565. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37566. return MA_INVALID_ARGS;
  37567. }
  37568. /* The format cannot be changed after initialization. */
  37569. if (pLPF->format != ma_format_unknown && pLPF->format != pConfig->format) {
  37570. return MA_INVALID_OPERATION;
  37571. }
  37572. /* The channel count cannot be changed after initialization. */
  37573. if (pLPF->channels != 0 && pLPF->channels != pConfig->channels) {
  37574. return MA_INVALID_OPERATION;
  37575. }
  37576. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  37577. return MA_INVALID_ARGS;
  37578. }
  37579. ma_lpf_calculate_sub_lpf_counts(pConfig->order, &lpf1Count, &lpf2Count);
  37580. /* The filter order can't change between reinits. */
  37581. if (!isNew) {
  37582. if (pLPF->lpf1Count != lpf1Count || pLPF->lpf2Count != lpf2Count) {
  37583. return MA_INVALID_OPERATION;
  37584. }
  37585. }
  37586. if (isNew) {
  37587. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  37588. if (result != MA_SUCCESS) {
  37589. return result;
  37590. }
  37591. pLPF->_pHeap = pHeap;
  37592. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  37593. pLPF->pLPF1 = (ma_lpf1*)ma_offset_ptr(pHeap, heapLayout.lpf1Offset);
  37594. pLPF->pLPF2 = (ma_lpf2*)ma_offset_ptr(pHeap, heapLayout.lpf2Offset);
  37595. } else {
  37596. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  37597. }
  37598. for (ilpf1 = 0; ilpf1 < lpf1Count; ilpf1 += 1) {
  37599. ma_lpf1_config lpf1Config = ma_lpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  37600. if (isNew) {
  37601. size_t lpf1HeapSizeInBytes;
  37602. result = ma_lpf1_get_heap_size(&lpf1Config, &lpf1HeapSizeInBytes);
  37603. if (result == MA_SUCCESS) {
  37604. result = ma_lpf1_init_preallocated(&lpf1Config, ma_offset_ptr(pHeap, heapLayout.lpf1Offset + (sizeof(ma_lpf1) * lpf1Count) + (ilpf1 * lpf1HeapSizeInBytes)), &pLPF->pLPF1[ilpf1]);
  37605. }
  37606. } else {
  37607. result = ma_lpf1_reinit(&lpf1Config, &pLPF->pLPF1[ilpf1]);
  37608. }
  37609. if (result != MA_SUCCESS) {
  37610. ma_uint32 jlpf1;
  37611. for (jlpf1 = 0; jlpf1 < ilpf1; jlpf1 += 1) {
  37612. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  37613. }
  37614. return result;
  37615. }
  37616. }
  37617. for (ilpf2 = 0; ilpf2 < lpf2Count; ilpf2 += 1) {
  37618. ma_lpf2_config lpf2Config;
  37619. double q;
  37620. double a;
  37621. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  37622. if (lpf1Count == 1) {
  37623. a = (1 + ilpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  37624. } else {
  37625. a = (1 + ilpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  37626. }
  37627. q = 1 / (2*ma_cosd(a));
  37628. lpf2Config = ma_lpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  37629. if (isNew) {
  37630. size_t lpf2HeapSizeInBytes;
  37631. result = ma_lpf2_get_heap_size(&lpf2Config, &lpf2HeapSizeInBytes);
  37632. if (result == MA_SUCCESS) {
  37633. result = ma_lpf2_init_preallocated(&lpf2Config, ma_offset_ptr(pHeap, heapLayout.lpf2Offset + (sizeof(ma_lpf2) * lpf2Count) + (ilpf2 * lpf2HeapSizeInBytes)), &pLPF->pLPF2[ilpf2]);
  37634. }
  37635. } else {
  37636. result = ma_lpf2_reinit(&lpf2Config, &pLPF->pLPF2[ilpf2]);
  37637. }
  37638. if (result != MA_SUCCESS) {
  37639. ma_uint32 jlpf1;
  37640. ma_uint32 jlpf2;
  37641. for (jlpf1 = 0; jlpf1 < lpf1Count; jlpf1 += 1) {
  37642. ma_lpf1_uninit(&pLPF->pLPF1[jlpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  37643. }
  37644. for (jlpf2 = 0; jlpf2 < ilpf2; jlpf2 += 1) {
  37645. ma_lpf2_uninit(&pLPF->pLPF2[jlpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  37646. }
  37647. return result;
  37648. }
  37649. }
  37650. pLPF->lpf1Count = lpf1Count;
  37651. pLPF->lpf2Count = lpf2Count;
  37652. pLPF->format = pConfig->format;
  37653. pLPF->channels = pConfig->channels;
  37654. pLPF->sampleRate = pConfig->sampleRate;
  37655. return MA_SUCCESS;
  37656. }
  37657. MA_API ma_result ma_lpf_get_heap_size(const ma_lpf_config* pConfig, size_t* pHeapSizeInBytes)
  37658. {
  37659. ma_result result;
  37660. ma_lpf_heap_layout heapLayout;
  37661. if (pHeapSizeInBytes == NULL) {
  37662. return MA_INVALID_ARGS;
  37663. }
  37664. *pHeapSizeInBytes = 0;
  37665. result = ma_lpf_get_heap_layout(pConfig, &heapLayout);
  37666. if (result != MA_SUCCESS) {
  37667. return result;
  37668. }
  37669. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  37670. return result;
  37671. }
  37672. MA_API ma_result ma_lpf_init_preallocated(const ma_lpf_config* pConfig, void* pHeap, ma_lpf* pLPF)
  37673. {
  37674. if (pLPF == NULL) {
  37675. return MA_INVALID_ARGS;
  37676. }
  37677. MA_ZERO_OBJECT(pLPF);
  37678. return ma_lpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  37679. }
  37680. MA_API ma_result ma_lpf_init(const ma_lpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_lpf* pLPF)
  37681. {
  37682. ma_result result;
  37683. size_t heapSizeInBytes;
  37684. void* pHeap;
  37685. result = ma_lpf_get_heap_size(pConfig, &heapSizeInBytes);
  37686. if (result != MA_SUCCESS) {
  37687. return result;
  37688. }
  37689. if (heapSizeInBytes > 0) {
  37690. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37691. if (pHeap == NULL) {
  37692. return MA_OUT_OF_MEMORY;
  37693. }
  37694. } else {
  37695. pHeap = NULL;
  37696. }
  37697. result = ma_lpf_init_preallocated(pConfig, pHeap, pLPF);
  37698. if (result != MA_SUCCESS) {
  37699. ma_free(pHeap, pAllocationCallbacks);
  37700. return result;
  37701. }
  37702. pLPF->_ownsHeap = MA_TRUE;
  37703. return MA_SUCCESS;
  37704. }
  37705. MA_API void ma_lpf_uninit(ma_lpf* pLPF, const ma_allocation_callbacks* pAllocationCallbacks)
  37706. {
  37707. ma_uint32 ilpf1;
  37708. ma_uint32 ilpf2;
  37709. if (pLPF == NULL) {
  37710. return;
  37711. }
  37712. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  37713. ma_lpf1_uninit(&pLPF->pLPF1[ilpf1], pAllocationCallbacks);
  37714. }
  37715. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  37716. ma_lpf2_uninit(&pLPF->pLPF2[ilpf2], pAllocationCallbacks);
  37717. }
  37718. if (pLPF->_ownsHeap) {
  37719. ma_free(pLPF->_pHeap, pAllocationCallbacks);
  37720. }
  37721. }
  37722. MA_API ma_result ma_lpf_reinit(const ma_lpf_config* pConfig, ma_lpf* pLPF)
  37723. {
  37724. return ma_lpf_reinit__internal(pConfig, NULL, pLPF, /*isNew*/MA_FALSE);
  37725. }
  37726. MA_API ma_result ma_lpf_clear_cache(ma_lpf* pLPF)
  37727. {
  37728. ma_uint32 ilpf1;
  37729. ma_uint32 ilpf2;
  37730. if (pLPF == NULL) {
  37731. return MA_INVALID_ARGS;
  37732. }
  37733. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  37734. ma_lpf1_clear_cache(&pLPF->pLPF1[ilpf1]);
  37735. }
  37736. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  37737. ma_lpf2_clear_cache(&pLPF->pLPF2[ilpf2]);
  37738. }
  37739. return MA_SUCCESS;
  37740. }
  37741. static MA_INLINE void ma_lpf_process_pcm_frame_f32(ma_lpf* pLPF, float* pY, const void* pX)
  37742. {
  37743. ma_uint32 ilpf1;
  37744. ma_uint32 ilpf2;
  37745. MA_ASSERT(pLPF->format == ma_format_f32);
  37746. MA_COPY_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  37747. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  37748. ma_lpf1_process_pcm_frame_f32(&pLPF->pLPF1[ilpf1], pY, pY);
  37749. }
  37750. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  37751. ma_lpf2_process_pcm_frame_f32(&pLPF->pLPF2[ilpf2], pY, pY);
  37752. }
  37753. }
  37754. static MA_INLINE void ma_lpf_process_pcm_frame_s16(ma_lpf* pLPF, ma_int16* pY, const ma_int16* pX)
  37755. {
  37756. ma_uint32 ilpf1;
  37757. ma_uint32 ilpf2;
  37758. MA_ASSERT(pLPF->format == ma_format_s16);
  37759. MA_COPY_MEMORY(pY, pX, ma_get_bytes_per_frame(pLPF->format, pLPF->channels));
  37760. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  37761. ma_lpf1_process_pcm_frame_s16(&pLPF->pLPF1[ilpf1], pY, pY);
  37762. }
  37763. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  37764. ma_lpf2_process_pcm_frame_s16(&pLPF->pLPF2[ilpf2], pY, pY);
  37765. }
  37766. }
  37767. MA_API ma_result ma_lpf_process_pcm_frames(ma_lpf* pLPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  37768. {
  37769. ma_result result;
  37770. ma_uint32 ilpf1;
  37771. ma_uint32 ilpf2;
  37772. if (pLPF == NULL) {
  37773. return MA_INVALID_ARGS;
  37774. }
  37775. /* Faster path for in-place. */
  37776. if (pFramesOut == pFramesIn) {
  37777. for (ilpf1 = 0; ilpf1 < pLPF->lpf1Count; ilpf1 += 1) {
  37778. result = ma_lpf1_process_pcm_frames(&pLPF->pLPF1[ilpf1], pFramesOut, pFramesOut, frameCount);
  37779. if (result != MA_SUCCESS) {
  37780. return result;
  37781. }
  37782. }
  37783. for (ilpf2 = 0; ilpf2 < pLPF->lpf2Count; ilpf2 += 1) {
  37784. result = ma_lpf2_process_pcm_frames(&pLPF->pLPF2[ilpf2], pFramesOut, pFramesOut, frameCount);
  37785. if (result != MA_SUCCESS) {
  37786. return result;
  37787. }
  37788. }
  37789. }
  37790. /* Slightly slower path for copying. */
  37791. if (pFramesOut != pFramesIn) {
  37792. ma_uint32 iFrame;
  37793. /* */ if (pLPF->format == ma_format_f32) {
  37794. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  37795. const float* pFramesInF32 = (const float*)pFramesIn;
  37796. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37797. ma_lpf_process_pcm_frame_f32(pLPF, pFramesOutF32, pFramesInF32);
  37798. pFramesOutF32 += pLPF->channels;
  37799. pFramesInF32 += pLPF->channels;
  37800. }
  37801. } else if (pLPF->format == ma_format_s16) {
  37802. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  37803. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  37804. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  37805. ma_lpf_process_pcm_frame_s16(pLPF, pFramesOutS16, pFramesInS16);
  37806. pFramesOutS16 += pLPF->channels;
  37807. pFramesInS16 += pLPF->channels;
  37808. }
  37809. } else {
  37810. MA_ASSERT(MA_FALSE);
  37811. return MA_INVALID_OPERATION; /* Should never hit this. */
  37812. }
  37813. }
  37814. return MA_SUCCESS;
  37815. }
  37816. MA_API ma_uint32 ma_lpf_get_latency(const ma_lpf* pLPF)
  37817. {
  37818. if (pLPF == NULL) {
  37819. return 0;
  37820. }
  37821. return pLPF->lpf2Count*2 + pLPF->lpf1Count;
  37822. }
  37823. /**************************************************************************************************************************************************************
  37824. High-Pass Filtering
  37825. **************************************************************************************************************************************************************/
  37826. MA_API ma_hpf1_config ma_hpf1_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency)
  37827. {
  37828. ma_hpf1_config config;
  37829. MA_ZERO_OBJECT(&config);
  37830. config.format = format;
  37831. config.channels = channels;
  37832. config.sampleRate = sampleRate;
  37833. config.cutoffFrequency = cutoffFrequency;
  37834. return config;
  37835. }
  37836. MA_API ma_hpf2_config ma_hpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  37837. {
  37838. ma_hpf2_config config;
  37839. MA_ZERO_OBJECT(&config);
  37840. config.format = format;
  37841. config.channels = channels;
  37842. config.sampleRate = sampleRate;
  37843. config.cutoffFrequency = cutoffFrequency;
  37844. config.q = q;
  37845. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  37846. if (config.q == 0) {
  37847. config.q = 0.707107;
  37848. }
  37849. return config;
  37850. }
  37851. typedef struct
  37852. {
  37853. size_t sizeInBytes;
  37854. size_t r1Offset;
  37855. } ma_hpf1_heap_layout;
  37856. static ma_result ma_hpf1_get_heap_layout(const ma_hpf1_config* pConfig, ma_hpf1_heap_layout* pHeapLayout)
  37857. {
  37858. MA_ASSERT(pHeapLayout != NULL);
  37859. MA_ZERO_OBJECT(pHeapLayout);
  37860. if (pConfig == NULL) {
  37861. return MA_INVALID_ARGS;
  37862. }
  37863. if (pConfig->channels == 0) {
  37864. return MA_INVALID_ARGS;
  37865. }
  37866. pHeapLayout->sizeInBytes = 0;
  37867. /* R1 */
  37868. pHeapLayout->r1Offset = pHeapLayout->sizeInBytes;
  37869. pHeapLayout->sizeInBytes += sizeof(ma_biquad_coefficient) * pConfig->channels;
  37870. /* Make sure allocation size is aligned. */
  37871. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  37872. return MA_SUCCESS;
  37873. }
  37874. MA_API ma_result ma_hpf1_get_heap_size(const ma_hpf1_config* pConfig, size_t* pHeapSizeInBytes)
  37875. {
  37876. ma_result result;
  37877. ma_hpf1_heap_layout heapLayout;
  37878. if (pHeapSizeInBytes == NULL) {
  37879. return MA_INVALID_ARGS;
  37880. }
  37881. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  37882. if (result != MA_SUCCESS) {
  37883. return result;
  37884. }
  37885. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  37886. return MA_SUCCESS;
  37887. }
  37888. MA_API ma_result ma_hpf1_init_preallocated(const ma_hpf1_config* pConfig, void* pHeap, ma_hpf1* pLPF)
  37889. {
  37890. ma_result result;
  37891. ma_hpf1_heap_layout heapLayout;
  37892. if (pLPF == NULL) {
  37893. return MA_INVALID_ARGS;
  37894. }
  37895. MA_ZERO_OBJECT(pLPF);
  37896. result = ma_hpf1_get_heap_layout(pConfig, &heapLayout);
  37897. if (result != MA_SUCCESS) {
  37898. return result;
  37899. }
  37900. pLPF->_pHeap = pHeap;
  37901. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  37902. pLPF->pR1 = (ma_biquad_coefficient*)ma_offset_ptr(pHeap, heapLayout.r1Offset);
  37903. return ma_hpf1_reinit(pConfig, pLPF);
  37904. }
  37905. MA_API ma_result ma_hpf1_init(const ma_hpf1_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf1* pLPF)
  37906. {
  37907. ma_result result;
  37908. size_t heapSizeInBytes;
  37909. void* pHeap;
  37910. result = ma_hpf1_get_heap_size(pConfig, &heapSizeInBytes);
  37911. if (result != MA_SUCCESS) {
  37912. return result;
  37913. }
  37914. if (heapSizeInBytes > 0) {
  37915. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  37916. if (pHeap == NULL) {
  37917. return MA_OUT_OF_MEMORY;
  37918. }
  37919. } else {
  37920. pHeap = NULL;
  37921. }
  37922. result = ma_hpf1_init_preallocated(pConfig, pHeap, pLPF);
  37923. if (result != MA_SUCCESS) {
  37924. ma_free(pHeap, pAllocationCallbacks);
  37925. return result;
  37926. }
  37927. pLPF->_ownsHeap = MA_TRUE;
  37928. return MA_SUCCESS;
  37929. }
  37930. MA_API void ma_hpf1_uninit(ma_hpf1* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  37931. {
  37932. if (pHPF == NULL) {
  37933. return;
  37934. }
  37935. if (pHPF->_ownsHeap) {
  37936. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  37937. }
  37938. }
  37939. MA_API ma_result ma_hpf1_reinit(const ma_hpf1_config* pConfig, ma_hpf1* pHPF)
  37940. {
  37941. double a;
  37942. if (pHPF == NULL || pConfig == NULL) {
  37943. return MA_INVALID_ARGS;
  37944. }
  37945. /* Only supporting f32 and s16. */
  37946. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  37947. return MA_INVALID_ARGS;
  37948. }
  37949. /* The format cannot be changed after initialization. */
  37950. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  37951. return MA_INVALID_OPERATION;
  37952. }
  37953. /* The channel count cannot be changed after initialization. */
  37954. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  37955. return MA_INVALID_OPERATION;
  37956. }
  37957. pHPF->format = pConfig->format;
  37958. pHPF->channels = pConfig->channels;
  37959. a = ma_expd(-2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate);
  37960. if (pConfig->format == ma_format_f32) {
  37961. pHPF->a.f32 = (float)a;
  37962. } else {
  37963. pHPF->a.s32 = ma_biquad_float_to_fp(a);
  37964. }
  37965. return MA_SUCCESS;
  37966. }
  37967. static MA_INLINE void ma_hpf1_process_pcm_frame_f32(ma_hpf1* pHPF, float* pY, const float* pX)
  37968. {
  37969. ma_uint32 c;
  37970. const ma_uint32 channels = pHPF->channels;
  37971. const float a = 1 - pHPF->a.f32;
  37972. const float b = 1 - a;
  37973. MA_ASSUME(channels > 0);
  37974. for (c = 0; c < channels; c += 1) {
  37975. float r1 = pHPF->pR1[c].f32;
  37976. float x = pX[c];
  37977. float y;
  37978. y = b*x - a*r1;
  37979. pY[c] = y;
  37980. pHPF->pR1[c].f32 = y;
  37981. }
  37982. }
  37983. static MA_INLINE void ma_hpf1_process_pcm_frame_s16(ma_hpf1* pHPF, ma_int16* pY, const ma_int16* pX)
  37984. {
  37985. ma_uint32 c;
  37986. const ma_uint32 channels = pHPF->channels;
  37987. const ma_int32 a = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - pHPF->a.s32);
  37988. const ma_int32 b = ((1 << MA_BIQUAD_FIXED_POINT_SHIFT) - a);
  37989. MA_ASSUME(channels > 0);
  37990. for (c = 0; c < channels; c += 1) {
  37991. ma_int32 r1 = pHPF->pR1[c].s32;
  37992. ma_int32 x = pX[c];
  37993. ma_int32 y;
  37994. y = (b*x - a*r1) >> MA_BIQUAD_FIXED_POINT_SHIFT;
  37995. pY[c] = (ma_int16)y;
  37996. pHPF->pR1[c].s32 = (ma_int32)y;
  37997. }
  37998. }
  37999. MA_API ma_result ma_hpf1_process_pcm_frames(ma_hpf1* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38000. {
  38001. ma_uint32 n;
  38002. if (pHPF == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  38003. return MA_INVALID_ARGS;
  38004. }
  38005. /* 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. */
  38006. if (pHPF->format == ma_format_f32) {
  38007. /* */ float* pY = ( float*)pFramesOut;
  38008. const float* pX = (const float*)pFramesIn;
  38009. for (n = 0; n < frameCount; n += 1) {
  38010. ma_hpf1_process_pcm_frame_f32(pHPF, pY, pX);
  38011. pY += pHPF->channels;
  38012. pX += pHPF->channels;
  38013. }
  38014. } else if (pHPF->format == ma_format_s16) {
  38015. /* */ ma_int16* pY = ( ma_int16*)pFramesOut;
  38016. const ma_int16* pX = (const ma_int16*)pFramesIn;
  38017. for (n = 0; n < frameCount; n += 1) {
  38018. ma_hpf1_process_pcm_frame_s16(pHPF, pY, pX);
  38019. pY += pHPF->channels;
  38020. pX += pHPF->channels;
  38021. }
  38022. } else {
  38023. MA_ASSERT(MA_FALSE);
  38024. return MA_INVALID_ARGS; /* Format not supported. Should never hit this because it's checked in ma_biquad_init() and ma_biquad_reinit(). */
  38025. }
  38026. return MA_SUCCESS;
  38027. }
  38028. MA_API ma_uint32 ma_hpf1_get_latency(const ma_hpf1* pHPF)
  38029. {
  38030. if (pHPF == NULL) {
  38031. return 0;
  38032. }
  38033. return 1;
  38034. }
  38035. static MA_INLINE ma_biquad_config ma_hpf2__get_biquad_config(const ma_hpf2_config* pConfig)
  38036. {
  38037. ma_biquad_config bqConfig;
  38038. double q;
  38039. double w;
  38040. double s;
  38041. double c;
  38042. double a;
  38043. MA_ASSERT(pConfig != NULL);
  38044. q = pConfig->q;
  38045. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38046. s = ma_sind(w);
  38047. c = ma_cosd(w);
  38048. a = s / (2*q);
  38049. bqConfig.b0 = (1 + c) / 2;
  38050. bqConfig.b1 = -(1 + c);
  38051. bqConfig.b2 = (1 + c) / 2;
  38052. bqConfig.a0 = 1 + a;
  38053. bqConfig.a1 = -2 * c;
  38054. bqConfig.a2 = 1 - a;
  38055. bqConfig.format = pConfig->format;
  38056. bqConfig.channels = pConfig->channels;
  38057. return bqConfig;
  38058. }
  38059. MA_API ma_result ma_hpf2_get_heap_size(const ma_hpf2_config* pConfig, size_t* pHeapSizeInBytes)
  38060. {
  38061. ma_biquad_config bqConfig;
  38062. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  38063. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38064. }
  38065. MA_API ma_result ma_hpf2_init_preallocated(const ma_hpf2_config* pConfig, void* pHeap, ma_hpf2* pHPF)
  38066. {
  38067. ma_result result;
  38068. ma_biquad_config bqConfig;
  38069. if (pHPF == NULL) {
  38070. return MA_INVALID_ARGS;
  38071. }
  38072. MA_ZERO_OBJECT(pHPF);
  38073. if (pConfig == NULL) {
  38074. return MA_INVALID_ARGS;
  38075. }
  38076. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  38077. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pHPF->bq);
  38078. if (result != MA_SUCCESS) {
  38079. return result;
  38080. }
  38081. return MA_SUCCESS;
  38082. }
  38083. MA_API ma_result ma_hpf2_init(const ma_hpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf2* pHPF)
  38084. {
  38085. ma_result result;
  38086. size_t heapSizeInBytes;
  38087. void* pHeap;
  38088. result = ma_hpf2_get_heap_size(pConfig, &heapSizeInBytes);
  38089. if (result != MA_SUCCESS) {
  38090. return result;
  38091. }
  38092. if (heapSizeInBytes > 0) {
  38093. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38094. if (pHeap == NULL) {
  38095. return MA_OUT_OF_MEMORY;
  38096. }
  38097. } else {
  38098. pHeap = NULL;
  38099. }
  38100. result = ma_hpf2_init_preallocated(pConfig, pHeap, pHPF);
  38101. if (result != MA_SUCCESS) {
  38102. ma_free(pHeap, pAllocationCallbacks);
  38103. return result;
  38104. }
  38105. pHPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  38106. return MA_SUCCESS;
  38107. }
  38108. MA_API void ma_hpf2_uninit(ma_hpf2* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38109. {
  38110. if (pHPF == NULL) {
  38111. return;
  38112. }
  38113. ma_biquad_uninit(&pHPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  38114. }
  38115. MA_API ma_result ma_hpf2_reinit(const ma_hpf2_config* pConfig, ma_hpf2* pHPF)
  38116. {
  38117. ma_result result;
  38118. ma_biquad_config bqConfig;
  38119. if (pHPF == NULL || pConfig == NULL) {
  38120. return MA_INVALID_ARGS;
  38121. }
  38122. bqConfig = ma_hpf2__get_biquad_config(pConfig);
  38123. result = ma_biquad_reinit(&bqConfig, &pHPF->bq);
  38124. if (result != MA_SUCCESS) {
  38125. return result;
  38126. }
  38127. return MA_SUCCESS;
  38128. }
  38129. static MA_INLINE void ma_hpf2_process_pcm_frame_s16(ma_hpf2* pHPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  38130. {
  38131. ma_biquad_process_pcm_frame_s16(&pHPF->bq, pFrameOut, pFrameIn);
  38132. }
  38133. static MA_INLINE void ma_hpf2_process_pcm_frame_f32(ma_hpf2* pHPF, float* pFrameOut, const float* pFrameIn)
  38134. {
  38135. ma_biquad_process_pcm_frame_f32(&pHPF->bq, pFrameOut, pFrameIn);
  38136. }
  38137. MA_API ma_result ma_hpf2_process_pcm_frames(ma_hpf2* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38138. {
  38139. if (pHPF == NULL) {
  38140. return MA_INVALID_ARGS;
  38141. }
  38142. return ma_biquad_process_pcm_frames(&pHPF->bq, pFramesOut, pFramesIn, frameCount);
  38143. }
  38144. MA_API ma_uint32 ma_hpf2_get_latency(const ma_hpf2* pHPF)
  38145. {
  38146. if (pHPF == NULL) {
  38147. return 0;
  38148. }
  38149. return ma_biquad_get_latency(&pHPF->bq);
  38150. }
  38151. MA_API ma_hpf_config ma_hpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  38152. {
  38153. ma_hpf_config config;
  38154. MA_ZERO_OBJECT(&config);
  38155. config.format = format;
  38156. config.channels = channels;
  38157. config.sampleRate = sampleRate;
  38158. config.cutoffFrequency = cutoffFrequency;
  38159. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  38160. return config;
  38161. }
  38162. typedef struct
  38163. {
  38164. size_t sizeInBytes;
  38165. size_t hpf1Offset;
  38166. size_t hpf2Offset; /* Offset of the first second order filter. Subsequent filters will come straight after, and will each have the same heap size. */
  38167. } ma_hpf_heap_layout;
  38168. static void ma_hpf_calculate_sub_hpf_counts(ma_uint32 order, ma_uint32* pHPF1Count, ma_uint32* pHPF2Count)
  38169. {
  38170. MA_ASSERT(pHPF1Count != NULL);
  38171. MA_ASSERT(pHPF2Count != NULL);
  38172. *pHPF1Count = order % 2;
  38173. *pHPF2Count = order / 2;
  38174. }
  38175. static ma_result ma_hpf_get_heap_layout(const ma_hpf_config* pConfig, ma_hpf_heap_layout* pHeapLayout)
  38176. {
  38177. ma_result result;
  38178. ma_uint32 hpf1Count;
  38179. ma_uint32 hpf2Count;
  38180. ma_uint32 ihpf1;
  38181. ma_uint32 ihpf2;
  38182. MA_ASSERT(pHeapLayout != NULL);
  38183. MA_ZERO_OBJECT(pHeapLayout);
  38184. if (pConfig == NULL) {
  38185. return MA_INVALID_ARGS;
  38186. }
  38187. if (pConfig->channels == 0) {
  38188. return MA_INVALID_ARGS;
  38189. }
  38190. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38191. return MA_INVALID_ARGS;
  38192. }
  38193. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  38194. pHeapLayout->sizeInBytes = 0;
  38195. /* HPF 1 */
  38196. pHeapLayout->hpf1Offset = pHeapLayout->sizeInBytes;
  38197. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  38198. size_t hpf1HeapSizeInBytes;
  38199. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38200. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  38201. if (result != MA_SUCCESS) {
  38202. return result;
  38203. }
  38204. pHeapLayout->sizeInBytes += sizeof(ma_hpf1) + hpf1HeapSizeInBytes;
  38205. }
  38206. /* HPF 2*/
  38207. pHeapLayout->hpf2Offset = pHeapLayout->sizeInBytes;
  38208. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  38209. size_t hpf2HeapSizeInBytes;
  38210. 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. */
  38211. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  38212. if (result != MA_SUCCESS) {
  38213. return result;
  38214. }
  38215. pHeapLayout->sizeInBytes += sizeof(ma_hpf2) + hpf2HeapSizeInBytes;
  38216. }
  38217. /* Make sure allocation size is aligned. */
  38218. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38219. return MA_SUCCESS;
  38220. }
  38221. static ma_result ma_hpf_reinit__internal(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pHPF, ma_bool32 isNew)
  38222. {
  38223. ma_result result;
  38224. ma_uint32 hpf1Count;
  38225. ma_uint32 hpf2Count;
  38226. ma_uint32 ihpf1;
  38227. ma_uint32 ihpf2;
  38228. ma_hpf_heap_layout heapLayout; /* Only used if isNew is true. */
  38229. if (pHPF == NULL || pConfig == NULL) {
  38230. return MA_INVALID_ARGS;
  38231. }
  38232. /* Only supporting f32 and s16. */
  38233. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38234. return MA_INVALID_ARGS;
  38235. }
  38236. /* The format cannot be changed after initialization. */
  38237. if (pHPF->format != ma_format_unknown && pHPF->format != pConfig->format) {
  38238. return MA_INVALID_OPERATION;
  38239. }
  38240. /* The channel count cannot be changed after initialization. */
  38241. if (pHPF->channels != 0 && pHPF->channels != pConfig->channels) {
  38242. return MA_INVALID_OPERATION;
  38243. }
  38244. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38245. return MA_INVALID_ARGS;
  38246. }
  38247. ma_hpf_calculate_sub_hpf_counts(pConfig->order, &hpf1Count, &hpf2Count);
  38248. /* The filter order can't change between reinits. */
  38249. if (!isNew) {
  38250. if (pHPF->hpf1Count != hpf1Count || pHPF->hpf2Count != hpf2Count) {
  38251. return MA_INVALID_OPERATION;
  38252. }
  38253. }
  38254. if (isNew) {
  38255. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  38256. if (result != MA_SUCCESS) {
  38257. return result;
  38258. }
  38259. pHPF->_pHeap = pHeap;
  38260. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38261. pHPF->pHPF1 = (ma_hpf1*)ma_offset_ptr(pHeap, heapLayout.hpf1Offset);
  38262. pHPF->pHPF2 = (ma_hpf2*)ma_offset_ptr(pHeap, heapLayout.hpf2Offset);
  38263. } else {
  38264. MA_ZERO_OBJECT(&heapLayout); /* To silence a compiler warning. */
  38265. }
  38266. for (ihpf1 = 0; ihpf1 < hpf1Count; ihpf1 += 1) {
  38267. ma_hpf1_config hpf1Config = ma_hpf1_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency);
  38268. if (isNew) {
  38269. size_t hpf1HeapSizeInBytes;
  38270. result = ma_hpf1_get_heap_size(&hpf1Config, &hpf1HeapSizeInBytes);
  38271. if (result == MA_SUCCESS) {
  38272. result = ma_hpf1_init_preallocated(&hpf1Config, ma_offset_ptr(pHeap, heapLayout.hpf1Offset + (sizeof(ma_hpf1) * hpf1Count) + (ihpf1 * hpf1HeapSizeInBytes)), &pHPF->pHPF1[ihpf1]);
  38273. }
  38274. } else {
  38275. result = ma_hpf1_reinit(&hpf1Config, &pHPF->pHPF1[ihpf1]);
  38276. }
  38277. if (result != MA_SUCCESS) {
  38278. ma_uint32 jhpf1;
  38279. for (jhpf1 = 0; jhpf1 < ihpf1; jhpf1 += 1) {
  38280. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38281. }
  38282. return result;
  38283. }
  38284. }
  38285. for (ihpf2 = 0; ihpf2 < hpf2Count; ihpf2 += 1) {
  38286. ma_hpf2_config hpf2Config;
  38287. double q;
  38288. double a;
  38289. /* Tempting to use 0.707107, but won't result in a Butterworth filter if the order is > 2. */
  38290. if (hpf1Count == 1) {
  38291. a = (1 + ihpf2*1) * (MA_PI_D/(pConfig->order*1)); /* Odd order. */
  38292. } else {
  38293. a = (1 + ihpf2*2) * (MA_PI_D/(pConfig->order*2)); /* Even order. */
  38294. }
  38295. q = 1 / (2*ma_cosd(a));
  38296. hpf2Config = ma_hpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  38297. if (isNew) {
  38298. size_t hpf2HeapSizeInBytes;
  38299. result = ma_hpf2_get_heap_size(&hpf2Config, &hpf2HeapSizeInBytes);
  38300. if (result == MA_SUCCESS) {
  38301. result = ma_hpf2_init_preallocated(&hpf2Config, ma_offset_ptr(pHeap, heapLayout.hpf2Offset + (sizeof(ma_hpf2) * hpf2Count) + (ihpf2 * hpf2HeapSizeInBytes)), &pHPF->pHPF2[ihpf2]);
  38302. }
  38303. } else {
  38304. result = ma_hpf2_reinit(&hpf2Config, &pHPF->pHPF2[ihpf2]);
  38305. }
  38306. if (result != MA_SUCCESS) {
  38307. ma_uint32 jhpf1;
  38308. ma_uint32 jhpf2;
  38309. for (jhpf1 = 0; jhpf1 < hpf1Count; jhpf1 += 1) {
  38310. ma_hpf1_uninit(&pHPF->pHPF1[jhpf1], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38311. }
  38312. for (jhpf2 = 0; jhpf2 < ihpf2; jhpf2 += 1) {
  38313. ma_hpf2_uninit(&pHPF->pHPF2[jhpf2], NULL); /* No need for allocation callbacks here since we used a preallocated heap allocation. */
  38314. }
  38315. return result;
  38316. }
  38317. }
  38318. pHPF->hpf1Count = hpf1Count;
  38319. pHPF->hpf2Count = hpf2Count;
  38320. pHPF->format = pConfig->format;
  38321. pHPF->channels = pConfig->channels;
  38322. pHPF->sampleRate = pConfig->sampleRate;
  38323. return MA_SUCCESS;
  38324. }
  38325. MA_API ma_result ma_hpf_get_heap_size(const ma_hpf_config* pConfig, size_t* pHeapSizeInBytes)
  38326. {
  38327. ma_result result;
  38328. ma_hpf_heap_layout heapLayout;
  38329. if (pHeapSizeInBytes == NULL) {
  38330. return MA_INVALID_ARGS;
  38331. }
  38332. *pHeapSizeInBytes = 0;
  38333. result = ma_hpf_get_heap_layout(pConfig, &heapLayout);
  38334. if (result != MA_SUCCESS) {
  38335. return result;
  38336. }
  38337. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38338. return result;
  38339. }
  38340. MA_API ma_result ma_hpf_init_preallocated(const ma_hpf_config* pConfig, void* pHeap, ma_hpf* pLPF)
  38341. {
  38342. if (pLPF == NULL) {
  38343. return MA_INVALID_ARGS;
  38344. }
  38345. MA_ZERO_OBJECT(pLPF);
  38346. return ma_hpf_reinit__internal(pConfig, pHeap, pLPF, /*isNew*/MA_TRUE);
  38347. }
  38348. MA_API ma_result ma_hpf_init(const ma_hpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hpf* pHPF)
  38349. {
  38350. ma_result result;
  38351. size_t heapSizeInBytes;
  38352. void* pHeap;
  38353. result = ma_hpf_get_heap_size(pConfig, &heapSizeInBytes);
  38354. if (result != MA_SUCCESS) {
  38355. return result;
  38356. }
  38357. if (heapSizeInBytes > 0) {
  38358. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38359. if (pHeap == NULL) {
  38360. return MA_OUT_OF_MEMORY;
  38361. }
  38362. } else {
  38363. pHeap = NULL;
  38364. }
  38365. result = ma_hpf_init_preallocated(pConfig, pHeap, pHPF);
  38366. if (result != MA_SUCCESS) {
  38367. ma_free(pHeap, pAllocationCallbacks);
  38368. return result;
  38369. }
  38370. pHPF->_ownsHeap = MA_TRUE;
  38371. return MA_SUCCESS;
  38372. }
  38373. MA_API void ma_hpf_uninit(ma_hpf* pHPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38374. {
  38375. ma_uint32 ihpf1;
  38376. ma_uint32 ihpf2;
  38377. if (pHPF == NULL) {
  38378. return;
  38379. }
  38380. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  38381. ma_hpf1_uninit(&pHPF->pHPF1[ihpf1], pAllocationCallbacks);
  38382. }
  38383. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  38384. ma_hpf2_uninit(&pHPF->pHPF2[ihpf2], pAllocationCallbacks);
  38385. }
  38386. if (pHPF->_ownsHeap) {
  38387. ma_free(pHPF->_pHeap, pAllocationCallbacks);
  38388. }
  38389. }
  38390. MA_API ma_result ma_hpf_reinit(const ma_hpf_config* pConfig, ma_hpf* pHPF)
  38391. {
  38392. return ma_hpf_reinit__internal(pConfig, NULL, pHPF, /*isNew*/MA_FALSE);
  38393. }
  38394. MA_API ma_result ma_hpf_process_pcm_frames(ma_hpf* pHPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38395. {
  38396. ma_result result;
  38397. ma_uint32 ihpf1;
  38398. ma_uint32 ihpf2;
  38399. if (pHPF == NULL) {
  38400. return MA_INVALID_ARGS;
  38401. }
  38402. /* Faster path for in-place. */
  38403. if (pFramesOut == pFramesIn) {
  38404. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  38405. result = ma_hpf1_process_pcm_frames(&pHPF->pHPF1[ihpf1], pFramesOut, pFramesOut, frameCount);
  38406. if (result != MA_SUCCESS) {
  38407. return result;
  38408. }
  38409. }
  38410. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  38411. result = ma_hpf2_process_pcm_frames(&pHPF->pHPF2[ihpf2], pFramesOut, pFramesOut, frameCount);
  38412. if (result != MA_SUCCESS) {
  38413. return result;
  38414. }
  38415. }
  38416. }
  38417. /* Slightly slower path for copying. */
  38418. if (pFramesOut != pFramesIn) {
  38419. ma_uint32 iFrame;
  38420. /* */ if (pHPF->format == ma_format_f32) {
  38421. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  38422. const float* pFramesInF32 = (const float*)pFramesIn;
  38423. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38424. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  38425. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  38426. ma_hpf1_process_pcm_frame_f32(&pHPF->pHPF1[ihpf1], pFramesOutF32, pFramesOutF32);
  38427. }
  38428. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  38429. ma_hpf2_process_pcm_frame_f32(&pHPF->pHPF2[ihpf2], pFramesOutF32, pFramesOutF32);
  38430. }
  38431. pFramesOutF32 += pHPF->channels;
  38432. pFramesInF32 += pHPF->channels;
  38433. }
  38434. } else if (pHPF->format == ma_format_s16) {
  38435. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  38436. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  38437. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38438. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pHPF->format, pHPF->channels));
  38439. for (ihpf1 = 0; ihpf1 < pHPF->hpf1Count; ihpf1 += 1) {
  38440. ma_hpf1_process_pcm_frame_s16(&pHPF->pHPF1[ihpf1], pFramesOutS16, pFramesOutS16);
  38441. }
  38442. for (ihpf2 = 0; ihpf2 < pHPF->hpf2Count; ihpf2 += 1) {
  38443. ma_hpf2_process_pcm_frame_s16(&pHPF->pHPF2[ihpf2], pFramesOutS16, pFramesOutS16);
  38444. }
  38445. pFramesOutS16 += pHPF->channels;
  38446. pFramesInS16 += pHPF->channels;
  38447. }
  38448. } else {
  38449. MA_ASSERT(MA_FALSE);
  38450. return MA_INVALID_OPERATION; /* Should never hit this. */
  38451. }
  38452. }
  38453. return MA_SUCCESS;
  38454. }
  38455. MA_API ma_uint32 ma_hpf_get_latency(const ma_hpf* pHPF)
  38456. {
  38457. if (pHPF == NULL) {
  38458. return 0;
  38459. }
  38460. return pHPF->hpf2Count*2 + pHPF->hpf1Count;
  38461. }
  38462. /**************************************************************************************************************************************************************
  38463. Band-Pass Filtering
  38464. **************************************************************************************************************************************************************/
  38465. MA_API ma_bpf2_config ma_bpf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, double q)
  38466. {
  38467. ma_bpf2_config config;
  38468. MA_ZERO_OBJECT(&config);
  38469. config.format = format;
  38470. config.channels = channels;
  38471. config.sampleRate = sampleRate;
  38472. config.cutoffFrequency = cutoffFrequency;
  38473. config.q = q;
  38474. /* Q cannot be 0 or else it'll result in a division by 0. In this case just default to 0.707107. */
  38475. if (config.q == 0) {
  38476. config.q = 0.707107;
  38477. }
  38478. return config;
  38479. }
  38480. static MA_INLINE ma_biquad_config ma_bpf2__get_biquad_config(const ma_bpf2_config* pConfig)
  38481. {
  38482. ma_biquad_config bqConfig;
  38483. double q;
  38484. double w;
  38485. double s;
  38486. double c;
  38487. double a;
  38488. MA_ASSERT(pConfig != NULL);
  38489. q = pConfig->q;
  38490. w = 2 * MA_PI_D * pConfig->cutoffFrequency / pConfig->sampleRate;
  38491. s = ma_sind(w);
  38492. c = ma_cosd(w);
  38493. a = s / (2*q);
  38494. bqConfig.b0 = q * a;
  38495. bqConfig.b1 = 0;
  38496. bqConfig.b2 = -q * a;
  38497. bqConfig.a0 = 1 + a;
  38498. bqConfig.a1 = -2 * c;
  38499. bqConfig.a2 = 1 - a;
  38500. bqConfig.format = pConfig->format;
  38501. bqConfig.channels = pConfig->channels;
  38502. return bqConfig;
  38503. }
  38504. MA_API ma_result ma_bpf2_get_heap_size(const ma_bpf2_config* pConfig, size_t* pHeapSizeInBytes)
  38505. {
  38506. ma_biquad_config bqConfig;
  38507. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  38508. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38509. }
  38510. MA_API ma_result ma_bpf2_init_preallocated(const ma_bpf2_config* pConfig, void* pHeap, ma_bpf2* pBPF)
  38511. {
  38512. ma_result result;
  38513. ma_biquad_config bqConfig;
  38514. if (pBPF == NULL) {
  38515. return MA_INVALID_ARGS;
  38516. }
  38517. MA_ZERO_OBJECT(pBPF);
  38518. if (pConfig == NULL) {
  38519. return MA_INVALID_ARGS;
  38520. }
  38521. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  38522. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pBPF->bq);
  38523. if (result != MA_SUCCESS) {
  38524. return result;
  38525. }
  38526. return MA_SUCCESS;
  38527. }
  38528. MA_API ma_result ma_bpf2_init(const ma_bpf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf2* pBPF)
  38529. {
  38530. ma_result result;
  38531. size_t heapSizeInBytes;
  38532. void* pHeap;
  38533. result = ma_bpf2_get_heap_size(pConfig, &heapSizeInBytes);
  38534. if (result != MA_SUCCESS) {
  38535. return result;
  38536. }
  38537. if (heapSizeInBytes > 0) {
  38538. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38539. if (pHeap == NULL) {
  38540. return MA_OUT_OF_MEMORY;
  38541. }
  38542. } else {
  38543. pHeap = NULL;
  38544. }
  38545. result = ma_bpf2_init_preallocated(pConfig, pHeap, pBPF);
  38546. if (result != MA_SUCCESS) {
  38547. ma_free(pHeap, pAllocationCallbacks);
  38548. return result;
  38549. }
  38550. pBPF->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  38551. return MA_SUCCESS;
  38552. }
  38553. MA_API void ma_bpf2_uninit(ma_bpf2* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38554. {
  38555. if (pBPF == NULL) {
  38556. return;
  38557. }
  38558. ma_biquad_uninit(&pBPF->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  38559. }
  38560. MA_API ma_result ma_bpf2_reinit(const ma_bpf2_config* pConfig, ma_bpf2* pBPF)
  38561. {
  38562. ma_result result;
  38563. ma_biquad_config bqConfig;
  38564. if (pBPF == NULL || pConfig == NULL) {
  38565. return MA_INVALID_ARGS;
  38566. }
  38567. bqConfig = ma_bpf2__get_biquad_config(pConfig);
  38568. result = ma_biquad_reinit(&bqConfig, &pBPF->bq);
  38569. if (result != MA_SUCCESS) {
  38570. return result;
  38571. }
  38572. return MA_SUCCESS;
  38573. }
  38574. static MA_INLINE void ma_bpf2_process_pcm_frame_s16(ma_bpf2* pBPF, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  38575. {
  38576. ma_biquad_process_pcm_frame_s16(&pBPF->bq, pFrameOut, pFrameIn);
  38577. }
  38578. static MA_INLINE void ma_bpf2_process_pcm_frame_f32(ma_bpf2* pBPF, float* pFrameOut, const float* pFrameIn)
  38579. {
  38580. ma_biquad_process_pcm_frame_f32(&pBPF->bq, pFrameOut, pFrameIn);
  38581. }
  38582. MA_API ma_result ma_bpf2_process_pcm_frames(ma_bpf2* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38583. {
  38584. if (pBPF == NULL) {
  38585. return MA_INVALID_ARGS;
  38586. }
  38587. return ma_biquad_process_pcm_frames(&pBPF->bq, pFramesOut, pFramesIn, frameCount);
  38588. }
  38589. MA_API ma_uint32 ma_bpf2_get_latency(const ma_bpf2* pBPF)
  38590. {
  38591. if (pBPF == NULL) {
  38592. return 0;
  38593. }
  38594. return ma_biquad_get_latency(&pBPF->bq);
  38595. }
  38596. MA_API ma_bpf_config ma_bpf_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  38597. {
  38598. ma_bpf_config config;
  38599. MA_ZERO_OBJECT(&config);
  38600. config.format = format;
  38601. config.channels = channels;
  38602. config.sampleRate = sampleRate;
  38603. config.cutoffFrequency = cutoffFrequency;
  38604. config.order = ma_min(order, MA_MAX_FILTER_ORDER);
  38605. return config;
  38606. }
  38607. typedef struct
  38608. {
  38609. size_t sizeInBytes;
  38610. size_t bpf2Offset;
  38611. } ma_bpf_heap_layout;
  38612. static ma_result ma_bpf_get_heap_layout(const ma_bpf_config* pConfig, ma_bpf_heap_layout* pHeapLayout)
  38613. {
  38614. ma_result result;
  38615. ma_uint32 bpf2Count;
  38616. ma_uint32 ibpf2;
  38617. MA_ASSERT(pHeapLayout != NULL);
  38618. MA_ZERO_OBJECT(pHeapLayout);
  38619. if (pConfig == NULL) {
  38620. return MA_INVALID_ARGS;
  38621. }
  38622. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38623. return MA_INVALID_ARGS;
  38624. }
  38625. /* We must have an even number of order. */
  38626. if ((pConfig->order & 0x1) != 0) {
  38627. return MA_INVALID_ARGS;
  38628. }
  38629. bpf2Count = pConfig->channels / 2;
  38630. pHeapLayout->sizeInBytes = 0;
  38631. /* BPF 2 */
  38632. pHeapLayout->bpf2Offset = pHeapLayout->sizeInBytes;
  38633. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  38634. size_t bpf2HeapSizeInBytes;
  38635. 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. */
  38636. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  38637. if (result != MA_SUCCESS) {
  38638. return result;
  38639. }
  38640. pHeapLayout->sizeInBytes += sizeof(ma_bpf2) + bpf2HeapSizeInBytes;
  38641. }
  38642. /* Make sure allocation size is aligned. */
  38643. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  38644. return MA_SUCCESS;
  38645. }
  38646. static ma_result ma_bpf_reinit__internal(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF, ma_bool32 isNew)
  38647. {
  38648. ma_result result;
  38649. ma_uint32 bpf2Count;
  38650. ma_uint32 ibpf2;
  38651. ma_bpf_heap_layout heapLayout; /* Only used if isNew is true. */
  38652. if (pBPF == NULL || pConfig == NULL) {
  38653. return MA_INVALID_ARGS;
  38654. }
  38655. /* Only supporting f32 and s16. */
  38656. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  38657. return MA_INVALID_ARGS;
  38658. }
  38659. /* The format cannot be changed after initialization. */
  38660. if (pBPF->format != ma_format_unknown && pBPF->format != pConfig->format) {
  38661. return MA_INVALID_OPERATION;
  38662. }
  38663. /* The channel count cannot be changed after initialization. */
  38664. if (pBPF->channels != 0 && pBPF->channels != pConfig->channels) {
  38665. return MA_INVALID_OPERATION;
  38666. }
  38667. if (pConfig->order > MA_MAX_FILTER_ORDER) {
  38668. return MA_INVALID_ARGS;
  38669. }
  38670. /* We must have an even number of order. */
  38671. if ((pConfig->order & 0x1) != 0) {
  38672. return MA_INVALID_ARGS;
  38673. }
  38674. bpf2Count = pConfig->order / 2;
  38675. /* The filter order can't change between reinits. */
  38676. if (!isNew) {
  38677. if (pBPF->bpf2Count != bpf2Count) {
  38678. return MA_INVALID_OPERATION;
  38679. }
  38680. }
  38681. if (isNew) {
  38682. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  38683. if (result != MA_SUCCESS) {
  38684. return result;
  38685. }
  38686. pBPF->_pHeap = pHeap;
  38687. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  38688. pBPF->pBPF2 = (ma_bpf2*)ma_offset_ptr(pHeap, heapLayout.bpf2Offset);
  38689. } else {
  38690. MA_ZERO_OBJECT(&heapLayout);
  38691. }
  38692. for (ibpf2 = 0; ibpf2 < bpf2Count; ibpf2 += 1) {
  38693. ma_bpf2_config bpf2Config;
  38694. double q;
  38695. /* TODO: Calculate Q to make this a proper Butterworth filter. */
  38696. q = 0.707107;
  38697. bpf2Config = ma_bpf2_config_init(pConfig->format, pConfig->channels, pConfig->sampleRate, pConfig->cutoffFrequency, q);
  38698. if (isNew) {
  38699. size_t bpf2HeapSizeInBytes;
  38700. result = ma_bpf2_get_heap_size(&bpf2Config, &bpf2HeapSizeInBytes);
  38701. if (result == MA_SUCCESS) {
  38702. result = ma_bpf2_init_preallocated(&bpf2Config, ma_offset_ptr(pHeap, heapLayout.bpf2Offset + (sizeof(ma_bpf2) * bpf2Count) + (ibpf2 * bpf2HeapSizeInBytes)), &pBPF->pBPF2[ibpf2]);
  38703. }
  38704. } else {
  38705. result = ma_bpf2_reinit(&bpf2Config, &pBPF->pBPF2[ibpf2]);
  38706. }
  38707. if (result != MA_SUCCESS) {
  38708. return result;
  38709. }
  38710. }
  38711. pBPF->bpf2Count = bpf2Count;
  38712. pBPF->format = pConfig->format;
  38713. pBPF->channels = pConfig->channels;
  38714. return MA_SUCCESS;
  38715. }
  38716. MA_API ma_result ma_bpf_get_heap_size(const ma_bpf_config* pConfig, size_t* pHeapSizeInBytes)
  38717. {
  38718. ma_result result;
  38719. ma_bpf_heap_layout heapLayout;
  38720. if (pHeapSizeInBytes == NULL) {
  38721. return MA_INVALID_ARGS;
  38722. }
  38723. *pHeapSizeInBytes = 0;
  38724. result = ma_bpf_get_heap_layout(pConfig, &heapLayout);
  38725. if (result != MA_SUCCESS) {
  38726. return result;
  38727. }
  38728. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  38729. return MA_SUCCESS;
  38730. }
  38731. MA_API ma_result ma_bpf_init_preallocated(const ma_bpf_config* pConfig, void* pHeap, ma_bpf* pBPF)
  38732. {
  38733. if (pBPF == NULL) {
  38734. return MA_INVALID_ARGS;
  38735. }
  38736. MA_ZERO_OBJECT(pBPF);
  38737. return ma_bpf_reinit__internal(pConfig, pHeap, pBPF, /*isNew*/MA_TRUE);
  38738. }
  38739. MA_API ma_result ma_bpf_init(const ma_bpf_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_bpf* pBPF)
  38740. {
  38741. ma_result result;
  38742. size_t heapSizeInBytes;
  38743. void* pHeap;
  38744. result = ma_bpf_get_heap_size(pConfig, &heapSizeInBytes);
  38745. if (result != MA_SUCCESS) {
  38746. return result;
  38747. }
  38748. if (heapSizeInBytes > 0) {
  38749. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38750. if (pHeap == NULL) {
  38751. return MA_OUT_OF_MEMORY;
  38752. }
  38753. } else {
  38754. pHeap = NULL;
  38755. }
  38756. result = ma_bpf_init_preallocated(pConfig, pHeap, pBPF);
  38757. if (result != MA_SUCCESS) {
  38758. ma_free(pHeap, pAllocationCallbacks);
  38759. return result;
  38760. }
  38761. pBPF->_ownsHeap = MA_TRUE;
  38762. return MA_SUCCESS;
  38763. }
  38764. MA_API void ma_bpf_uninit(ma_bpf* pBPF, const ma_allocation_callbacks* pAllocationCallbacks)
  38765. {
  38766. ma_uint32 ibpf2;
  38767. if (pBPF == NULL) {
  38768. return;
  38769. }
  38770. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  38771. ma_bpf2_uninit(&pBPF->pBPF2[ibpf2], pAllocationCallbacks);
  38772. }
  38773. if (pBPF->_ownsHeap) {
  38774. ma_free(pBPF->_pHeap, pAllocationCallbacks);
  38775. }
  38776. }
  38777. MA_API ma_result ma_bpf_reinit(const ma_bpf_config* pConfig, ma_bpf* pBPF)
  38778. {
  38779. return ma_bpf_reinit__internal(pConfig, NULL, pBPF, /*isNew*/MA_FALSE);
  38780. }
  38781. MA_API ma_result ma_bpf_process_pcm_frames(ma_bpf* pBPF, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38782. {
  38783. ma_result result;
  38784. ma_uint32 ibpf2;
  38785. if (pBPF == NULL) {
  38786. return MA_INVALID_ARGS;
  38787. }
  38788. /* Faster path for in-place. */
  38789. if (pFramesOut == pFramesIn) {
  38790. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  38791. result = ma_bpf2_process_pcm_frames(&pBPF->pBPF2[ibpf2], pFramesOut, pFramesOut, frameCount);
  38792. if (result != MA_SUCCESS) {
  38793. return result;
  38794. }
  38795. }
  38796. }
  38797. /* Slightly slower path for copying. */
  38798. if (pFramesOut != pFramesIn) {
  38799. ma_uint32 iFrame;
  38800. /* */ if (pBPF->format == ma_format_f32) {
  38801. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  38802. const float* pFramesInF32 = (const float*)pFramesIn;
  38803. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38804. MA_COPY_MEMORY(pFramesOutF32, pFramesInF32, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  38805. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  38806. ma_bpf2_process_pcm_frame_f32(&pBPF->pBPF2[ibpf2], pFramesOutF32, pFramesOutF32);
  38807. }
  38808. pFramesOutF32 += pBPF->channels;
  38809. pFramesInF32 += pBPF->channels;
  38810. }
  38811. } else if (pBPF->format == ma_format_s16) {
  38812. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  38813. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  38814. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  38815. MA_COPY_MEMORY(pFramesOutS16, pFramesInS16, ma_get_bytes_per_frame(pBPF->format, pBPF->channels));
  38816. for (ibpf2 = 0; ibpf2 < pBPF->bpf2Count; ibpf2 += 1) {
  38817. ma_bpf2_process_pcm_frame_s16(&pBPF->pBPF2[ibpf2], pFramesOutS16, pFramesOutS16);
  38818. }
  38819. pFramesOutS16 += pBPF->channels;
  38820. pFramesInS16 += pBPF->channels;
  38821. }
  38822. } else {
  38823. MA_ASSERT(MA_FALSE);
  38824. return MA_INVALID_OPERATION; /* Should never hit this. */
  38825. }
  38826. }
  38827. return MA_SUCCESS;
  38828. }
  38829. MA_API ma_uint32 ma_bpf_get_latency(const ma_bpf* pBPF)
  38830. {
  38831. if (pBPF == NULL) {
  38832. return 0;
  38833. }
  38834. return pBPF->bpf2Count*2;
  38835. }
  38836. /**************************************************************************************************************************************************************
  38837. Notching Filter
  38838. **************************************************************************************************************************************************************/
  38839. MA_API ma_notch2_config ma_notch2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  38840. {
  38841. ma_notch2_config config;
  38842. MA_ZERO_OBJECT(&config);
  38843. config.format = format;
  38844. config.channels = channels;
  38845. config.sampleRate = sampleRate;
  38846. config.q = q;
  38847. config.frequency = frequency;
  38848. if (config.q == 0) {
  38849. config.q = 0.707107;
  38850. }
  38851. return config;
  38852. }
  38853. static MA_INLINE ma_biquad_config ma_notch2__get_biquad_config(const ma_notch2_config* pConfig)
  38854. {
  38855. ma_biquad_config bqConfig;
  38856. double q;
  38857. double w;
  38858. double s;
  38859. double c;
  38860. double a;
  38861. MA_ASSERT(pConfig != NULL);
  38862. q = pConfig->q;
  38863. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  38864. s = ma_sind(w);
  38865. c = ma_cosd(w);
  38866. a = s / (2*q);
  38867. bqConfig.b0 = 1;
  38868. bqConfig.b1 = -2 * c;
  38869. bqConfig.b2 = 1;
  38870. bqConfig.a0 = 1 + a;
  38871. bqConfig.a1 = -2 * c;
  38872. bqConfig.a2 = 1 - a;
  38873. bqConfig.format = pConfig->format;
  38874. bqConfig.channels = pConfig->channels;
  38875. return bqConfig;
  38876. }
  38877. MA_API ma_result ma_notch2_get_heap_size(const ma_notch2_config* pConfig, size_t* pHeapSizeInBytes)
  38878. {
  38879. ma_biquad_config bqConfig;
  38880. bqConfig = ma_notch2__get_biquad_config(pConfig);
  38881. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  38882. }
  38883. MA_API ma_result ma_notch2_init_preallocated(const ma_notch2_config* pConfig, void* pHeap, ma_notch2* pFilter)
  38884. {
  38885. ma_result result;
  38886. ma_biquad_config bqConfig;
  38887. if (pFilter == NULL) {
  38888. return MA_INVALID_ARGS;
  38889. }
  38890. MA_ZERO_OBJECT(pFilter);
  38891. if (pConfig == NULL) {
  38892. return MA_INVALID_ARGS;
  38893. }
  38894. bqConfig = ma_notch2__get_biquad_config(pConfig);
  38895. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  38896. if (result != MA_SUCCESS) {
  38897. return result;
  38898. }
  38899. return MA_SUCCESS;
  38900. }
  38901. MA_API ma_result ma_notch2_init(const ma_notch2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_notch2* pFilter)
  38902. {
  38903. ma_result result;
  38904. size_t heapSizeInBytes;
  38905. void* pHeap;
  38906. result = ma_notch2_get_heap_size(pConfig, &heapSizeInBytes);
  38907. if (result != MA_SUCCESS) {
  38908. return result;
  38909. }
  38910. if (heapSizeInBytes > 0) {
  38911. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  38912. if (pHeap == NULL) {
  38913. return MA_OUT_OF_MEMORY;
  38914. }
  38915. } else {
  38916. pHeap = NULL;
  38917. }
  38918. result = ma_notch2_init_preallocated(pConfig, pHeap, pFilter);
  38919. if (result != MA_SUCCESS) {
  38920. ma_free(pHeap, pAllocationCallbacks);
  38921. return result;
  38922. }
  38923. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  38924. return MA_SUCCESS;
  38925. }
  38926. MA_API void ma_notch2_uninit(ma_notch2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  38927. {
  38928. if (pFilter == NULL) {
  38929. return;
  38930. }
  38931. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  38932. }
  38933. MA_API ma_result ma_notch2_reinit(const ma_notch2_config* pConfig, ma_notch2* pFilter)
  38934. {
  38935. ma_result result;
  38936. ma_biquad_config bqConfig;
  38937. if (pFilter == NULL || pConfig == NULL) {
  38938. return MA_INVALID_ARGS;
  38939. }
  38940. bqConfig = ma_notch2__get_biquad_config(pConfig);
  38941. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  38942. if (result != MA_SUCCESS) {
  38943. return result;
  38944. }
  38945. return MA_SUCCESS;
  38946. }
  38947. static MA_INLINE void ma_notch2_process_pcm_frame_s16(ma_notch2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  38948. {
  38949. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  38950. }
  38951. static MA_INLINE void ma_notch2_process_pcm_frame_f32(ma_notch2* pFilter, float* pFrameOut, const float* pFrameIn)
  38952. {
  38953. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  38954. }
  38955. MA_API ma_result ma_notch2_process_pcm_frames(ma_notch2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  38956. {
  38957. if (pFilter == NULL) {
  38958. return MA_INVALID_ARGS;
  38959. }
  38960. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  38961. }
  38962. MA_API ma_uint32 ma_notch2_get_latency(const ma_notch2* pFilter)
  38963. {
  38964. if (pFilter == NULL) {
  38965. return 0;
  38966. }
  38967. return ma_biquad_get_latency(&pFilter->bq);
  38968. }
  38969. /**************************************************************************************************************************************************************
  38970. Peaking EQ Filter
  38971. **************************************************************************************************************************************************************/
  38972. MA_API ma_peak2_config ma_peak2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  38973. {
  38974. ma_peak2_config config;
  38975. MA_ZERO_OBJECT(&config);
  38976. config.format = format;
  38977. config.channels = channels;
  38978. config.sampleRate = sampleRate;
  38979. config.gainDB = gainDB;
  38980. config.q = q;
  38981. config.frequency = frequency;
  38982. if (config.q == 0) {
  38983. config.q = 0.707107;
  38984. }
  38985. return config;
  38986. }
  38987. static MA_INLINE ma_biquad_config ma_peak2__get_biquad_config(const ma_peak2_config* pConfig)
  38988. {
  38989. ma_biquad_config bqConfig;
  38990. double q;
  38991. double w;
  38992. double s;
  38993. double c;
  38994. double a;
  38995. double A;
  38996. MA_ASSERT(pConfig != NULL);
  38997. q = pConfig->q;
  38998. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  38999. s = ma_sind(w);
  39000. c = ma_cosd(w);
  39001. a = s / (2*q);
  39002. A = ma_powd(10, (pConfig->gainDB / 40));
  39003. bqConfig.b0 = 1 + (a * A);
  39004. bqConfig.b1 = -2 * c;
  39005. bqConfig.b2 = 1 - (a * A);
  39006. bqConfig.a0 = 1 + (a / A);
  39007. bqConfig.a1 = -2 * c;
  39008. bqConfig.a2 = 1 - (a / A);
  39009. bqConfig.format = pConfig->format;
  39010. bqConfig.channels = pConfig->channels;
  39011. return bqConfig;
  39012. }
  39013. MA_API ma_result ma_peak2_get_heap_size(const ma_peak2_config* pConfig, size_t* pHeapSizeInBytes)
  39014. {
  39015. ma_biquad_config bqConfig;
  39016. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39017. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39018. }
  39019. MA_API ma_result ma_peak2_init_preallocated(const ma_peak2_config* pConfig, void* pHeap, ma_peak2* pFilter)
  39020. {
  39021. ma_result result;
  39022. ma_biquad_config bqConfig;
  39023. if (pFilter == NULL) {
  39024. return MA_INVALID_ARGS;
  39025. }
  39026. MA_ZERO_OBJECT(pFilter);
  39027. if (pConfig == NULL) {
  39028. return MA_INVALID_ARGS;
  39029. }
  39030. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39031. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39032. if (result != MA_SUCCESS) {
  39033. return result;
  39034. }
  39035. return MA_SUCCESS;
  39036. }
  39037. MA_API ma_result ma_peak2_init(const ma_peak2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_peak2* pFilter)
  39038. {
  39039. ma_result result;
  39040. size_t heapSizeInBytes;
  39041. void* pHeap;
  39042. result = ma_peak2_get_heap_size(pConfig, &heapSizeInBytes);
  39043. if (result != MA_SUCCESS) {
  39044. return result;
  39045. }
  39046. if (heapSizeInBytes > 0) {
  39047. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39048. if (pHeap == NULL) {
  39049. return MA_OUT_OF_MEMORY;
  39050. }
  39051. } else {
  39052. pHeap = NULL;
  39053. }
  39054. result = ma_peak2_init_preallocated(pConfig, pHeap, pFilter);
  39055. if (result != MA_SUCCESS) {
  39056. ma_free(pHeap, pAllocationCallbacks);
  39057. return result;
  39058. }
  39059. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39060. return MA_SUCCESS;
  39061. }
  39062. MA_API void ma_peak2_uninit(ma_peak2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39063. {
  39064. if (pFilter == NULL) {
  39065. return;
  39066. }
  39067. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39068. }
  39069. MA_API ma_result ma_peak2_reinit(const ma_peak2_config* pConfig, ma_peak2* pFilter)
  39070. {
  39071. ma_result result;
  39072. ma_biquad_config bqConfig;
  39073. if (pFilter == NULL || pConfig == NULL) {
  39074. return MA_INVALID_ARGS;
  39075. }
  39076. bqConfig = ma_peak2__get_biquad_config(pConfig);
  39077. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  39078. if (result != MA_SUCCESS) {
  39079. return result;
  39080. }
  39081. return MA_SUCCESS;
  39082. }
  39083. static MA_INLINE void ma_peak2_process_pcm_frame_s16(ma_peak2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39084. {
  39085. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  39086. }
  39087. static MA_INLINE void ma_peak2_process_pcm_frame_f32(ma_peak2* pFilter, float* pFrameOut, const float* pFrameIn)
  39088. {
  39089. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  39090. }
  39091. MA_API ma_result ma_peak2_process_pcm_frames(ma_peak2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39092. {
  39093. if (pFilter == NULL) {
  39094. return MA_INVALID_ARGS;
  39095. }
  39096. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  39097. }
  39098. MA_API ma_uint32 ma_peak2_get_latency(const ma_peak2* pFilter)
  39099. {
  39100. if (pFilter == NULL) {
  39101. return 0;
  39102. }
  39103. return ma_biquad_get_latency(&pFilter->bq);
  39104. }
  39105. /**************************************************************************************************************************************************************
  39106. Low Shelf Filter
  39107. **************************************************************************************************************************************************************/
  39108. MA_API ma_loshelf2_config ma_loshelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  39109. {
  39110. ma_loshelf2_config config;
  39111. MA_ZERO_OBJECT(&config);
  39112. config.format = format;
  39113. config.channels = channels;
  39114. config.sampleRate = sampleRate;
  39115. config.gainDB = gainDB;
  39116. config.shelfSlope = shelfSlope;
  39117. config.frequency = frequency;
  39118. return config;
  39119. }
  39120. static MA_INLINE ma_biquad_config ma_loshelf2__get_biquad_config(const ma_loshelf2_config* pConfig)
  39121. {
  39122. ma_biquad_config bqConfig;
  39123. double w;
  39124. double s;
  39125. double c;
  39126. double A;
  39127. double S;
  39128. double a;
  39129. double sqrtA;
  39130. MA_ASSERT(pConfig != NULL);
  39131. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39132. s = ma_sind(w);
  39133. c = ma_cosd(w);
  39134. A = ma_powd(10, (pConfig->gainDB / 40));
  39135. S = pConfig->shelfSlope;
  39136. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  39137. sqrtA = 2*ma_sqrtd(A)*a;
  39138. bqConfig.b0 = A * ((A + 1) - (A - 1)*c + sqrtA);
  39139. bqConfig.b1 = 2 * A * ((A - 1) - (A + 1)*c);
  39140. bqConfig.b2 = A * ((A + 1) - (A - 1)*c - sqrtA);
  39141. bqConfig.a0 = (A + 1) + (A - 1)*c + sqrtA;
  39142. bqConfig.a1 = -2 * ((A - 1) + (A + 1)*c);
  39143. bqConfig.a2 = (A + 1) + (A - 1)*c - sqrtA;
  39144. bqConfig.format = pConfig->format;
  39145. bqConfig.channels = pConfig->channels;
  39146. return bqConfig;
  39147. }
  39148. MA_API ma_result ma_loshelf2_get_heap_size(const ma_loshelf2_config* pConfig, size_t* pHeapSizeInBytes)
  39149. {
  39150. ma_biquad_config bqConfig;
  39151. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  39152. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39153. }
  39154. MA_API ma_result ma_loshelf2_init_preallocated(const ma_loshelf2_config* pConfig, void* pHeap, ma_loshelf2* pFilter)
  39155. {
  39156. ma_result result;
  39157. ma_biquad_config bqConfig;
  39158. if (pFilter == NULL) {
  39159. return MA_INVALID_ARGS;
  39160. }
  39161. MA_ZERO_OBJECT(pFilter);
  39162. if (pConfig == NULL) {
  39163. return MA_INVALID_ARGS;
  39164. }
  39165. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  39166. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39167. if (result != MA_SUCCESS) {
  39168. return result;
  39169. }
  39170. return MA_SUCCESS;
  39171. }
  39172. MA_API ma_result ma_loshelf2_init(const ma_loshelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_loshelf2* pFilter)
  39173. {
  39174. ma_result result;
  39175. size_t heapSizeInBytes;
  39176. void* pHeap;
  39177. result = ma_loshelf2_get_heap_size(pConfig, &heapSizeInBytes);
  39178. if (result != MA_SUCCESS) {
  39179. return result;
  39180. }
  39181. if (heapSizeInBytes > 0) {
  39182. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39183. if (pHeap == NULL) {
  39184. return MA_OUT_OF_MEMORY;
  39185. }
  39186. } else {
  39187. pHeap = NULL;
  39188. }
  39189. result = ma_loshelf2_init_preallocated(pConfig, pHeap, pFilter);
  39190. if (result != MA_SUCCESS) {
  39191. ma_free(pHeap, pAllocationCallbacks);
  39192. return result;
  39193. }
  39194. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39195. return MA_SUCCESS;
  39196. }
  39197. MA_API void ma_loshelf2_uninit(ma_loshelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39198. {
  39199. if (pFilter == NULL) {
  39200. return;
  39201. }
  39202. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39203. }
  39204. MA_API ma_result ma_loshelf2_reinit(const ma_loshelf2_config* pConfig, ma_loshelf2* pFilter)
  39205. {
  39206. ma_result result;
  39207. ma_biquad_config bqConfig;
  39208. if (pFilter == NULL || pConfig == NULL) {
  39209. return MA_INVALID_ARGS;
  39210. }
  39211. bqConfig = ma_loshelf2__get_biquad_config(pConfig);
  39212. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  39213. if (result != MA_SUCCESS) {
  39214. return result;
  39215. }
  39216. return MA_SUCCESS;
  39217. }
  39218. static MA_INLINE void ma_loshelf2_process_pcm_frame_s16(ma_loshelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39219. {
  39220. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  39221. }
  39222. static MA_INLINE void ma_loshelf2_process_pcm_frame_f32(ma_loshelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  39223. {
  39224. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  39225. }
  39226. MA_API ma_result ma_loshelf2_process_pcm_frames(ma_loshelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39227. {
  39228. if (pFilter == NULL) {
  39229. return MA_INVALID_ARGS;
  39230. }
  39231. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  39232. }
  39233. MA_API ma_uint32 ma_loshelf2_get_latency(const ma_loshelf2* pFilter)
  39234. {
  39235. if (pFilter == NULL) {
  39236. return 0;
  39237. }
  39238. return ma_biquad_get_latency(&pFilter->bq);
  39239. }
  39240. /**************************************************************************************************************************************************************
  39241. High Shelf Filter
  39242. **************************************************************************************************************************************************************/
  39243. MA_API ma_hishelf2_config ma_hishelf2_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double shelfSlope, double frequency)
  39244. {
  39245. ma_hishelf2_config config;
  39246. MA_ZERO_OBJECT(&config);
  39247. config.format = format;
  39248. config.channels = channels;
  39249. config.sampleRate = sampleRate;
  39250. config.gainDB = gainDB;
  39251. config.shelfSlope = shelfSlope;
  39252. config.frequency = frequency;
  39253. return config;
  39254. }
  39255. static MA_INLINE ma_biquad_config ma_hishelf2__get_biquad_config(const ma_hishelf2_config* pConfig)
  39256. {
  39257. ma_biquad_config bqConfig;
  39258. double w;
  39259. double s;
  39260. double c;
  39261. double A;
  39262. double S;
  39263. double a;
  39264. double sqrtA;
  39265. MA_ASSERT(pConfig != NULL);
  39266. w = 2 * MA_PI_D * pConfig->frequency / pConfig->sampleRate;
  39267. s = ma_sind(w);
  39268. c = ma_cosd(w);
  39269. A = ma_powd(10, (pConfig->gainDB / 40));
  39270. S = pConfig->shelfSlope;
  39271. a = s/2 * ma_sqrtd((A + 1/A) * (1/S - 1) + 2);
  39272. sqrtA = 2*ma_sqrtd(A)*a;
  39273. bqConfig.b0 = A * ((A + 1) + (A - 1)*c + sqrtA);
  39274. bqConfig.b1 = -2 * A * ((A - 1) + (A + 1)*c);
  39275. bqConfig.b2 = A * ((A + 1) + (A - 1)*c - sqrtA);
  39276. bqConfig.a0 = (A + 1) - (A - 1)*c + sqrtA;
  39277. bqConfig.a1 = 2 * ((A - 1) - (A + 1)*c);
  39278. bqConfig.a2 = (A + 1) - (A - 1)*c - sqrtA;
  39279. bqConfig.format = pConfig->format;
  39280. bqConfig.channels = pConfig->channels;
  39281. return bqConfig;
  39282. }
  39283. MA_API ma_result ma_hishelf2_get_heap_size(const ma_hishelf2_config* pConfig, size_t* pHeapSizeInBytes)
  39284. {
  39285. ma_biquad_config bqConfig;
  39286. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  39287. return ma_biquad_get_heap_size(&bqConfig, pHeapSizeInBytes);
  39288. }
  39289. MA_API ma_result ma_hishelf2_init_preallocated(const ma_hishelf2_config* pConfig, void* pHeap, ma_hishelf2* pFilter)
  39290. {
  39291. ma_result result;
  39292. ma_biquad_config bqConfig;
  39293. if (pFilter == NULL) {
  39294. return MA_INVALID_ARGS;
  39295. }
  39296. MA_ZERO_OBJECT(pFilter);
  39297. if (pConfig == NULL) {
  39298. return MA_INVALID_ARGS;
  39299. }
  39300. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  39301. result = ma_biquad_init_preallocated(&bqConfig, pHeap, &pFilter->bq);
  39302. if (result != MA_SUCCESS) {
  39303. return result;
  39304. }
  39305. return MA_SUCCESS;
  39306. }
  39307. MA_API ma_result ma_hishelf2_init(const ma_hishelf2_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_hishelf2* pFilter)
  39308. {
  39309. ma_result result;
  39310. size_t heapSizeInBytes;
  39311. void* pHeap;
  39312. result = ma_hishelf2_get_heap_size(pConfig, &heapSizeInBytes);
  39313. if (result != MA_SUCCESS) {
  39314. return result;
  39315. }
  39316. if (heapSizeInBytes > 0) {
  39317. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39318. if (pHeap == NULL) {
  39319. return MA_OUT_OF_MEMORY;
  39320. }
  39321. } else {
  39322. pHeap = NULL;
  39323. }
  39324. result = ma_hishelf2_init_preallocated(pConfig, pHeap, pFilter);
  39325. if (result != MA_SUCCESS) {
  39326. ma_free(pHeap, pAllocationCallbacks);
  39327. return result;
  39328. }
  39329. pFilter->bq._ownsHeap = MA_TRUE; /* <-- This will cause the biquad to take ownership of the heap and free it when it's uninitialized. */
  39330. return MA_SUCCESS;
  39331. }
  39332. MA_API void ma_hishelf2_uninit(ma_hishelf2* pFilter, const ma_allocation_callbacks* pAllocationCallbacks)
  39333. {
  39334. if (pFilter == NULL) {
  39335. return;
  39336. }
  39337. ma_biquad_uninit(&pFilter->bq, pAllocationCallbacks); /* <-- This will free the heap allocation. */
  39338. }
  39339. MA_API ma_result ma_hishelf2_reinit(const ma_hishelf2_config* pConfig, ma_hishelf2* pFilter)
  39340. {
  39341. ma_result result;
  39342. ma_biquad_config bqConfig;
  39343. if (pFilter == NULL || pConfig == NULL) {
  39344. return MA_INVALID_ARGS;
  39345. }
  39346. bqConfig = ma_hishelf2__get_biquad_config(pConfig);
  39347. result = ma_biquad_reinit(&bqConfig, &pFilter->bq);
  39348. if (result != MA_SUCCESS) {
  39349. return result;
  39350. }
  39351. return MA_SUCCESS;
  39352. }
  39353. static MA_INLINE void ma_hishelf2_process_pcm_frame_s16(ma_hishelf2* pFilter, ma_int16* pFrameOut, const ma_int16* pFrameIn)
  39354. {
  39355. ma_biquad_process_pcm_frame_s16(&pFilter->bq, pFrameOut, pFrameIn);
  39356. }
  39357. static MA_INLINE void ma_hishelf2_process_pcm_frame_f32(ma_hishelf2* pFilter, float* pFrameOut, const float* pFrameIn)
  39358. {
  39359. ma_biquad_process_pcm_frame_f32(&pFilter->bq, pFrameOut, pFrameIn);
  39360. }
  39361. MA_API ma_result ma_hishelf2_process_pcm_frames(ma_hishelf2* pFilter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39362. {
  39363. if (pFilter == NULL) {
  39364. return MA_INVALID_ARGS;
  39365. }
  39366. return ma_biquad_process_pcm_frames(&pFilter->bq, pFramesOut, pFramesIn, frameCount);
  39367. }
  39368. MA_API ma_uint32 ma_hishelf2_get_latency(const ma_hishelf2* pFilter)
  39369. {
  39370. if (pFilter == NULL) {
  39371. return 0;
  39372. }
  39373. return ma_biquad_get_latency(&pFilter->bq);
  39374. }
  39375. /*
  39376. Delay
  39377. */
  39378. MA_API ma_delay_config ma_delay_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  39379. {
  39380. ma_delay_config config;
  39381. MA_ZERO_OBJECT(&config);
  39382. config.channels = channels;
  39383. config.sampleRate = sampleRate;
  39384. config.delayInFrames = delayInFrames;
  39385. config.delayStart = (decay == 0) ? MA_TRUE : MA_FALSE; /* Delay the start if it looks like we're not configuring an echo. */
  39386. config.wet = 1;
  39387. config.dry = 1;
  39388. config.decay = decay;
  39389. return config;
  39390. }
  39391. MA_API ma_result ma_delay_init(const ma_delay_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_delay* pDelay)
  39392. {
  39393. if (pDelay == NULL) {
  39394. return MA_INVALID_ARGS;
  39395. }
  39396. MA_ZERO_OBJECT(pDelay);
  39397. if (pConfig == NULL) {
  39398. return MA_INVALID_ARGS;
  39399. }
  39400. if (pConfig->decay < 0 || pConfig->decay > 1) {
  39401. return MA_INVALID_ARGS;
  39402. }
  39403. pDelay->config = *pConfig;
  39404. pDelay->bufferSizeInFrames = pConfig->delayInFrames;
  39405. pDelay->cursor = 0;
  39406. pDelay->pBuffer = (float*)ma_malloc((size_t)(pDelay->bufferSizeInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->channels)), pAllocationCallbacks);
  39407. if (pDelay->pBuffer == NULL) {
  39408. return MA_OUT_OF_MEMORY;
  39409. }
  39410. ma_silence_pcm_frames(pDelay->pBuffer, pDelay->bufferSizeInFrames, ma_format_f32, pConfig->channels);
  39411. return MA_SUCCESS;
  39412. }
  39413. MA_API void ma_delay_uninit(ma_delay* pDelay, const ma_allocation_callbacks* pAllocationCallbacks)
  39414. {
  39415. if (pDelay == NULL) {
  39416. return;
  39417. }
  39418. ma_free(pDelay->pBuffer, pAllocationCallbacks);
  39419. }
  39420. MA_API ma_result ma_delay_process_pcm_frames(ma_delay* pDelay, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  39421. {
  39422. ma_uint32 iFrame;
  39423. ma_uint32 iChannel;
  39424. float* pFramesOutF32 = (float*)pFramesOut;
  39425. const float* pFramesInF32 = (const float*)pFramesIn;
  39426. if (pDelay == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  39427. return MA_INVALID_ARGS;
  39428. }
  39429. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39430. for (iChannel = 0; iChannel < pDelay->config.channels; iChannel += 1) {
  39431. ma_uint32 iBuffer = (pDelay->cursor * pDelay->config.channels) + iChannel;
  39432. if (pDelay->config.delayStart) {
  39433. /* Delayed start. */
  39434. /* Read */
  39435. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  39436. /* Feedback */
  39437. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  39438. } else {
  39439. /* Immediate start */
  39440. /* Feedback */
  39441. pDelay->pBuffer[iBuffer] = (pDelay->pBuffer[iBuffer] * pDelay->config.decay) + (pFramesInF32[iChannel] * pDelay->config.dry);
  39442. /* Read */
  39443. pFramesOutF32[iChannel] = pDelay->pBuffer[iBuffer] * pDelay->config.wet;
  39444. }
  39445. }
  39446. pDelay->cursor = (pDelay->cursor + 1) % pDelay->bufferSizeInFrames;
  39447. pFramesOutF32 += pDelay->config.channels;
  39448. pFramesInF32 += pDelay->config.channels;
  39449. }
  39450. return MA_SUCCESS;
  39451. }
  39452. MA_API void ma_delay_set_wet(ma_delay* pDelay, float value)
  39453. {
  39454. if (pDelay == NULL) {
  39455. return;
  39456. }
  39457. pDelay->config.wet = value;
  39458. }
  39459. MA_API float ma_delay_get_wet(const ma_delay* pDelay)
  39460. {
  39461. if (pDelay == NULL) {
  39462. return 0;
  39463. }
  39464. return pDelay->config.wet;
  39465. }
  39466. MA_API void ma_delay_set_dry(ma_delay* pDelay, float value)
  39467. {
  39468. if (pDelay == NULL) {
  39469. return;
  39470. }
  39471. pDelay->config.dry = value;
  39472. }
  39473. MA_API float ma_delay_get_dry(const ma_delay* pDelay)
  39474. {
  39475. if (pDelay == NULL) {
  39476. return 0;
  39477. }
  39478. return pDelay->config.dry;
  39479. }
  39480. MA_API void ma_delay_set_decay(ma_delay* pDelay, float value)
  39481. {
  39482. if (pDelay == NULL) {
  39483. return;
  39484. }
  39485. pDelay->config.decay = value;
  39486. }
  39487. MA_API float ma_delay_get_decay(const ma_delay* pDelay)
  39488. {
  39489. if (pDelay == NULL) {
  39490. return 0;
  39491. }
  39492. return pDelay->config.decay;
  39493. }
  39494. MA_API ma_gainer_config ma_gainer_config_init(ma_uint32 channels, ma_uint32 smoothTimeInFrames)
  39495. {
  39496. ma_gainer_config config;
  39497. MA_ZERO_OBJECT(&config);
  39498. config.channels = channels;
  39499. config.smoothTimeInFrames = smoothTimeInFrames;
  39500. return config;
  39501. }
  39502. typedef struct
  39503. {
  39504. size_t sizeInBytes;
  39505. size_t oldGainsOffset;
  39506. size_t newGainsOffset;
  39507. } ma_gainer_heap_layout;
  39508. static ma_result ma_gainer_get_heap_layout(const ma_gainer_config* pConfig, ma_gainer_heap_layout* pHeapLayout)
  39509. {
  39510. MA_ASSERT(pHeapLayout != NULL);
  39511. MA_ZERO_OBJECT(pHeapLayout);
  39512. if (pConfig == NULL) {
  39513. return MA_INVALID_ARGS;
  39514. }
  39515. if (pConfig->channels == 0) {
  39516. return MA_INVALID_ARGS;
  39517. }
  39518. pHeapLayout->sizeInBytes = 0;
  39519. /* Old gains. */
  39520. pHeapLayout->oldGainsOffset = pHeapLayout->sizeInBytes;
  39521. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  39522. /* New gains. */
  39523. pHeapLayout->newGainsOffset = pHeapLayout->sizeInBytes;
  39524. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  39525. /* Alignment. */
  39526. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  39527. return MA_SUCCESS;
  39528. }
  39529. MA_API ma_result ma_gainer_get_heap_size(const ma_gainer_config* pConfig, size_t* pHeapSizeInBytes)
  39530. {
  39531. ma_result result;
  39532. ma_gainer_heap_layout heapLayout;
  39533. if (pHeapSizeInBytes == NULL) {
  39534. return MA_INVALID_ARGS;
  39535. }
  39536. *pHeapSizeInBytes = 0;
  39537. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  39538. if (result != MA_SUCCESS) {
  39539. return MA_INVALID_ARGS;
  39540. }
  39541. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  39542. return MA_SUCCESS;
  39543. }
  39544. MA_API ma_result ma_gainer_init_preallocated(const ma_gainer_config* pConfig, void* pHeap, ma_gainer* pGainer)
  39545. {
  39546. ma_result result;
  39547. ma_gainer_heap_layout heapLayout;
  39548. ma_uint32 iChannel;
  39549. if (pGainer == NULL) {
  39550. return MA_INVALID_ARGS;
  39551. }
  39552. MA_ZERO_OBJECT(pGainer);
  39553. if (pConfig == NULL || pHeap == NULL) {
  39554. return MA_INVALID_ARGS;
  39555. }
  39556. result = ma_gainer_get_heap_layout(pConfig, &heapLayout);
  39557. if (result != MA_SUCCESS) {
  39558. return result;
  39559. }
  39560. pGainer->_pHeap = pHeap;
  39561. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  39562. pGainer->pOldGains = (float*)ma_offset_ptr(pHeap, heapLayout.oldGainsOffset);
  39563. pGainer->pNewGains = (float*)ma_offset_ptr(pHeap, heapLayout.newGainsOffset);
  39564. pGainer->config = *pConfig;
  39565. pGainer->t = (ma_uint32)-1; /* No interpolation by default. */
  39566. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  39567. pGainer->pOldGains[iChannel] = 1;
  39568. pGainer->pNewGains[iChannel] = 1;
  39569. }
  39570. return MA_SUCCESS;
  39571. }
  39572. MA_API ma_result ma_gainer_init(const ma_gainer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_gainer* pGainer)
  39573. {
  39574. ma_result result;
  39575. size_t heapSizeInBytes;
  39576. void* pHeap;
  39577. result = ma_gainer_get_heap_size(pConfig, &heapSizeInBytes);
  39578. if (result != MA_SUCCESS) {
  39579. return result; /* Failed to retrieve the size of the heap allocation. */
  39580. }
  39581. if (heapSizeInBytes > 0) {
  39582. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  39583. if (pHeap == NULL) {
  39584. return MA_OUT_OF_MEMORY;
  39585. }
  39586. } else {
  39587. pHeap = NULL;
  39588. }
  39589. result = ma_gainer_init_preallocated(pConfig, pHeap, pGainer);
  39590. if (result != MA_SUCCESS) {
  39591. ma_free(pHeap, pAllocationCallbacks);
  39592. return result;
  39593. }
  39594. pGainer->_ownsHeap = MA_TRUE;
  39595. return MA_SUCCESS;
  39596. }
  39597. MA_API void ma_gainer_uninit(ma_gainer* pGainer, const ma_allocation_callbacks* pAllocationCallbacks)
  39598. {
  39599. if (pGainer == NULL) {
  39600. return;
  39601. }
  39602. if (pGainer->_ownsHeap) {
  39603. ma_free(pGainer->_pHeap, pAllocationCallbacks);
  39604. }
  39605. }
  39606. static float ma_gainer_calculate_current_gain(const ma_gainer* pGainer, ma_uint32 channel)
  39607. {
  39608. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  39609. return ma_mix_f32_fast(pGainer->pOldGains[channel], pGainer->pNewGains[channel], a);
  39610. }
  39611. MA_API ma_result ma_gainer_process_pcm_frames(ma_gainer* pGainer, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39612. {
  39613. ma_uint64 iFrame;
  39614. ma_uint32 iChannel;
  39615. float* pFramesOutF32 = (float*)pFramesOut;
  39616. const float* pFramesInF32 = (const float*)pFramesIn;
  39617. if (pGainer == NULL) {
  39618. return MA_INVALID_ARGS;
  39619. }
  39620. if (pGainer->t >= pGainer->config.smoothTimeInFrames) {
  39621. /* Fast path. No gain calculation required. */
  39622. ma_copy_and_apply_volume_factor_per_channel_f32(pFramesOutF32, pFramesInF32, frameCount, pGainer->config.channels, pGainer->pNewGains);
  39623. /* Now that some frames have been processed we need to make sure future changes to the gain are interpolated. */
  39624. if (pGainer->t == (ma_uint32)-1) {
  39625. pGainer->t = pGainer->config.smoothTimeInFrames;
  39626. }
  39627. } else {
  39628. /* Slow path. Need to interpolate the gain for each channel individually. */
  39629. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  39630. if (pFramesOut != NULL && pFramesIn != NULL) {
  39631. float a = (float)pGainer->t / pGainer->config.smoothTimeInFrames;
  39632. float d = 1.0f / pGainer->config.smoothTimeInFrames;
  39633. ma_uint32 channelCount = pGainer->config.channels;
  39634. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39635. for (iChannel = 0; iChannel < channelCount; iChannel += 1) {
  39636. pFramesOutF32[iChannel] = pFramesInF32[iChannel] * ma_mix_f32_fast(pGainer->pOldGains[iChannel], pGainer->pNewGains[iChannel], a);
  39637. }
  39638. pFramesOutF32 += channelCount;
  39639. pFramesInF32 += channelCount;
  39640. a += d;
  39641. if (a > 1) {
  39642. a = 1;
  39643. }
  39644. }
  39645. }
  39646. pGainer->t = (ma_uint32)ma_min(pGainer->t + frameCount, pGainer->config.smoothTimeInFrames);
  39647. #if 0 /* Reference implementation. */
  39648. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39649. /* We can allow the input and output buffers to be null in which case we'll just update the internal timer. */
  39650. if (pFramesOut != NULL && pFramesIn != NULL) {
  39651. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  39652. pFramesOutF32[iFrame*pGainer->config.channels + iChannel] = pFramesInF32[iFrame*pGainer->config.channels + iChannel] * ma_gainer_calculate_current_gain(pGainer, iChannel);
  39653. }
  39654. }
  39655. /* Move interpolation time forward, but don't go beyond our smoothing time. */
  39656. pGainer->t = ma_min(pGainer->t + 1, pGainer->config.smoothTimeInFrames);
  39657. }
  39658. #endif
  39659. }
  39660. return MA_SUCCESS;
  39661. }
  39662. static void ma_gainer_set_gain_by_index(ma_gainer* pGainer, float newGain, ma_uint32 iChannel)
  39663. {
  39664. pGainer->pOldGains[iChannel] = ma_gainer_calculate_current_gain(pGainer, iChannel);
  39665. pGainer->pNewGains[iChannel] = newGain;
  39666. }
  39667. static void ma_gainer_reset_smoothing_time(ma_gainer* pGainer)
  39668. {
  39669. if (pGainer->t == (ma_uint32)-1) {
  39670. pGainer->t = pGainer->config.smoothTimeInFrames; /* No smoothing required for initial gains setting. */
  39671. } else {
  39672. pGainer->t = 0;
  39673. }
  39674. }
  39675. MA_API ma_result ma_gainer_set_gain(ma_gainer* pGainer, float newGain)
  39676. {
  39677. ma_uint32 iChannel;
  39678. if (pGainer == NULL) {
  39679. return MA_INVALID_ARGS;
  39680. }
  39681. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  39682. ma_gainer_set_gain_by_index(pGainer, newGain, iChannel);
  39683. }
  39684. /* 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. */
  39685. ma_gainer_reset_smoothing_time(pGainer);
  39686. return MA_SUCCESS;
  39687. }
  39688. MA_API ma_result ma_gainer_set_gains(ma_gainer* pGainer, float* pNewGains)
  39689. {
  39690. ma_uint32 iChannel;
  39691. if (pGainer == NULL || pNewGains == NULL) {
  39692. return MA_INVALID_ARGS;
  39693. }
  39694. for (iChannel = 0; iChannel < pGainer->config.channels; iChannel += 1) {
  39695. ma_gainer_set_gain_by_index(pGainer, pNewGains[iChannel], iChannel);
  39696. }
  39697. /* 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. */
  39698. ma_gainer_reset_smoothing_time(pGainer);
  39699. return MA_SUCCESS;
  39700. }
  39701. MA_API ma_panner_config ma_panner_config_init(ma_format format, ma_uint32 channels)
  39702. {
  39703. ma_panner_config config;
  39704. MA_ZERO_OBJECT(&config);
  39705. config.format = format;
  39706. config.channels = channels;
  39707. 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. */
  39708. config.pan = 0;
  39709. return config;
  39710. }
  39711. MA_API ma_result ma_panner_init(const ma_panner_config* pConfig, ma_panner* pPanner)
  39712. {
  39713. if (pPanner == NULL) {
  39714. return MA_INVALID_ARGS;
  39715. }
  39716. MA_ZERO_OBJECT(pPanner);
  39717. if (pConfig == NULL) {
  39718. return MA_INVALID_ARGS;
  39719. }
  39720. pPanner->format = pConfig->format;
  39721. pPanner->channels = pConfig->channels;
  39722. pPanner->mode = pConfig->mode;
  39723. pPanner->pan = pConfig->pan;
  39724. return MA_SUCCESS;
  39725. }
  39726. static void ma_stereo_balance_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  39727. {
  39728. ma_uint64 iFrame;
  39729. if (pan > 0) {
  39730. float factor = 1.0f - pan;
  39731. if (pFramesOut == pFramesIn) {
  39732. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39733. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  39734. }
  39735. } else {
  39736. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39737. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0] * factor;
  39738. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1];
  39739. }
  39740. }
  39741. } else {
  39742. float factor = 1.0f + pan;
  39743. if (pFramesOut == pFramesIn) {
  39744. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39745. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  39746. }
  39747. } else {
  39748. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39749. pFramesOut[iFrame*2 + 0] = pFramesIn[iFrame*2 + 0];
  39750. pFramesOut[iFrame*2 + 1] = pFramesIn[iFrame*2 + 1] * factor;
  39751. }
  39752. }
  39753. }
  39754. }
  39755. static void ma_stereo_balance_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  39756. {
  39757. if (pan == 0) {
  39758. /* Fast path. No panning required. */
  39759. if (pFramesOut == pFramesIn) {
  39760. /* No-op */
  39761. } else {
  39762. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  39763. }
  39764. return;
  39765. }
  39766. switch (format) {
  39767. case ma_format_f32: ma_stereo_balance_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  39768. /* Unknown format. Just copy. */
  39769. default:
  39770. {
  39771. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  39772. } break;
  39773. }
  39774. }
  39775. static void ma_stereo_pan_pcm_frames_f32(float* pFramesOut, const float* pFramesIn, ma_uint64 frameCount, float pan)
  39776. {
  39777. ma_uint64 iFrame;
  39778. if (pan > 0) {
  39779. float factorL0 = 1.0f - pan;
  39780. float factorL1 = 0.0f + pan;
  39781. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39782. float sample0 = (pFramesIn[iFrame*2 + 0] * factorL0);
  39783. float sample1 = (pFramesIn[iFrame*2 + 0] * factorL1) + pFramesIn[iFrame*2 + 1];
  39784. pFramesOut[iFrame*2 + 0] = sample0;
  39785. pFramesOut[iFrame*2 + 1] = sample1;
  39786. }
  39787. } else {
  39788. float factorR0 = 0.0f - pan;
  39789. float factorR1 = 1.0f + pan;
  39790. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39791. float sample0 = pFramesIn[iFrame*2 + 0] + (pFramesIn[iFrame*2 + 1] * factorR0);
  39792. float sample1 = (pFramesIn[iFrame*2 + 1] * factorR1);
  39793. pFramesOut[iFrame*2 + 0] = sample0;
  39794. pFramesOut[iFrame*2 + 1] = sample1;
  39795. }
  39796. }
  39797. }
  39798. static void ma_stereo_pan_pcm_frames(void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount, ma_format format, float pan)
  39799. {
  39800. if (pan == 0) {
  39801. /* Fast path. No panning required. */
  39802. if (pFramesOut == pFramesIn) {
  39803. /* No-op */
  39804. } else {
  39805. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  39806. }
  39807. return;
  39808. }
  39809. switch (format) {
  39810. case ma_format_f32: ma_stereo_pan_pcm_frames_f32((float*)pFramesOut, (float*)pFramesIn, frameCount, pan); break;
  39811. /* Unknown format. Just copy. */
  39812. default:
  39813. {
  39814. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, format, 2);
  39815. } break;
  39816. }
  39817. }
  39818. MA_API ma_result ma_panner_process_pcm_frames(ma_panner* pPanner, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39819. {
  39820. if (pPanner == NULL || pFramesOut == NULL || pFramesIn == NULL) {
  39821. return MA_INVALID_ARGS;
  39822. }
  39823. if (pPanner->channels == 2) {
  39824. /* Stereo case. For now assume channel 0 is left and channel right is 1, but should probably add support for a channel map. */
  39825. if (pPanner->mode == ma_pan_mode_balance) {
  39826. ma_stereo_balance_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  39827. } else {
  39828. ma_stereo_pan_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->pan);
  39829. }
  39830. } else {
  39831. if (pPanner->channels == 1) {
  39832. /* Panning has no effect on mono streams. */
  39833. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  39834. } else {
  39835. /* For now we're not going to support non-stereo set ups. Not sure how I want to handle this case just yet. */
  39836. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pPanner->format, pPanner->channels);
  39837. }
  39838. }
  39839. return MA_SUCCESS;
  39840. }
  39841. MA_API void ma_panner_set_mode(ma_panner* pPanner, ma_pan_mode mode)
  39842. {
  39843. if (pPanner == NULL) {
  39844. return;
  39845. }
  39846. pPanner->mode = mode;
  39847. }
  39848. MA_API ma_pan_mode ma_panner_get_mode(const ma_panner* pPanner)
  39849. {
  39850. if (pPanner == NULL) {
  39851. return ma_pan_mode_balance;
  39852. }
  39853. return pPanner->mode;
  39854. }
  39855. MA_API void ma_panner_set_pan(ma_panner* pPanner, float pan)
  39856. {
  39857. if (pPanner == NULL) {
  39858. return;
  39859. }
  39860. pPanner->pan = ma_clamp(pan, -1.0f, 1.0f);
  39861. }
  39862. MA_API float ma_panner_get_pan(const ma_panner* pPanner)
  39863. {
  39864. if (pPanner == NULL) {
  39865. return 0;
  39866. }
  39867. return pPanner->pan;
  39868. }
  39869. MA_API ma_fader_config ma_fader_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  39870. {
  39871. ma_fader_config config;
  39872. MA_ZERO_OBJECT(&config);
  39873. config.format = format;
  39874. config.channels = channels;
  39875. config.sampleRate = sampleRate;
  39876. return config;
  39877. }
  39878. MA_API ma_result ma_fader_init(const ma_fader_config* pConfig, ma_fader* pFader)
  39879. {
  39880. if (pFader == NULL) {
  39881. return MA_INVALID_ARGS;
  39882. }
  39883. MA_ZERO_OBJECT(pFader);
  39884. if (pConfig == NULL) {
  39885. return MA_INVALID_ARGS;
  39886. }
  39887. /* Only f32 is supported for now. */
  39888. if (pConfig->format != ma_format_f32) {
  39889. return MA_INVALID_ARGS;
  39890. }
  39891. pFader->config = *pConfig;
  39892. pFader->volumeBeg = 1;
  39893. pFader->volumeEnd = 1;
  39894. pFader->lengthInFrames = 0;
  39895. pFader->cursorInFrames = 0;
  39896. return MA_SUCCESS;
  39897. }
  39898. MA_API ma_result ma_fader_process_pcm_frames(ma_fader* pFader, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  39899. {
  39900. if (pFader == NULL) {
  39901. return MA_INVALID_ARGS;
  39902. }
  39903. /*
  39904. For now we need to clamp frameCount so that the cursor never overflows 32-bits. This is required for
  39905. the conversion to a float which we use for the linear interpolation. This might be changed later.
  39906. */
  39907. if (frameCount + pFader->cursorInFrames > UINT_MAX) {
  39908. frameCount = UINT_MAX - pFader->cursorInFrames;
  39909. }
  39910. /* Optimized path if volumeBeg and volumeEnd are equal. */
  39911. if (pFader->volumeBeg == pFader->volumeEnd) {
  39912. if (pFader->volumeBeg == 1) {
  39913. /* Straight copy. */
  39914. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels);
  39915. } else {
  39916. /* Copy with volume. */
  39917. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd);
  39918. }
  39919. } else {
  39920. /* Slower path. Volumes are different, so may need to do an interpolation. */
  39921. if (pFader->cursorInFrames >= pFader->lengthInFrames) {
  39922. /* Fast path. We've gone past the end of the fade period so just apply the end volume to all samples. */
  39923. ma_copy_and_apply_volume_and_clip_pcm_frames(pFramesOut, pFramesIn, frameCount, pFader->config.format, pFader->config.channels, pFader->volumeEnd);
  39924. } else {
  39925. /* Slow path. This is where we do the actual fading. */
  39926. ma_uint64 iFrame;
  39927. ma_uint32 iChannel;
  39928. /* For now we only support f32. Support for other formats will be added later. */
  39929. if (pFader->config.format == ma_format_f32) {
  39930. const float* pFramesInF32 = (const float*)pFramesIn;
  39931. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  39932. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  39933. 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. */
  39934. float volume = ma_mix_f32_fast(pFader->volumeBeg, pFader->volumeEnd, a);
  39935. for (iChannel = 0; iChannel < pFader->config.channels; iChannel += 1) {
  39936. pFramesOutF32[iFrame*pFader->config.channels + iChannel] = pFramesInF32[iFrame*pFader->config.channels + iChannel] * volume;
  39937. }
  39938. }
  39939. } else {
  39940. return MA_NOT_IMPLEMENTED;
  39941. }
  39942. }
  39943. }
  39944. pFader->cursorInFrames += frameCount;
  39945. return MA_SUCCESS;
  39946. }
  39947. MA_API void ma_fader_get_data_format(const ma_fader* pFader, ma_format* pFormat, ma_uint32* pChannels, ma_uint32* pSampleRate)
  39948. {
  39949. if (pFader == NULL) {
  39950. return;
  39951. }
  39952. if (pFormat != NULL) {
  39953. *pFormat = pFader->config.format;
  39954. }
  39955. if (pChannels != NULL) {
  39956. *pChannels = pFader->config.channels;
  39957. }
  39958. if (pSampleRate != NULL) {
  39959. *pSampleRate = pFader->config.sampleRate;
  39960. }
  39961. }
  39962. MA_API void ma_fader_set_fade(ma_fader* pFader, float volumeBeg, float volumeEnd, ma_uint64 lengthInFrames)
  39963. {
  39964. if (pFader == NULL) {
  39965. return;
  39966. }
  39967. /* If the volume is negative, use current volume. */
  39968. if (volumeBeg < 0) {
  39969. volumeBeg = ma_fader_get_current_volume(pFader);
  39970. }
  39971. /*
  39972. The length needs to be clamped to 32-bits due to how we convert it to a float for linear
  39973. interpolation reasons. I might change this requirement later, but for now it's not important.
  39974. */
  39975. if (lengthInFrames > UINT_MAX) {
  39976. lengthInFrames = UINT_MAX;
  39977. }
  39978. pFader->volumeBeg = volumeBeg;
  39979. pFader->volumeEnd = volumeEnd;
  39980. pFader->lengthInFrames = lengthInFrames;
  39981. pFader->cursorInFrames = 0; /* Reset cursor. */
  39982. }
  39983. MA_API float ma_fader_get_current_volume(ma_fader* pFader)
  39984. {
  39985. if (pFader == NULL) {
  39986. return 0.0f;
  39987. }
  39988. /* The current volume depends on the position of the cursor. */
  39989. if (pFader->cursorInFrames == 0) {
  39990. return pFader->volumeBeg;
  39991. } else if (pFader->cursorInFrames >= pFader->lengthInFrames) {
  39992. return pFader->volumeEnd;
  39993. } else {
  39994. /* 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. */
  39995. 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(). */
  39996. }
  39997. }
  39998. MA_API ma_vec3f ma_vec3f_init_3f(float x, float y, float z)
  39999. {
  40000. ma_vec3f v;
  40001. v.x = x;
  40002. v.y = y;
  40003. v.z = z;
  40004. return v;
  40005. }
  40006. MA_API ma_vec3f ma_vec3f_sub(ma_vec3f a, ma_vec3f b)
  40007. {
  40008. return ma_vec3f_init_3f(
  40009. a.x - b.x,
  40010. a.y - b.y,
  40011. a.z - b.z
  40012. );
  40013. }
  40014. MA_API ma_vec3f ma_vec3f_neg(ma_vec3f a)
  40015. {
  40016. return ma_vec3f_init_3f(
  40017. -a.x,
  40018. -a.y,
  40019. -a.z
  40020. );
  40021. }
  40022. MA_API float ma_vec3f_dot(ma_vec3f a, ma_vec3f b)
  40023. {
  40024. return a.x*b.x + a.y*b.y + a.z*b.z;
  40025. }
  40026. MA_API float ma_vec3f_len2(ma_vec3f v)
  40027. {
  40028. return ma_vec3f_dot(v, v);
  40029. }
  40030. MA_API float ma_vec3f_len(ma_vec3f v)
  40031. {
  40032. return (float)ma_sqrtd(ma_vec3f_len2(v));
  40033. }
  40034. MA_API float ma_vec3f_dist(ma_vec3f a, ma_vec3f b)
  40035. {
  40036. return ma_vec3f_len(ma_vec3f_sub(a, b));
  40037. }
  40038. MA_API ma_vec3f ma_vec3f_normalize(ma_vec3f v)
  40039. {
  40040. float f;
  40041. float l = ma_vec3f_len(v);
  40042. if (l == 0) {
  40043. return ma_vec3f_init_3f(0, 0, 0);
  40044. }
  40045. f = 1 / l;
  40046. v.x *= f;
  40047. v.y *= f;
  40048. v.z *= f;
  40049. return v;
  40050. }
  40051. MA_API ma_vec3f ma_vec3f_cross(ma_vec3f a, ma_vec3f b)
  40052. {
  40053. return ma_vec3f_init_3f(
  40054. a.y*b.z - a.z*b.y,
  40055. a.z*b.x - a.x*b.z,
  40056. a.x*b.y - a.y*b.x
  40057. );
  40058. }
  40059. 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);
  40060. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition);
  40061. #ifndef MA_DEFAULT_SPEED_OF_SOUND
  40062. #define MA_DEFAULT_SPEED_OF_SOUND 343.3f
  40063. #endif
  40064. /*
  40065. These vectors represent the direction that speakers are facing from the center point. They're used
  40066. for panning in the spatializer. Must be normalized.
  40067. */
  40068. static ma_vec3f g_maChannelDirections[MA_CHANNEL_POSITION_COUNT] = {
  40069. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_NONE */
  40070. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_MONO */
  40071. {-0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_LEFT */
  40072. {+0.7071f, 0.0f, -0.7071f }, /* MA_CHANNEL_FRONT_RIGHT */
  40073. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_FRONT_CENTER */
  40074. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_LFE */
  40075. {-0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_LEFT */
  40076. {+0.7071f, 0.0f, +0.7071f }, /* MA_CHANNEL_BACK_RIGHT */
  40077. {-0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  40078. {+0.3162f, 0.0f, -0.9487f }, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  40079. { 0.0f, 0.0f, +1.0f }, /* MA_CHANNEL_BACK_CENTER */
  40080. {-1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_LEFT */
  40081. {+1.0f, 0.0f, 0.0f }, /* MA_CHANNEL_SIDE_RIGHT */
  40082. { 0.0f, +1.0f, 0.0f }, /* MA_CHANNEL_TOP_CENTER */
  40083. {-0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_LEFT */
  40084. { 0.0f, +0.7071f, -0.7071f }, /* MA_CHANNEL_TOP_FRONT_CENTER */
  40085. {+0.5774f, +0.5774f, -0.5774f }, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  40086. {-0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_LEFT */
  40087. { 0.0f, +0.7071f, +0.7071f }, /* MA_CHANNEL_TOP_BACK_CENTER */
  40088. {+0.5774f, +0.5774f, +0.5774f }, /* MA_CHANNEL_TOP_BACK_RIGHT */
  40089. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_0 */
  40090. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_1 */
  40091. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_2 */
  40092. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_3 */
  40093. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_4 */
  40094. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_5 */
  40095. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_6 */
  40096. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_7 */
  40097. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_8 */
  40098. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_9 */
  40099. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_10 */
  40100. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_11 */
  40101. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_12 */
  40102. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_13 */
  40103. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_14 */
  40104. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_15 */
  40105. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_16 */
  40106. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_17 */
  40107. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_18 */
  40108. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_19 */
  40109. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_20 */
  40110. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_21 */
  40111. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_22 */
  40112. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_23 */
  40113. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_24 */
  40114. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_25 */
  40115. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_26 */
  40116. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_27 */
  40117. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_28 */
  40118. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_29 */
  40119. { 0.0f, 0.0f, -1.0f }, /* MA_CHANNEL_AUX_30 */
  40120. { 0.0f, 0.0f, -1.0f } /* MA_CHANNEL_AUX_31 */
  40121. };
  40122. static ma_vec3f ma_get_channel_direction(ma_channel channel)
  40123. {
  40124. if (channel >= MA_CHANNEL_POSITION_COUNT) {
  40125. return ma_vec3f_init_3f(0, 0, -1);
  40126. } else {
  40127. return g_maChannelDirections[channel];
  40128. }
  40129. }
  40130. static float ma_attenuation_inverse(float distance, float minDistance, float maxDistance, float rolloff)
  40131. {
  40132. if (minDistance >= maxDistance) {
  40133. return 1; /* To avoid division by zero. Do not attenuate. */
  40134. }
  40135. return minDistance / (minDistance + rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance));
  40136. }
  40137. static float ma_attenuation_linear(float distance, float minDistance, float maxDistance, float rolloff)
  40138. {
  40139. if (minDistance >= maxDistance) {
  40140. return 1; /* To avoid division by zero. Do not attenuate. */
  40141. }
  40142. return 1 - rolloff * (ma_clamp(distance, minDistance, maxDistance) - minDistance) / (maxDistance - minDistance);
  40143. }
  40144. static float ma_attenuation_exponential(float distance, float minDistance, float maxDistance, float rolloff)
  40145. {
  40146. if (minDistance >= maxDistance) {
  40147. return 1; /* To avoid division by zero. Do not attenuate. */
  40148. }
  40149. return (float)ma_powd(ma_clamp(distance, minDistance, maxDistance) / minDistance, -rolloff);
  40150. }
  40151. /*
  40152. Dopper Effect calculation taken from the OpenAL spec, with two main differences:
  40153. 1) The source to listener vector will have already been calcualted at an earlier step so we can
  40154. just use that directly. We need only the position of the source relative to the origin.
  40155. 2) We don't scale by a frequency because we actually just want the ratio which we'll plug straight
  40156. into the resampler directly.
  40157. */
  40158. static float ma_doppler_pitch(ma_vec3f relativePosition, ma_vec3f sourceVelocity, ma_vec3f listenVelocity, float speedOfSound, float dopplerFactor)
  40159. {
  40160. float len;
  40161. float vls;
  40162. float vss;
  40163. len = ma_vec3f_len(relativePosition);
  40164. /*
  40165. There's a case where the position of the source will be right on top of the listener in which
  40166. case the length will be 0 and we'll end up with a division by zero. We can just return a ratio
  40167. of 1.0 in this case. This is not considered in the OpenAL spec, but is necessary.
  40168. */
  40169. if (len == 0) {
  40170. return 1.0;
  40171. }
  40172. vls = ma_vec3f_dot(relativePosition, listenVelocity) / len;
  40173. vss = ma_vec3f_dot(relativePosition, sourceVelocity) / len;
  40174. vls = ma_min(vls, speedOfSound / dopplerFactor);
  40175. vss = ma_min(vss, speedOfSound / dopplerFactor);
  40176. return (speedOfSound - dopplerFactor*vls) / (speedOfSound - dopplerFactor*vss);
  40177. }
  40178. static void ma_get_default_channel_map_for_spatializer(ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channelCount)
  40179. {
  40180. /*
  40181. Special case for stereo. Want to default the left and right speakers to side left and side
  40182. right so that they're facing directly down the X axis rather than slightly forward. Not
  40183. doing this will result in sounds being quieter when behind the listener. This might
  40184. actually be good for some scenerios, but I don't think it's an appropriate default because
  40185. it can be a bit unexpected.
  40186. */
  40187. if (channelCount == 2) {
  40188. pChannelMap[0] = MA_CHANNEL_SIDE_LEFT;
  40189. pChannelMap[1] = MA_CHANNEL_SIDE_RIGHT;
  40190. } else {
  40191. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channelCount);
  40192. }
  40193. }
  40194. MA_API ma_spatializer_listener_config ma_spatializer_listener_config_init(ma_uint32 channelsOut)
  40195. {
  40196. ma_spatializer_listener_config config;
  40197. MA_ZERO_OBJECT(&config);
  40198. config.channelsOut = channelsOut;
  40199. config.pChannelMapOut = NULL;
  40200. config.handedness = ma_handedness_right;
  40201. config.worldUp = ma_vec3f_init_3f(0, 1, 0);
  40202. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  40203. config.coneOuterAngleInRadians = 6.283185f; /* 360 degrees. */
  40204. config.coneOuterGain = 0;
  40205. config.speedOfSound = 343.3f; /* Same as OpenAL. Used for doppler effect. */
  40206. return config;
  40207. }
  40208. typedef struct
  40209. {
  40210. size_t sizeInBytes;
  40211. size_t channelMapOutOffset;
  40212. } ma_spatializer_listener_heap_layout;
  40213. static ma_result ma_spatializer_listener_get_heap_layout(const ma_spatializer_listener_config* pConfig, ma_spatializer_listener_heap_layout* pHeapLayout)
  40214. {
  40215. MA_ASSERT(pHeapLayout != NULL);
  40216. MA_ZERO_OBJECT(pHeapLayout);
  40217. if (pConfig == NULL) {
  40218. return MA_INVALID_ARGS;
  40219. }
  40220. if (pConfig->channelsOut == 0) {
  40221. return MA_INVALID_ARGS;
  40222. }
  40223. pHeapLayout->sizeInBytes = 0;
  40224. /* Channel map. We always need this, even for passthroughs. */
  40225. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  40226. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapOut) * pConfig->channelsOut);
  40227. return MA_SUCCESS;
  40228. }
  40229. MA_API ma_result ma_spatializer_listener_get_heap_size(const ma_spatializer_listener_config* pConfig, size_t* pHeapSizeInBytes)
  40230. {
  40231. ma_result result;
  40232. ma_spatializer_listener_heap_layout heapLayout;
  40233. if (pHeapSizeInBytes == NULL) {
  40234. return MA_INVALID_ARGS;
  40235. }
  40236. *pHeapSizeInBytes = 0;
  40237. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  40238. if (result != MA_SUCCESS) {
  40239. return result;
  40240. }
  40241. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  40242. return MA_SUCCESS;
  40243. }
  40244. MA_API ma_result ma_spatializer_listener_init_preallocated(const ma_spatializer_listener_config* pConfig, void* pHeap, ma_spatializer_listener* pListener)
  40245. {
  40246. ma_result result;
  40247. ma_spatializer_listener_heap_layout heapLayout;
  40248. if (pListener == NULL) {
  40249. return MA_INVALID_ARGS;
  40250. }
  40251. MA_ZERO_OBJECT(pListener);
  40252. result = ma_spatializer_listener_get_heap_layout(pConfig, &heapLayout);
  40253. if (result != MA_SUCCESS) {
  40254. return result;
  40255. }
  40256. pListener->_pHeap = pHeap;
  40257. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  40258. pListener->config = *pConfig;
  40259. pListener->position = ma_vec3f_init_3f(0, 0, 0);
  40260. pListener->direction = ma_vec3f_init_3f(0, 0, -1);
  40261. pListener->velocity = ma_vec3f_init_3f(0, 0, 0);
  40262. pListener->isEnabled = MA_TRUE;
  40263. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  40264. if (pListener->config.handedness == ma_handedness_left) {
  40265. pListener->direction = ma_vec3f_neg(pListener->direction);
  40266. }
  40267. /* We must always have a valid channel map. */
  40268. pListener->config.pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  40269. /* Use a slightly different default channel map for stereo. */
  40270. if (pConfig->pChannelMapOut == NULL) {
  40271. ma_get_default_channel_map_for_spatializer(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->channelsOut);
  40272. } else {
  40273. ma_channel_map_copy_or_default(pListener->config.pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  40274. }
  40275. return MA_SUCCESS;
  40276. }
  40277. MA_API ma_result ma_spatializer_listener_init(const ma_spatializer_listener_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer_listener* pListener)
  40278. {
  40279. ma_result result;
  40280. size_t heapSizeInBytes;
  40281. void* pHeap;
  40282. result = ma_spatializer_listener_get_heap_size(pConfig, &heapSizeInBytes);
  40283. if (result != MA_SUCCESS) {
  40284. return result;
  40285. }
  40286. if (heapSizeInBytes > 0) {
  40287. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40288. if (pHeap == NULL) {
  40289. return MA_OUT_OF_MEMORY;
  40290. }
  40291. } else {
  40292. pHeap = NULL;
  40293. }
  40294. result = ma_spatializer_listener_init_preallocated(pConfig, pHeap, pListener);
  40295. if (result != MA_SUCCESS) {
  40296. ma_free(pHeap, pAllocationCallbacks);
  40297. return result;
  40298. }
  40299. pListener->_ownsHeap = MA_TRUE;
  40300. return MA_SUCCESS;
  40301. }
  40302. MA_API void ma_spatializer_listener_uninit(ma_spatializer_listener* pListener, const ma_allocation_callbacks* pAllocationCallbacks)
  40303. {
  40304. if (pListener == NULL) {
  40305. return;
  40306. }
  40307. if (pListener->_ownsHeap) {
  40308. ma_free(pListener->_pHeap, pAllocationCallbacks);
  40309. }
  40310. }
  40311. MA_API ma_channel* ma_spatializer_listener_get_channel_map(ma_spatializer_listener* pListener)
  40312. {
  40313. if (pListener == NULL) {
  40314. return NULL;
  40315. }
  40316. return pListener->config.pChannelMapOut;
  40317. }
  40318. MA_API void ma_spatializer_listener_set_cone(ma_spatializer_listener* pListener, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  40319. {
  40320. if (pListener == NULL) {
  40321. return;
  40322. }
  40323. pListener->config.coneInnerAngleInRadians = innerAngleInRadians;
  40324. pListener->config.coneOuterAngleInRadians = outerAngleInRadians;
  40325. pListener->config.coneOuterGain = outerGain;
  40326. }
  40327. MA_API void ma_spatializer_listener_get_cone(const ma_spatializer_listener* pListener, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  40328. {
  40329. if (pListener == NULL) {
  40330. return;
  40331. }
  40332. if (pInnerAngleInRadians != NULL) {
  40333. *pInnerAngleInRadians = pListener->config.coneInnerAngleInRadians;
  40334. }
  40335. if (pOuterAngleInRadians != NULL) {
  40336. *pOuterAngleInRadians = pListener->config.coneOuterAngleInRadians;
  40337. }
  40338. if (pOuterGain != NULL) {
  40339. *pOuterGain = pListener->config.coneOuterGain;
  40340. }
  40341. }
  40342. MA_API void ma_spatializer_listener_set_position(ma_spatializer_listener* pListener, float x, float y, float z)
  40343. {
  40344. if (pListener == NULL) {
  40345. return;
  40346. }
  40347. pListener->position = ma_vec3f_init_3f(x, y, z);
  40348. }
  40349. MA_API ma_vec3f ma_spatializer_listener_get_position(const ma_spatializer_listener* pListener)
  40350. {
  40351. if (pListener == NULL) {
  40352. return ma_vec3f_init_3f(0, 0, 0);
  40353. }
  40354. return pListener->position;
  40355. }
  40356. MA_API void ma_spatializer_listener_set_direction(ma_spatializer_listener* pListener, float x, float y, float z)
  40357. {
  40358. if (pListener == NULL) {
  40359. return;
  40360. }
  40361. pListener->direction = ma_vec3f_init_3f(x, y, z);
  40362. }
  40363. MA_API ma_vec3f ma_spatializer_listener_get_direction(const ma_spatializer_listener* pListener)
  40364. {
  40365. if (pListener == NULL) {
  40366. return ma_vec3f_init_3f(0, 0, -1);
  40367. }
  40368. return pListener->direction;
  40369. }
  40370. MA_API void ma_spatializer_listener_set_velocity(ma_spatializer_listener* pListener, float x, float y, float z)
  40371. {
  40372. if (pListener == NULL) {
  40373. return;
  40374. }
  40375. pListener->velocity = ma_vec3f_init_3f(x, y, z);
  40376. }
  40377. MA_API ma_vec3f ma_spatializer_listener_get_velocity(const ma_spatializer_listener* pListener)
  40378. {
  40379. if (pListener == NULL) {
  40380. return ma_vec3f_init_3f(0, 0, 0);
  40381. }
  40382. return pListener->velocity;
  40383. }
  40384. MA_API void ma_spatializer_listener_set_speed_of_sound(ma_spatializer_listener* pListener, float speedOfSound)
  40385. {
  40386. if (pListener == NULL) {
  40387. return;
  40388. }
  40389. pListener->config.speedOfSound = speedOfSound;
  40390. }
  40391. MA_API float ma_spatializer_listener_get_speed_of_sound(const ma_spatializer_listener* pListener)
  40392. {
  40393. if (pListener == NULL) {
  40394. return 0;
  40395. }
  40396. return pListener->config.speedOfSound;
  40397. }
  40398. MA_API void ma_spatializer_listener_set_world_up(ma_spatializer_listener* pListener, float x, float y, float z)
  40399. {
  40400. if (pListener == NULL) {
  40401. return;
  40402. }
  40403. pListener->config.worldUp = ma_vec3f_init_3f(x, y, z);
  40404. }
  40405. MA_API ma_vec3f ma_spatializer_listener_get_world_up(const ma_spatializer_listener* pListener)
  40406. {
  40407. if (pListener == NULL) {
  40408. return ma_vec3f_init_3f(0, 1, 0);
  40409. }
  40410. return pListener->config.worldUp;
  40411. }
  40412. MA_API void ma_spatializer_listener_set_enabled(ma_spatializer_listener* pListener, ma_bool32 isEnabled)
  40413. {
  40414. if (pListener == NULL) {
  40415. return;
  40416. }
  40417. pListener->isEnabled = isEnabled;
  40418. }
  40419. MA_API ma_bool32 ma_spatializer_listener_is_enabled(const ma_spatializer_listener* pListener)
  40420. {
  40421. if (pListener == NULL) {
  40422. return MA_FALSE;
  40423. }
  40424. return pListener->isEnabled;
  40425. }
  40426. MA_API ma_spatializer_config ma_spatializer_config_init(ma_uint32 channelsIn, ma_uint32 channelsOut)
  40427. {
  40428. ma_spatializer_config config;
  40429. MA_ZERO_OBJECT(&config);
  40430. config.channelsIn = channelsIn;
  40431. config.channelsOut = channelsOut;
  40432. config.pChannelMapIn = NULL;
  40433. config.attenuationModel = ma_attenuation_model_inverse;
  40434. config.positioning = ma_positioning_absolute;
  40435. config.handedness = ma_handedness_right;
  40436. config.minGain = 0;
  40437. config.maxGain = 1;
  40438. config.minDistance = 1;
  40439. config.maxDistance = MA_FLT_MAX;
  40440. config.rolloff = 1;
  40441. config.coneInnerAngleInRadians = 6.283185f; /* 360 degrees. */
  40442. config.coneOuterAngleInRadians = 6.283185f; /* 360 degress. */
  40443. config.coneOuterGain = 0.0f;
  40444. config.dopplerFactor = 1;
  40445. config.directionalAttenuationFactor = 1;
  40446. config.gainSmoothTimeInFrames = 360; /* 7.5ms @ 48K. */
  40447. return config;
  40448. }
  40449. static ma_gainer_config ma_spatializer_gainer_config_init(const ma_spatializer_config* pConfig)
  40450. {
  40451. MA_ASSERT(pConfig != NULL);
  40452. return ma_gainer_config_init(pConfig->channelsOut, pConfig->gainSmoothTimeInFrames);
  40453. }
  40454. static ma_result ma_spatializer_validate_config(const ma_spatializer_config* pConfig)
  40455. {
  40456. MA_ASSERT(pConfig != NULL);
  40457. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  40458. return MA_INVALID_ARGS;
  40459. }
  40460. return MA_SUCCESS;
  40461. }
  40462. typedef struct
  40463. {
  40464. size_t sizeInBytes;
  40465. size_t channelMapInOffset;
  40466. size_t newChannelGainsOffset;
  40467. size_t gainerOffset;
  40468. } ma_spatializer_heap_layout;
  40469. static ma_result ma_spatializer_get_heap_layout(const ma_spatializer_config* pConfig, ma_spatializer_heap_layout* pHeapLayout)
  40470. {
  40471. ma_result result;
  40472. MA_ASSERT(pHeapLayout != NULL);
  40473. MA_ZERO_OBJECT(pHeapLayout);
  40474. if (pConfig == NULL) {
  40475. return MA_INVALID_ARGS;
  40476. }
  40477. result = ma_spatializer_validate_config(pConfig);
  40478. if (result != MA_SUCCESS) {
  40479. return result;
  40480. }
  40481. pHeapLayout->sizeInBytes = 0;
  40482. /* Channel map. */
  40483. pHeapLayout->channelMapInOffset = MA_SIZE_MAX; /* <-- MA_SIZE_MAX indicates no allocation necessary. */
  40484. if (pConfig->pChannelMapIn != NULL) {
  40485. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  40486. pHeapLayout->sizeInBytes += ma_align_64(sizeof(*pConfig->pChannelMapIn) * pConfig->channelsIn);
  40487. }
  40488. /* New channel gains for output. */
  40489. pHeapLayout->newChannelGainsOffset = pHeapLayout->sizeInBytes;
  40490. pHeapLayout->sizeInBytes += ma_align_64(sizeof(float) * pConfig->channelsOut);
  40491. /* Gainer. */
  40492. {
  40493. size_t gainerHeapSizeInBytes;
  40494. ma_gainer_config gainerConfig;
  40495. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  40496. result = ma_gainer_get_heap_size(&gainerConfig, &gainerHeapSizeInBytes);
  40497. if (result != MA_SUCCESS) {
  40498. return result;
  40499. }
  40500. pHeapLayout->gainerOffset = pHeapLayout->sizeInBytes;
  40501. pHeapLayout->sizeInBytes += ma_align_64(gainerHeapSizeInBytes);
  40502. }
  40503. return MA_SUCCESS;
  40504. }
  40505. MA_API ma_result ma_spatializer_get_heap_size(const ma_spatializer_config* pConfig, size_t* pHeapSizeInBytes)
  40506. {
  40507. ma_result result;
  40508. ma_spatializer_heap_layout heapLayout;
  40509. if (pHeapSizeInBytes == NULL) {
  40510. return MA_INVALID_ARGS;
  40511. }
  40512. *pHeapSizeInBytes = 0; /* Safety. */
  40513. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  40514. if (result != MA_SUCCESS) {
  40515. return result;
  40516. }
  40517. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  40518. return MA_SUCCESS;
  40519. }
  40520. MA_API ma_result ma_spatializer_init_preallocated(const ma_spatializer_config* pConfig, void* pHeap, ma_spatializer* pSpatializer)
  40521. {
  40522. ma_result result;
  40523. ma_spatializer_heap_layout heapLayout;
  40524. ma_gainer_config gainerConfig;
  40525. if (pSpatializer == NULL) {
  40526. return MA_INVALID_ARGS;
  40527. }
  40528. MA_ZERO_OBJECT(pSpatializer);
  40529. if (pConfig == NULL || pHeap == NULL) {
  40530. return MA_INVALID_ARGS;
  40531. }
  40532. result = ma_spatializer_get_heap_layout(pConfig, &heapLayout);
  40533. if (result != MA_SUCCESS) {
  40534. return result;
  40535. }
  40536. pSpatializer->_pHeap = pHeap;
  40537. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  40538. pSpatializer->channelsIn = pConfig->channelsIn;
  40539. pSpatializer->channelsOut = pConfig->channelsOut;
  40540. pSpatializer->attenuationModel = pConfig->attenuationModel;
  40541. pSpatializer->positioning = pConfig->positioning;
  40542. pSpatializer->handedness = pConfig->handedness;
  40543. pSpatializer->minGain = pConfig->minGain;
  40544. pSpatializer->maxGain = pConfig->maxGain;
  40545. pSpatializer->minDistance = pConfig->minDistance;
  40546. pSpatializer->maxDistance = pConfig->maxDistance;
  40547. pSpatializer->rolloff = pConfig->rolloff;
  40548. pSpatializer->coneInnerAngleInRadians = pConfig->coneInnerAngleInRadians;
  40549. pSpatializer->coneOuterAngleInRadians = pConfig->coneOuterAngleInRadians;
  40550. pSpatializer->coneOuterGain = pConfig->coneOuterGain;
  40551. pSpatializer->dopplerFactor = pConfig->dopplerFactor;
  40552. pSpatializer->directionalAttenuationFactor = pConfig->directionalAttenuationFactor;
  40553. pSpatializer->gainSmoothTimeInFrames = pConfig->gainSmoothTimeInFrames;
  40554. pSpatializer->position = ma_vec3f_init_3f(0, 0, 0);
  40555. pSpatializer->direction = ma_vec3f_init_3f(0, 0, -1);
  40556. pSpatializer->velocity = ma_vec3f_init_3f(0, 0, 0);
  40557. pSpatializer->dopplerPitch = 1;
  40558. /* Swap the forward direction if we're left handed (it was initialized based on right handed). */
  40559. if (pSpatializer->handedness == ma_handedness_left) {
  40560. pSpatializer->direction = ma_vec3f_neg(pSpatializer->direction);
  40561. }
  40562. /* Channel map. This will be on the heap. */
  40563. if (pConfig->pChannelMapIn != NULL) {
  40564. pSpatializer->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  40565. ma_channel_map_copy_or_default(pSpatializer->pChannelMapIn, pSpatializer->channelsIn, pConfig->pChannelMapIn, pSpatializer->channelsIn);
  40566. }
  40567. /* New channel gains for output channels. */
  40568. pSpatializer->pNewChannelGainsOut = (float*)ma_offset_ptr(pHeap, heapLayout.newChannelGainsOffset);
  40569. /* Gainer. */
  40570. gainerConfig = ma_spatializer_gainer_config_init(pConfig);
  40571. result = ma_gainer_init_preallocated(&gainerConfig, ma_offset_ptr(pHeap, heapLayout.gainerOffset), &pSpatializer->gainer);
  40572. if (result != MA_SUCCESS) {
  40573. return result; /* Failed to initialize the gainer. */
  40574. }
  40575. return MA_SUCCESS;
  40576. }
  40577. MA_API ma_result ma_spatializer_init(const ma_spatializer_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_spatializer* pSpatializer)
  40578. {
  40579. ma_result result;
  40580. size_t heapSizeInBytes;
  40581. void* pHeap;
  40582. /* We'll need a heap allocation to retrieve the size. */
  40583. result = ma_spatializer_get_heap_size(pConfig, &heapSizeInBytes);
  40584. if (result != MA_SUCCESS) {
  40585. return result;
  40586. }
  40587. if (heapSizeInBytes > 0) {
  40588. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  40589. if (pHeap == NULL) {
  40590. return MA_OUT_OF_MEMORY;
  40591. }
  40592. } else {
  40593. pHeap = NULL;
  40594. }
  40595. result = ma_spatializer_init_preallocated(pConfig, pHeap, pSpatializer);
  40596. if (result != MA_SUCCESS) {
  40597. ma_free(pHeap, pAllocationCallbacks);
  40598. return result;
  40599. }
  40600. pSpatializer->_ownsHeap = MA_TRUE;
  40601. return MA_SUCCESS;
  40602. }
  40603. MA_API void ma_spatializer_uninit(ma_spatializer* pSpatializer, const ma_allocation_callbacks* pAllocationCallbacks)
  40604. {
  40605. if (pSpatializer == NULL) {
  40606. return;
  40607. }
  40608. ma_gainer_uninit(&pSpatializer->gainer, pAllocationCallbacks);
  40609. if (pSpatializer->_ownsHeap) {
  40610. ma_free(pSpatializer->_pHeap, pAllocationCallbacks);
  40611. }
  40612. }
  40613. static float ma_calculate_angular_gain(ma_vec3f dirA, ma_vec3f dirB, float coneInnerAngleInRadians, float coneOuterAngleInRadians, float coneOuterGain)
  40614. {
  40615. /*
  40616. Angular attenuation.
  40617. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  40618. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  40619. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  40620. just need to get the direction from the source to the listener and then do a dot product against that and the
  40621. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  40622. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  40623. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  40624. */
  40625. if (coneInnerAngleInRadians < 6.283185f) {
  40626. float angularGain = 1;
  40627. float cutoffInner = (float)ma_cosd(coneInnerAngleInRadians*0.5f);
  40628. float cutoffOuter = (float)ma_cosd(coneOuterAngleInRadians*0.5f);
  40629. float d;
  40630. d = ma_vec3f_dot(dirA, dirB);
  40631. if (d > cutoffInner) {
  40632. /* It's inside the inner angle. */
  40633. angularGain = 1;
  40634. } else {
  40635. /* It's outside the inner angle. */
  40636. if (d > cutoffOuter) {
  40637. /* It's between the inner and outer angle. We need to linearly interpolate between 1 and coneOuterGain. */
  40638. angularGain = ma_mix_f32(coneOuterGain, 1, (d - cutoffOuter) / (cutoffInner - cutoffOuter));
  40639. } else {
  40640. /* It's outside the outer angle. */
  40641. angularGain = coneOuterGain;
  40642. }
  40643. }
  40644. /*printf("d = %f; cutoffInner = %f; cutoffOuter = %f; angularGain = %f\n", d, cutoffInner, cutoffOuter, angularGain);*/
  40645. return angularGain;
  40646. } else {
  40647. /* Inner angle is 360 degrees so no need to do any attenuation. */
  40648. return 1;
  40649. }
  40650. }
  40651. MA_API ma_result ma_spatializer_process_pcm_frames(ma_spatializer* pSpatializer, ma_spatializer_listener* pListener, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  40652. {
  40653. ma_channel* pChannelMapIn = pSpatializer->pChannelMapIn;
  40654. ma_channel* pChannelMapOut = pListener->config.pChannelMapOut;
  40655. if (pSpatializer == NULL) {
  40656. return MA_INVALID_ARGS;
  40657. }
  40658. /* If we're not spatializing we need to run an optimized path. */
  40659. if (c89atomic_load_i32(&pSpatializer->attenuationModel) == ma_attenuation_model_none) {
  40660. if (ma_spatializer_listener_is_enabled(pListener)) {
  40661. /* No attenuation is required, but we'll need to do some channel conversion. */
  40662. if (pSpatializer->channelsIn == pSpatializer->channelsOut) {
  40663. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, pSpatializer->channelsIn);
  40664. } else {
  40665. 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. */
  40666. }
  40667. } else {
  40668. /* The listener is disabled. Output silence. */
  40669. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  40670. }
  40671. /*
  40672. We're not doing attenuation so don't bother with doppler for now. I'm not sure if this is
  40673. the correct thinking so might need to review this later.
  40674. */
  40675. pSpatializer->dopplerPitch = 1;
  40676. } else {
  40677. /*
  40678. Let's first determine which listener the sound is closest to. Need to keep in mind that we
  40679. might not have a world or any listeners, in which case we just spatializer based on the
  40680. listener being positioned at the origin (0, 0, 0).
  40681. */
  40682. ma_vec3f relativePosNormalized;
  40683. ma_vec3f relativePos; /* The position relative to the listener. */
  40684. ma_vec3f relativeDir; /* The direction of the sound, relative to the listener. */
  40685. ma_vec3f listenerVel; /* The volocity of the listener. For doppler pitch calculation. */
  40686. float speedOfSound;
  40687. float distance = 0;
  40688. float gain = 1;
  40689. ma_uint32 iChannel;
  40690. const ma_uint32 channelsOut = pSpatializer->channelsOut;
  40691. const ma_uint32 channelsIn = pSpatializer->channelsIn;
  40692. float minDistance = ma_spatializer_get_min_distance(pSpatializer);
  40693. float maxDistance = ma_spatializer_get_max_distance(pSpatializer);
  40694. float rolloff = ma_spatializer_get_rolloff(pSpatializer);
  40695. float dopplerFactor = ma_spatializer_get_doppler_factor(pSpatializer);
  40696. /*
  40697. We'll need the listener velocity for doppler pitch calculations. The speed of sound is
  40698. defined by the listener, so we'll grab that here too.
  40699. */
  40700. if (pListener != NULL) {
  40701. listenerVel = pListener->velocity;
  40702. speedOfSound = pListener->config.speedOfSound;
  40703. } else {
  40704. listenerVel = ma_vec3f_init_3f(0, 0, 0);
  40705. speedOfSound = MA_DEFAULT_SPEED_OF_SOUND;
  40706. }
  40707. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  40708. /* There's no listener or we're using relative positioning. */
  40709. relativePos = pSpatializer->position;
  40710. relativeDir = pSpatializer->direction;
  40711. } else {
  40712. /*
  40713. We've found a listener and we're using absolute positioning. We need to transform the
  40714. sound's position and direction so that it's relative to listener. Later on we'll use
  40715. this for determining the factors to apply to each channel to apply the panning effect.
  40716. */
  40717. ma_spatializer_get_relative_position_and_direction(pSpatializer, pListener, &relativePos, &relativeDir);
  40718. }
  40719. distance = ma_vec3f_len(relativePos);
  40720. /* We've gathered the data, so now we can apply some spatialization. */
  40721. switch (ma_spatializer_get_attenuation_model(pSpatializer)) {
  40722. case ma_attenuation_model_inverse:
  40723. {
  40724. gain = ma_attenuation_inverse(distance, minDistance, maxDistance, rolloff);
  40725. } break;
  40726. case ma_attenuation_model_linear:
  40727. {
  40728. gain = ma_attenuation_linear(distance, minDistance, maxDistance, rolloff);
  40729. } break;
  40730. case ma_attenuation_model_exponential:
  40731. {
  40732. gain = ma_attenuation_exponential(distance, minDistance, maxDistance, rolloff);
  40733. } break;
  40734. case ma_attenuation_model_none:
  40735. default:
  40736. {
  40737. gain = 1;
  40738. } break;
  40739. }
  40740. /* Normalize the position. */
  40741. if (distance > 0.001f) {
  40742. float distanceInv = 1/distance;
  40743. relativePosNormalized = relativePos;
  40744. relativePosNormalized.x *= distanceInv;
  40745. relativePosNormalized.y *= distanceInv;
  40746. relativePosNormalized.z *= distanceInv;
  40747. } else {
  40748. distance = 0;
  40749. relativePosNormalized = ma_vec3f_init_3f(0, 0, 0);
  40750. }
  40751. /*
  40752. Angular attenuation.
  40753. Unlike distance gain, the math for this is not specified by the OpenAL spec so we'll just go ahead and figure
  40754. this out for ourselves at the expense of possibly being inconsistent with other implementations.
  40755. To do cone attenuation, I'm just using the same math that we'd use to implement a basic spotlight in OpenGL. We
  40756. just need to get the direction from the source to the listener and then do a dot product against that and the
  40757. direction of the spotlight. Then we just compare that dot product against the cosine of the inner and outer
  40758. angles. If the dot product is greater than the the outer angle, we just use coneOuterGain. If it's less than
  40759. the inner angle, we just use a gain of 1. Otherwise we linearly interpolate between 1 and coneOuterGain.
  40760. */
  40761. if (distance > 0) {
  40762. /* Source anglular gain. */
  40763. float spatializerConeInnerAngle;
  40764. float spatializerConeOuterAngle;
  40765. float spatializerConeOuterGain;
  40766. ma_spatializer_get_cone(pSpatializer, &spatializerConeInnerAngle, &spatializerConeOuterAngle, &spatializerConeOuterGain);
  40767. gain *= ma_calculate_angular_gain(relativeDir, ma_vec3f_neg(relativePosNormalized), spatializerConeInnerAngle, spatializerConeOuterAngle, spatializerConeOuterGain);
  40768. /*
  40769. We're supporting angular gain on the listener as well for those who want to reduce the volume of sounds that
  40770. are positioned behind the listener. On default settings, this will have no effect.
  40771. */
  40772. if (pListener != NULL && pListener->config.coneInnerAngleInRadians < 6.283185f) {
  40773. ma_vec3f listenerDirection;
  40774. float listenerInnerAngle;
  40775. float listenerOuterAngle;
  40776. float listenerOuterGain;
  40777. if (pListener->config.handedness == ma_handedness_right) {
  40778. listenerDirection = ma_vec3f_init_3f(0, 0, -1);
  40779. } else {
  40780. listenerDirection = ma_vec3f_init_3f(0, 0, +1);
  40781. }
  40782. listenerInnerAngle = pListener->config.coneInnerAngleInRadians;
  40783. listenerOuterAngle = pListener->config.coneOuterAngleInRadians;
  40784. listenerOuterGain = pListener->config.coneOuterGain;
  40785. gain *= ma_calculate_angular_gain(listenerDirection, relativePosNormalized, listenerInnerAngle, listenerOuterAngle, listenerOuterGain);
  40786. }
  40787. } else {
  40788. /* The sound is right on top of the listener. Don't do any angular attenuation. */
  40789. }
  40790. /* Clamp the gain. */
  40791. gain = ma_clamp(gain, ma_spatializer_get_min_gain(pSpatializer), ma_spatializer_get_max_gain(pSpatializer));
  40792. /*
  40793. Panning. This is where we'll apply the gain and convert to the output channel count. We have an optimized path for
  40794. when we're converting to a mono stream. In that case we don't really need to do any panning - we just apply the
  40795. gain to the final output.
  40796. */
  40797. /*printf("distance=%f; gain=%f\n", distance, gain);*/
  40798. /* We must have a valid channel map here to ensure we spatialize properly. */
  40799. MA_ASSERT(pChannelMapOut != NULL);
  40800. /*
  40801. We're not converting to mono so we'll want to apply some panning. This is where the feeling of something being
  40802. to the left, right, infront or behind the listener is calculated. I'm just using a basic model here. Note that
  40803. the code below is not based on any specific algorithm. I'm just implementing this off the top of my head and
  40804. seeing how it goes. There might be better ways to do this.
  40805. To determine the direction of the sound relative to a speaker I'm using dot products. Each speaker is given a
  40806. direction. For example, the left channel in a stereo system will be -1 on the X axis and the right channel will
  40807. be +1 on the X axis. A dot product is performed against the direction vector of the channel and the normalized
  40808. position of the sound.
  40809. */
  40810. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  40811. pSpatializer->pNewChannelGainsOut[iChannel] = gain;
  40812. }
  40813. /*
  40814. Convert to our output channel count. If the listener is disabled we just output silence here. We cannot ignore
  40815. the whole section of code here because we need to update some internal spatialization state.
  40816. */
  40817. if (ma_spatializer_listener_is_enabled(pListener)) {
  40818. 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);
  40819. } else {
  40820. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, pSpatializer->channelsOut);
  40821. }
  40822. /*
  40823. Calculate our per-channel gains. We do this based on the normalized relative position of the sound and it's
  40824. relation to the direction of the channel.
  40825. */
  40826. if (distance > 0) {
  40827. ma_vec3f unitPos = relativePos;
  40828. float distanceInv = 1/distance;
  40829. unitPos.x *= distanceInv;
  40830. unitPos.y *= distanceInv;
  40831. unitPos.z *= distanceInv;
  40832. for (iChannel = 0; iChannel < channelsOut; iChannel += 1) {
  40833. ma_channel channelOut;
  40834. float d;
  40835. float dMin;
  40836. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannel);
  40837. if (ma_is_spatial_channel_position(channelOut)) {
  40838. d = ma_mix_f32_fast(1, ma_vec3f_dot(unitPos, ma_get_channel_direction(channelOut)), ma_spatializer_get_directional_attenuation_factor(pSpatializer));
  40839. } else {
  40840. d = 1; /* It's not a spatial channel so there's no real notion of direction. */
  40841. }
  40842. /*
  40843. In my testing, if the panning effect is too aggressive it makes spatialization feel uncomfortable.
  40844. The "dMin" variable below is used to control the aggressiveness of the panning effect. When set to
  40845. 0, panning will be most extreme and any sounds that are positioned on the opposite side of the
  40846. speaker will be completely silent from that speaker. Not only does this feel uncomfortable, it
  40847. doesn't even remotely represent the real world at all because sounds that come from your right side
  40848. are still clearly audible from your left side. Setting "dMin" to 1 will result in no panning at
  40849. all, which is also not ideal. By setting it to something greater than 0, the spatialization effect
  40850. becomes much less dramatic and a lot more bearable.
  40851. Summary: 0 = more extreme panning; 1 = no panning.
  40852. */
  40853. dMin = 0.2f; /* TODO: Consider making this configurable. */
  40854. /*
  40855. At this point, "d" will be positive if the sound is on the same side as the channel and negative if
  40856. it's on the opposite side. It will be in the range of -1..1. There's two ways I can think of to
  40857. calculate a panning value. The first is to simply convert it to 0..1, however this has a problem
  40858. which I'm not entirely happy with. Considering a stereo system, when a sound is positioned right
  40859. in front of the listener it'll result in each speaker getting a gain of 0.5. I don't know if I like
  40860. the idea of having a scaling factor of 0.5 being applied to a sound when it's sitting right in front
  40861. of the listener. I would intuitively expect that to be played at full volume, or close to it.
  40862. The second idea I think of is to only apply a reduction in gain when the sound is on the opposite
  40863. side of the speaker. That is, reduce the gain only when the dot product is negative. The problem
  40864. with this is that there will not be any attenuation as the sound sweeps around the 180 degrees
  40865. where the dot product is positive. The idea with this option is that you leave the gain at 1 when
  40866. the sound is being played on the same side as the speaker and then you just reduce the volume when
  40867. the sound is on the other side.
  40868. The summarize, I think the first option should give a better sense of spatialization, but the second
  40869. option is better for preserving the sound's power.
  40870. UPDATE: In my testing, I find the first option to sound better. You can feel the sense of space a
  40871. bit better, but you can also hear the reduction in volume when it's right in front.
  40872. */
  40873. #if 1
  40874. {
  40875. /*
  40876. Scale the dot product from -1..1 to 0..1. Will result in a sound directly in front losing power
  40877. by being played at 0.5 gain.
  40878. */
  40879. d = (d + 1) * 0.5f; /* -1..1 to 0..1 */
  40880. d = ma_max(d, dMin);
  40881. pSpatializer->pNewChannelGainsOut[iChannel] *= d;
  40882. }
  40883. #else
  40884. {
  40885. /*
  40886. Only reduce the volume of the sound if it's on the opposite side. This path keeps the volume more
  40887. consistent, but comes at the expense of a worse sense of space and positioning.
  40888. */
  40889. if (d < 0) {
  40890. d += 1; /* Move into the positive range. */
  40891. d = ma_max(d, dMin);
  40892. channelGainsOut[iChannel] *= d;
  40893. }
  40894. }
  40895. #endif
  40896. }
  40897. } else {
  40898. /* Assume the sound is right on top of us. Don't do any panning. */
  40899. }
  40900. /* 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. */
  40901. ma_gainer_set_gains(&pSpatializer->gainer, pSpatializer->pNewChannelGainsOut);
  40902. ma_gainer_process_pcm_frames(&pSpatializer->gainer, pFramesOut, pFramesOut, frameCount);
  40903. /*
  40904. Before leaving we'll want to update our doppler pitch so that the caller can apply some
  40905. pitch shifting if they desire. Note that we need to negate the relative position here
  40906. because the doppler calculation needs to be source-to-listener, but ours is listener-to-
  40907. source.
  40908. */
  40909. if (dopplerFactor > 0) {
  40910. pSpatializer->dopplerPitch = ma_doppler_pitch(ma_vec3f_sub(pListener->position, pSpatializer->position), pSpatializer->velocity, listenerVel, speedOfSound, dopplerFactor);
  40911. } else {
  40912. pSpatializer->dopplerPitch = 1;
  40913. }
  40914. }
  40915. return MA_SUCCESS;
  40916. }
  40917. MA_API ma_uint32 ma_spatializer_get_input_channels(const ma_spatializer* pSpatializer)
  40918. {
  40919. if (pSpatializer == NULL) {
  40920. return 0;
  40921. }
  40922. return pSpatializer->channelsIn;
  40923. }
  40924. MA_API ma_uint32 ma_spatializer_get_output_channels(const ma_spatializer* pSpatializer)
  40925. {
  40926. if (pSpatializer == NULL) {
  40927. return 0;
  40928. }
  40929. return pSpatializer->channelsOut;
  40930. }
  40931. MA_API void ma_spatializer_set_attenuation_model(ma_spatializer* pSpatializer, ma_attenuation_model attenuationModel)
  40932. {
  40933. if (pSpatializer == NULL) {
  40934. return;
  40935. }
  40936. c89atomic_exchange_i32(&pSpatializer->attenuationModel, attenuationModel);
  40937. }
  40938. MA_API ma_attenuation_model ma_spatializer_get_attenuation_model(const ma_spatializer* pSpatializer)
  40939. {
  40940. if (pSpatializer == NULL) {
  40941. return ma_attenuation_model_none;
  40942. }
  40943. return (ma_attenuation_model)c89atomic_load_i32(&pSpatializer->attenuationModel);
  40944. }
  40945. MA_API void ma_spatializer_set_positioning(ma_spatializer* pSpatializer, ma_positioning positioning)
  40946. {
  40947. if (pSpatializer == NULL) {
  40948. return;
  40949. }
  40950. c89atomic_exchange_i32(&pSpatializer->positioning, positioning);
  40951. }
  40952. MA_API ma_positioning ma_spatializer_get_positioning(const ma_spatializer* pSpatializer)
  40953. {
  40954. if (pSpatializer == NULL) {
  40955. return ma_positioning_absolute;
  40956. }
  40957. return (ma_positioning)c89atomic_load_i32(&pSpatializer->positioning);
  40958. }
  40959. MA_API void ma_spatializer_set_rolloff(ma_spatializer* pSpatializer, float rolloff)
  40960. {
  40961. if (pSpatializer == NULL) {
  40962. return;
  40963. }
  40964. c89atomic_exchange_f32(&pSpatializer->rolloff, rolloff);
  40965. }
  40966. MA_API float ma_spatializer_get_rolloff(const ma_spatializer* pSpatializer)
  40967. {
  40968. if (pSpatializer == NULL) {
  40969. return 0;
  40970. }
  40971. return c89atomic_load_f32(&pSpatializer->rolloff);
  40972. }
  40973. MA_API void ma_spatializer_set_min_gain(ma_spatializer* pSpatializer, float minGain)
  40974. {
  40975. if (pSpatializer == NULL) {
  40976. return;
  40977. }
  40978. c89atomic_exchange_f32(&pSpatializer->minGain, minGain);
  40979. }
  40980. MA_API float ma_spatializer_get_min_gain(const ma_spatializer* pSpatializer)
  40981. {
  40982. if (pSpatializer == NULL) {
  40983. return 0;
  40984. }
  40985. return c89atomic_load_f32(&pSpatializer->minGain);
  40986. }
  40987. MA_API void ma_spatializer_set_max_gain(ma_spatializer* pSpatializer, float maxGain)
  40988. {
  40989. if (pSpatializer == NULL) {
  40990. return;
  40991. }
  40992. c89atomic_exchange_f32(&pSpatializer->maxGain, maxGain);
  40993. }
  40994. MA_API float ma_spatializer_get_max_gain(const ma_spatializer* pSpatializer)
  40995. {
  40996. if (pSpatializer == NULL) {
  40997. return 0;
  40998. }
  40999. return c89atomic_load_f32(&pSpatializer->maxGain);
  41000. }
  41001. MA_API void ma_spatializer_set_min_distance(ma_spatializer* pSpatializer, float minDistance)
  41002. {
  41003. if (pSpatializer == NULL) {
  41004. return;
  41005. }
  41006. c89atomic_exchange_f32(&pSpatializer->minDistance, minDistance);
  41007. }
  41008. MA_API float ma_spatializer_get_min_distance(const ma_spatializer* pSpatializer)
  41009. {
  41010. if (pSpatializer == NULL) {
  41011. return 0;
  41012. }
  41013. return c89atomic_load_f32(&pSpatializer->minDistance);
  41014. }
  41015. MA_API void ma_spatializer_set_max_distance(ma_spatializer* pSpatializer, float maxDistance)
  41016. {
  41017. if (pSpatializer == NULL) {
  41018. return;
  41019. }
  41020. c89atomic_exchange_f32(&pSpatializer->maxDistance, maxDistance);
  41021. }
  41022. MA_API float ma_spatializer_get_max_distance(const ma_spatializer* pSpatializer)
  41023. {
  41024. if (pSpatializer == NULL) {
  41025. return 0;
  41026. }
  41027. return c89atomic_load_f32(&pSpatializer->maxDistance);
  41028. }
  41029. MA_API void ma_spatializer_set_cone(ma_spatializer* pSpatializer, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  41030. {
  41031. if (pSpatializer == NULL) {
  41032. return;
  41033. }
  41034. c89atomic_exchange_f32(&pSpatializer->coneInnerAngleInRadians, innerAngleInRadians);
  41035. c89atomic_exchange_f32(&pSpatializer->coneOuterAngleInRadians, outerAngleInRadians);
  41036. c89atomic_exchange_f32(&pSpatializer->coneOuterGain, outerGain);
  41037. }
  41038. MA_API void ma_spatializer_get_cone(const ma_spatializer* pSpatializer, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  41039. {
  41040. if (pSpatializer == NULL) {
  41041. return;
  41042. }
  41043. if (pInnerAngleInRadians != NULL) {
  41044. *pInnerAngleInRadians = c89atomic_load_f32(&pSpatializer->coneInnerAngleInRadians);
  41045. }
  41046. if (pOuterAngleInRadians != NULL) {
  41047. *pOuterAngleInRadians = c89atomic_load_f32(&pSpatializer->coneOuterAngleInRadians);
  41048. }
  41049. if (pOuterGain != NULL) {
  41050. *pOuterGain = c89atomic_load_f32(&pSpatializer->coneOuterGain);
  41051. }
  41052. }
  41053. MA_API void ma_spatializer_set_doppler_factor(ma_spatializer* pSpatializer, float dopplerFactor)
  41054. {
  41055. if (pSpatializer == NULL) {
  41056. return;
  41057. }
  41058. c89atomic_exchange_f32(&pSpatializer->dopplerFactor, dopplerFactor);
  41059. }
  41060. MA_API float ma_spatializer_get_doppler_factor(const ma_spatializer* pSpatializer)
  41061. {
  41062. if (pSpatializer == NULL) {
  41063. return 1;
  41064. }
  41065. return c89atomic_load_f32(&pSpatializer->dopplerFactor);
  41066. }
  41067. MA_API void ma_spatializer_set_directional_attenuation_factor(ma_spatializer* pSpatializer, float directionalAttenuationFactor)
  41068. {
  41069. if (pSpatializer == NULL) {
  41070. return;
  41071. }
  41072. c89atomic_exchange_f32(&pSpatializer->directionalAttenuationFactor, directionalAttenuationFactor);
  41073. }
  41074. MA_API float ma_spatializer_get_directional_attenuation_factor(const ma_spatializer* pSpatializer)
  41075. {
  41076. if (pSpatializer == NULL) {
  41077. return 1;
  41078. }
  41079. return c89atomic_load_f32(&pSpatializer->directionalAttenuationFactor);
  41080. }
  41081. MA_API void ma_spatializer_set_position(ma_spatializer* pSpatializer, float x, float y, float z)
  41082. {
  41083. if (pSpatializer == NULL) {
  41084. return;
  41085. }
  41086. pSpatializer->position = ma_vec3f_init_3f(x, y, z);
  41087. }
  41088. MA_API ma_vec3f ma_spatializer_get_position(const ma_spatializer* pSpatializer)
  41089. {
  41090. if (pSpatializer == NULL) {
  41091. return ma_vec3f_init_3f(0, 0, 0);
  41092. }
  41093. return pSpatializer->position;
  41094. }
  41095. MA_API void ma_spatializer_set_direction(ma_spatializer* pSpatializer, float x, float y, float z)
  41096. {
  41097. if (pSpatializer == NULL) {
  41098. return;
  41099. }
  41100. pSpatializer->direction = ma_vec3f_init_3f(x, y, z);
  41101. }
  41102. MA_API ma_vec3f ma_spatializer_get_direction(const ma_spatializer* pSpatializer)
  41103. {
  41104. if (pSpatializer == NULL) {
  41105. return ma_vec3f_init_3f(0, 0, -1);
  41106. }
  41107. return pSpatializer->direction;
  41108. }
  41109. MA_API void ma_spatializer_set_velocity(ma_spatializer* pSpatializer, float x, float y, float z)
  41110. {
  41111. if (pSpatializer == NULL) {
  41112. return;
  41113. }
  41114. pSpatializer->velocity = ma_vec3f_init_3f(x, y, z);
  41115. }
  41116. MA_API ma_vec3f ma_spatializer_get_velocity(const ma_spatializer* pSpatializer)
  41117. {
  41118. if (pSpatializer == NULL) {
  41119. return ma_vec3f_init_3f(0, 0, 0);
  41120. }
  41121. return pSpatializer->velocity;
  41122. }
  41123. 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)
  41124. {
  41125. if (pRelativePos != NULL) {
  41126. pRelativePos->x = 0;
  41127. pRelativePos->y = 0;
  41128. pRelativePos->z = 0;
  41129. }
  41130. if (pRelativeDir != NULL) {
  41131. pRelativeDir->x = 0;
  41132. pRelativeDir->y = 0;
  41133. pRelativeDir->z = -1;
  41134. }
  41135. if (pSpatializer == NULL) {
  41136. return;
  41137. }
  41138. if (pListener == NULL || ma_spatializer_get_positioning(pSpatializer) == ma_positioning_relative) {
  41139. /* There's no listener or we're using relative positioning. */
  41140. if (pRelativePos != NULL) {
  41141. *pRelativePos = pSpatializer->position;
  41142. }
  41143. if (pRelativeDir != NULL) {
  41144. *pRelativeDir = pSpatializer->direction;
  41145. }
  41146. } else {
  41147. ma_vec3f v;
  41148. ma_vec3f axisX;
  41149. ma_vec3f axisY;
  41150. ma_vec3f axisZ;
  41151. float m[4][4];
  41152. /*
  41153. We need to calcualte the right vector from our forward and up vectors. This is done with
  41154. a cross product.
  41155. */
  41156. axisZ = ma_vec3f_normalize(pListener->direction); /* Normalization required here because we can't trust the caller. */
  41157. 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. */
  41158. /*
  41159. The calculation of axisX above can result in a zero-length vector if the listener is
  41160. looking straight up on the Y axis. We'll need to fall back to a +X in this case so that
  41161. the calculations below don't fall apart. This is where a quaternion based listener and
  41162. sound orientation would come in handy.
  41163. */
  41164. if (ma_vec3f_len2(axisX) == 0) {
  41165. axisX = ma_vec3f_init_3f(1, 0, 0);
  41166. }
  41167. axisY = ma_vec3f_cross(axisX, axisZ); /* No normalization is required here because axisX and axisZ are unit length and perpendicular. */
  41168. /*
  41169. We need to swap the X axis if we're left handed because otherwise the cross product above
  41170. will have resulted in it pointing in the wrong direction (right handed was assumed in the
  41171. cross products above).
  41172. */
  41173. if (pListener->config.handedness == ma_handedness_left) {
  41174. axisX = ma_vec3f_neg(axisX);
  41175. }
  41176. /* Lookat. */
  41177. m[0][0] = axisX.x; m[1][0] = axisX.y; m[2][0] = axisX.z; m[3][0] = -ma_vec3f_dot(axisX, pListener->position);
  41178. m[0][1] = axisY.x; m[1][1] = axisY.y; m[2][1] = axisY.z; m[3][1] = -ma_vec3f_dot(axisY, pListener->position);
  41179. 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), pListener->position);
  41180. m[0][3] = 0; m[1][3] = 0; m[2][3] = 0; m[3][3] = 1;
  41181. /*
  41182. Multiply the lookat matrix by the spatializer position to transform it to listener
  41183. space. This allows calculations to work based on the sound being relative to the
  41184. origin which makes things simpler.
  41185. */
  41186. if (pRelativePos != NULL) {
  41187. v = pSpatializer->position;
  41188. pRelativePos->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z + m[3][0] * 1;
  41189. pRelativePos->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z + m[3][1] * 1;
  41190. pRelativePos->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z + m[3][2] * 1;
  41191. }
  41192. /*
  41193. The direction of the sound needs to also be transformed so that it's relative to the
  41194. rotation of the listener.
  41195. */
  41196. if (pRelativeDir != NULL) {
  41197. v = pSpatializer->direction;
  41198. pRelativeDir->x = m[0][0] * v.x + m[1][0] * v.y + m[2][0] * v.z;
  41199. pRelativeDir->y = m[0][1] * v.x + m[1][1] * v.y + m[2][1] * v.z;
  41200. pRelativeDir->z = m[0][2] * v.x + m[1][2] * v.y + m[2][2] * v.z;
  41201. }
  41202. }
  41203. }
  41204. /**************************************************************************************************************************************************************
  41205. Resampling
  41206. **************************************************************************************************************************************************************/
  41207. MA_API ma_linear_resampler_config ma_linear_resampler_config_init(ma_format format, ma_uint32 channels, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  41208. {
  41209. ma_linear_resampler_config config;
  41210. MA_ZERO_OBJECT(&config);
  41211. config.format = format;
  41212. config.channels = channels;
  41213. config.sampleRateIn = sampleRateIn;
  41214. config.sampleRateOut = sampleRateOut;
  41215. config.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  41216. config.lpfNyquistFactor = 1;
  41217. return config;
  41218. }
  41219. typedef struct
  41220. {
  41221. size_t sizeInBytes;
  41222. size_t x0Offset;
  41223. size_t x1Offset;
  41224. size_t lpfOffset;
  41225. } ma_linear_resampler_heap_layout;
  41226. static void ma_linear_resampler_adjust_timer_for_new_rate(ma_linear_resampler* pResampler, ma_uint32 oldSampleRateOut, ma_uint32 newSampleRateOut)
  41227. {
  41228. /*
  41229. 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
  41230. be based on the old sample rate, but we are needing to adjust it to that it's based on the new sample rate.
  41231. */
  41232. 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. */
  41233. ma_uint32 oldRateTimeFract = pResampler->inTimeFrac % oldSampleRateOut;
  41234. pResampler->inTimeFrac =
  41235. (oldRateTimeWhole * newSampleRateOut) +
  41236. ((oldRateTimeFract * newSampleRateOut) / oldSampleRateOut);
  41237. /* Make sure the fractional part is less than the output sample rate. */
  41238. pResampler->inTimeInt += pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  41239. pResampler->inTimeFrac = pResampler->inTimeFrac % pResampler->config.sampleRateOut;
  41240. }
  41241. 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)
  41242. {
  41243. ma_result result;
  41244. ma_uint32 gcf;
  41245. ma_uint32 lpfSampleRate;
  41246. double lpfCutoffFrequency;
  41247. ma_lpf_config lpfConfig;
  41248. ma_uint32 oldSampleRateOut; /* Required for adjusting time advance down the bottom. */
  41249. if (pResampler == NULL) {
  41250. return MA_INVALID_ARGS;
  41251. }
  41252. if (sampleRateIn == 0 || sampleRateOut == 0) {
  41253. return MA_INVALID_ARGS;
  41254. }
  41255. oldSampleRateOut = pResampler->config.sampleRateOut;
  41256. pResampler->config.sampleRateIn = sampleRateIn;
  41257. pResampler->config.sampleRateOut = sampleRateOut;
  41258. /* Simplify the sample rate. */
  41259. gcf = ma_gcf_u32(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut);
  41260. pResampler->config.sampleRateIn /= gcf;
  41261. pResampler->config.sampleRateOut /= gcf;
  41262. /* Always initialize the low-pass filter, even when the order is 0. */
  41263. if (pResampler->config.lpfOrder > MA_MAX_FILTER_ORDER) {
  41264. return MA_INVALID_ARGS;
  41265. }
  41266. lpfSampleRate = (ma_uint32)(ma_max(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut));
  41267. lpfCutoffFrequency = ( double)(ma_min(pResampler->config.sampleRateIn, pResampler->config.sampleRateOut) * 0.5 * pResampler->config.lpfNyquistFactor);
  41268. lpfConfig = ma_lpf_config_init(pResampler->config.format, pResampler->config.channels, lpfSampleRate, lpfCutoffFrequency, pResampler->config.lpfOrder);
  41269. /*
  41270. 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
  41271. getting cleared. Instead we re-initialize the filter which will maintain any cached frames.
  41272. */
  41273. if (isResamplerAlreadyInitialized) {
  41274. result = ma_lpf_reinit(&lpfConfig, &pResampler->lpf);
  41275. } else {
  41276. result = ma_lpf_init_preallocated(&lpfConfig, ma_offset_ptr(pHeap, pHeapLayout->lpfOffset), &pResampler->lpf);
  41277. }
  41278. if (result != MA_SUCCESS) {
  41279. return result;
  41280. }
  41281. pResampler->inAdvanceInt = pResampler->config.sampleRateIn / pResampler->config.sampleRateOut;
  41282. pResampler->inAdvanceFrac = pResampler->config.sampleRateIn % pResampler->config.sampleRateOut;
  41283. /* Our timer was based on the old rate. We need to adjust it so that it's based on the new rate. */
  41284. ma_linear_resampler_adjust_timer_for_new_rate(pResampler, oldSampleRateOut, pResampler->config.sampleRateOut);
  41285. return MA_SUCCESS;
  41286. }
  41287. static ma_result ma_linear_resampler_get_heap_layout(const ma_linear_resampler_config* pConfig, ma_linear_resampler_heap_layout* pHeapLayout)
  41288. {
  41289. MA_ASSERT(pHeapLayout != NULL);
  41290. MA_ZERO_OBJECT(pHeapLayout);
  41291. if (pConfig == NULL) {
  41292. return MA_INVALID_ARGS;
  41293. }
  41294. if (pConfig->format != ma_format_f32 && pConfig->format != ma_format_s16) {
  41295. return MA_INVALID_ARGS;
  41296. }
  41297. if (pConfig->channels == 0) {
  41298. return MA_INVALID_ARGS;
  41299. }
  41300. pHeapLayout->sizeInBytes = 0;
  41301. /* x0 */
  41302. pHeapLayout->x0Offset = pHeapLayout->sizeInBytes;
  41303. if (pConfig->format == ma_format_f32) {
  41304. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  41305. } else {
  41306. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  41307. }
  41308. /* x1 */
  41309. pHeapLayout->x1Offset = pHeapLayout->sizeInBytes;
  41310. if (pConfig->format == ma_format_f32) {
  41311. pHeapLayout->sizeInBytes += sizeof(float) * pConfig->channels;
  41312. } else {
  41313. pHeapLayout->sizeInBytes += sizeof(ma_int16) * pConfig->channels;
  41314. }
  41315. /* LPF */
  41316. pHeapLayout->lpfOffset = ma_align_64(pHeapLayout->sizeInBytes);
  41317. {
  41318. ma_result result;
  41319. size_t lpfHeapSizeInBytes;
  41320. ma_lpf_config lpfConfig = ma_lpf_config_init(pConfig->format, pConfig->channels, 1, 1, pConfig->lpfOrder); /* Sample rate and cutoff frequency do not matter. */
  41321. result = ma_lpf_get_heap_size(&lpfConfig, &lpfHeapSizeInBytes);
  41322. if (result != MA_SUCCESS) {
  41323. return result;
  41324. }
  41325. pHeapLayout->sizeInBytes += lpfHeapSizeInBytes;
  41326. }
  41327. /* Make sure allocation size is aligned. */
  41328. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  41329. return MA_SUCCESS;
  41330. }
  41331. MA_API ma_result ma_linear_resampler_get_heap_size(const ma_linear_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  41332. {
  41333. ma_result result;
  41334. ma_linear_resampler_heap_layout heapLayout;
  41335. if (pHeapSizeInBytes == NULL) {
  41336. return MA_INVALID_ARGS;
  41337. }
  41338. *pHeapSizeInBytes = 0;
  41339. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  41340. if (result != MA_SUCCESS) {
  41341. return result;
  41342. }
  41343. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  41344. return MA_SUCCESS;
  41345. }
  41346. MA_API ma_result ma_linear_resampler_init_preallocated(const ma_linear_resampler_config* pConfig, void* pHeap, ma_linear_resampler* pResampler)
  41347. {
  41348. ma_result result;
  41349. ma_linear_resampler_heap_layout heapLayout;
  41350. if (pResampler == NULL) {
  41351. return MA_INVALID_ARGS;
  41352. }
  41353. MA_ZERO_OBJECT(pResampler);
  41354. result = ma_linear_resampler_get_heap_layout(pConfig, &heapLayout);
  41355. if (result != MA_SUCCESS) {
  41356. return result;
  41357. }
  41358. pResampler->config = *pConfig;
  41359. pResampler->_pHeap = pHeap;
  41360. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  41361. if (pConfig->format == ma_format_f32) {
  41362. pResampler->x0.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  41363. pResampler->x1.f32 = (float*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  41364. } else {
  41365. pResampler->x0.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x0Offset);
  41366. pResampler->x1.s16 = (ma_int16*)ma_offset_ptr(pHeap, heapLayout.x1Offset);
  41367. }
  41368. /* Setting the rate will set up the filter and time advances for us. */
  41369. result = ma_linear_resampler_set_rate_internal(pResampler, pHeap, &heapLayout, pConfig->sampleRateIn, pConfig->sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_FALSE);
  41370. if (result != MA_SUCCESS) {
  41371. return result;
  41372. }
  41373. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  41374. pResampler->inTimeFrac = 0;
  41375. return MA_SUCCESS;
  41376. }
  41377. MA_API ma_result ma_linear_resampler_init(const ma_linear_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_linear_resampler* pResampler)
  41378. {
  41379. ma_result result;
  41380. size_t heapSizeInBytes;
  41381. void* pHeap;
  41382. result = ma_linear_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  41383. if (result != MA_SUCCESS) {
  41384. return result;
  41385. }
  41386. if (heapSizeInBytes > 0) {
  41387. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  41388. if (pHeap == NULL) {
  41389. return MA_OUT_OF_MEMORY;
  41390. }
  41391. } else {
  41392. pHeap = NULL;
  41393. }
  41394. result = ma_linear_resampler_init_preallocated(pConfig, pHeap, pResampler);
  41395. if (result != MA_SUCCESS) {
  41396. ma_free(pHeap, pAllocationCallbacks);
  41397. return result;
  41398. }
  41399. pResampler->_ownsHeap = MA_TRUE;
  41400. return MA_SUCCESS;
  41401. }
  41402. MA_API void ma_linear_resampler_uninit(ma_linear_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  41403. {
  41404. if (pResampler == NULL) {
  41405. return;
  41406. }
  41407. ma_lpf_uninit(&pResampler->lpf, pAllocationCallbacks);
  41408. if (pResampler->_ownsHeap) {
  41409. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  41410. }
  41411. }
  41412. static MA_INLINE ma_int16 ma_linear_resampler_mix_s16(ma_int16 x, ma_int16 y, ma_int32 a, const ma_int32 shift)
  41413. {
  41414. ma_int32 b;
  41415. ma_int32 c;
  41416. ma_int32 r;
  41417. MA_ASSERT(a <= (1<<shift));
  41418. b = x * ((1<<shift) - a);
  41419. c = y * a;
  41420. r = b + c;
  41421. return (ma_int16)(r >> shift);
  41422. }
  41423. static void ma_linear_resampler_interpolate_frame_s16(ma_linear_resampler* pResampler, ma_int16* MA_RESTRICT pFrameOut)
  41424. {
  41425. ma_uint32 c;
  41426. ma_uint32 a;
  41427. const ma_uint32 channels = pResampler->config.channels;
  41428. const ma_uint32 shift = 12;
  41429. MA_ASSERT(pResampler != NULL);
  41430. MA_ASSERT(pFrameOut != NULL);
  41431. a = (pResampler->inTimeFrac << shift) / pResampler->config.sampleRateOut;
  41432. MA_ASSUME(channels > 0);
  41433. for (c = 0; c < channels; c += 1) {
  41434. ma_int16 s = ma_linear_resampler_mix_s16(pResampler->x0.s16[c], pResampler->x1.s16[c], a, shift);
  41435. pFrameOut[c] = s;
  41436. }
  41437. }
  41438. static void ma_linear_resampler_interpolate_frame_f32(ma_linear_resampler* pResampler, float* MA_RESTRICT pFrameOut)
  41439. {
  41440. ma_uint32 c;
  41441. float a;
  41442. const ma_uint32 channels = pResampler->config.channels;
  41443. MA_ASSERT(pResampler != NULL);
  41444. MA_ASSERT(pFrameOut != NULL);
  41445. a = (float)pResampler->inTimeFrac / pResampler->config.sampleRateOut;
  41446. MA_ASSUME(channels > 0);
  41447. for (c = 0; c < channels; c += 1) {
  41448. float s = ma_mix_f32_fast(pResampler->x0.f32[c], pResampler->x1.f32[c], a);
  41449. pFrameOut[c] = s;
  41450. }
  41451. }
  41452. 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)
  41453. {
  41454. const ma_int16* pFramesInS16;
  41455. /* */ ma_int16* pFramesOutS16;
  41456. ma_uint64 frameCountIn;
  41457. ma_uint64 frameCountOut;
  41458. ma_uint64 framesProcessedIn;
  41459. ma_uint64 framesProcessedOut;
  41460. MA_ASSERT(pResampler != NULL);
  41461. MA_ASSERT(pFrameCountIn != NULL);
  41462. MA_ASSERT(pFrameCountOut != NULL);
  41463. pFramesInS16 = (const ma_int16*)pFramesIn;
  41464. pFramesOutS16 = ( ma_int16*)pFramesOut;
  41465. frameCountIn = *pFrameCountIn;
  41466. frameCountOut = *pFrameCountOut;
  41467. framesProcessedIn = 0;
  41468. framesProcessedOut = 0;
  41469. while (framesProcessedOut < frameCountOut) {
  41470. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  41471. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  41472. ma_uint32 iChannel;
  41473. if (pFramesInS16 != NULL) {
  41474. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41475. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  41476. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  41477. }
  41478. pFramesInS16 += pResampler->config.channels;
  41479. } else {
  41480. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41481. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  41482. pResampler->x1.s16[iChannel] = 0;
  41483. }
  41484. }
  41485. /* Filter. */
  41486. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pResampler->x1.s16, pResampler->x1.s16);
  41487. framesProcessedIn += 1;
  41488. pResampler->inTimeInt -= 1;
  41489. }
  41490. if (pResampler->inTimeInt > 0) {
  41491. break; /* Ran out of input data. */
  41492. }
  41493. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  41494. if (pFramesOutS16 != NULL) {
  41495. MA_ASSERT(pResampler->inTimeInt == 0);
  41496. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  41497. pFramesOutS16 += pResampler->config.channels;
  41498. }
  41499. framesProcessedOut += 1;
  41500. /* Advance time forward. */
  41501. pResampler->inTimeInt += pResampler->inAdvanceInt;
  41502. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  41503. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  41504. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  41505. pResampler->inTimeInt += 1;
  41506. }
  41507. }
  41508. *pFrameCountIn = framesProcessedIn;
  41509. *pFrameCountOut = framesProcessedOut;
  41510. return MA_SUCCESS;
  41511. }
  41512. 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)
  41513. {
  41514. const ma_int16* pFramesInS16;
  41515. /* */ ma_int16* pFramesOutS16;
  41516. ma_uint64 frameCountIn;
  41517. ma_uint64 frameCountOut;
  41518. ma_uint64 framesProcessedIn;
  41519. ma_uint64 framesProcessedOut;
  41520. MA_ASSERT(pResampler != NULL);
  41521. MA_ASSERT(pFrameCountIn != NULL);
  41522. MA_ASSERT(pFrameCountOut != NULL);
  41523. pFramesInS16 = (const ma_int16*)pFramesIn;
  41524. pFramesOutS16 = ( ma_int16*)pFramesOut;
  41525. frameCountIn = *pFrameCountIn;
  41526. frameCountOut = *pFrameCountOut;
  41527. framesProcessedIn = 0;
  41528. framesProcessedOut = 0;
  41529. while (framesProcessedOut < frameCountOut) {
  41530. /* Before interpolating we need to load the buffers. */
  41531. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  41532. ma_uint32 iChannel;
  41533. if (pFramesInS16 != NULL) {
  41534. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41535. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  41536. pResampler->x1.s16[iChannel] = pFramesInS16[iChannel];
  41537. }
  41538. pFramesInS16 += pResampler->config.channels;
  41539. } else {
  41540. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41541. pResampler->x0.s16[iChannel] = pResampler->x1.s16[iChannel];
  41542. pResampler->x1.s16[iChannel] = 0;
  41543. }
  41544. }
  41545. framesProcessedIn += 1;
  41546. pResampler->inTimeInt -= 1;
  41547. }
  41548. if (pResampler->inTimeInt > 0) {
  41549. break; /* Ran out of input data. */
  41550. }
  41551. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  41552. if (pFramesOutS16 != NULL) {
  41553. MA_ASSERT(pResampler->inTimeInt == 0);
  41554. ma_linear_resampler_interpolate_frame_s16(pResampler, pFramesOutS16);
  41555. /* Filter. */
  41556. ma_lpf_process_pcm_frame_s16(&pResampler->lpf, pFramesOutS16, pFramesOutS16);
  41557. pFramesOutS16 += pResampler->config.channels;
  41558. }
  41559. framesProcessedOut += 1;
  41560. /* Advance time forward. */
  41561. pResampler->inTimeInt += pResampler->inAdvanceInt;
  41562. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  41563. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  41564. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  41565. pResampler->inTimeInt += 1;
  41566. }
  41567. }
  41568. *pFrameCountIn = framesProcessedIn;
  41569. *pFrameCountOut = framesProcessedOut;
  41570. return MA_SUCCESS;
  41571. }
  41572. 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)
  41573. {
  41574. MA_ASSERT(pResampler != NULL);
  41575. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  41576. return ma_linear_resampler_process_pcm_frames_s16_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41577. } else {
  41578. return ma_linear_resampler_process_pcm_frames_s16_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41579. }
  41580. }
  41581. 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)
  41582. {
  41583. const float* pFramesInF32;
  41584. /* */ float* pFramesOutF32;
  41585. ma_uint64 frameCountIn;
  41586. ma_uint64 frameCountOut;
  41587. ma_uint64 framesProcessedIn;
  41588. ma_uint64 framesProcessedOut;
  41589. MA_ASSERT(pResampler != NULL);
  41590. MA_ASSERT(pFrameCountIn != NULL);
  41591. MA_ASSERT(pFrameCountOut != NULL);
  41592. pFramesInF32 = (const float*)pFramesIn;
  41593. pFramesOutF32 = ( float*)pFramesOut;
  41594. frameCountIn = *pFrameCountIn;
  41595. frameCountOut = *pFrameCountOut;
  41596. framesProcessedIn = 0;
  41597. framesProcessedOut = 0;
  41598. while (framesProcessedOut < frameCountOut) {
  41599. /* Before interpolating we need to load the buffers. When doing this we need to ensure we run every input sample through the filter. */
  41600. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  41601. ma_uint32 iChannel;
  41602. if (pFramesInF32 != NULL) {
  41603. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41604. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  41605. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  41606. }
  41607. pFramesInF32 += pResampler->config.channels;
  41608. } else {
  41609. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41610. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  41611. pResampler->x1.f32[iChannel] = 0;
  41612. }
  41613. }
  41614. /* Filter. */
  41615. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pResampler->x1.f32, pResampler->x1.f32);
  41616. framesProcessedIn += 1;
  41617. pResampler->inTimeInt -= 1;
  41618. }
  41619. if (pResampler->inTimeInt > 0) {
  41620. break; /* Ran out of input data. */
  41621. }
  41622. /* Getting here means the frames have been loaded and filtered and we can generate the next output frame. */
  41623. if (pFramesOutF32 != NULL) {
  41624. MA_ASSERT(pResampler->inTimeInt == 0);
  41625. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  41626. pFramesOutF32 += pResampler->config.channels;
  41627. }
  41628. framesProcessedOut += 1;
  41629. /* Advance time forward. */
  41630. pResampler->inTimeInt += pResampler->inAdvanceInt;
  41631. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  41632. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  41633. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  41634. pResampler->inTimeInt += 1;
  41635. }
  41636. }
  41637. *pFrameCountIn = framesProcessedIn;
  41638. *pFrameCountOut = framesProcessedOut;
  41639. return MA_SUCCESS;
  41640. }
  41641. 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)
  41642. {
  41643. const float* pFramesInF32;
  41644. /* */ float* pFramesOutF32;
  41645. ma_uint64 frameCountIn;
  41646. ma_uint64 frameCountOut;
  41647. ma_uint64 framesProcessedIn;
  41648. ma_uint64 framesProcessedOut;
  41649. MA_ASSERT(pResampler != NULL);
  41650. MA_ASSERT(pFrameCountIn != NULL);
  41651. MA_ASSERT(pFrameCountOut != NULL);
  41652. pFramesInF32 = (const float*)pFramesIn;
  41653. pFramesOutF32 = ( float*)pFramesOut;
  41654. frameCountIn = *pFrameCountIn;
  41655. frameCountOut = *pFrameCountOut;
  41656. framesProcessedIn = 0;
  41657. framesProcessedOut = 0;
  41658. while (framesProcessedOut < frameCountOut) {
  41659. /* Before interpolating we need to load the buffers. */
  41660. while (pResampler->inTimeInt > 0 && frameCountIn > framesProcessedIn) {
  41661. ma_uint32 iChannel;
  41662. if (pFramesInF32 != NULL) {
  41663. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41664. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  41665. pResampler->x1.f32[iChannel] = pFramesInF32[iChannel];
  41666. }
  41667. pFramesInF32 += pResampler->config.channels;
  41668. } else {
  41669. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41670. pResampler->x0.f32[iChannel] = pResampler->x1.f32[iChannel];
  41671. pResampler->x1.f32[iChannel] = 0;
  41672. }
  41673. }
  41674. framesProcessedIn += 1;
  41675. pResampler->inTimeInt -= 1;
  41676. }
  41677. if (pResampler->inTimeInt > 0) {
  41678. break; /* Ran out of input data. */
  41679. }
  41680. /* Getting here means the frames have been loaded and we can generate the next output frame. */
  41681. if (pFramesOutF32 != NULL) {
  41682. MA_ASSERT(pResampler->inTimeInt == 0);
  41683. ma_linear_resampler_interpolate_frame_f32(pResampler, pFramesOutF32);
  41684. /* Filter. */
  41685. ma_lpf_process_pcm_frame_f32(&pResampler->lpf, pFramesOutF32, pFramesOutF32);
  41686. pFramesOutF32 += pResampler->config.channels;
  41687. }
  41688. framesProcessedOut += 1;
  41689. /* Advance time forward. */
  41690. pResampler->inTimeInt += pResampler->inAdvanceInt;
  41691. pResampler->inTimeFrac += pResampler->inAdvanceFrac;
  41692. if (pResampler->inTimeFrac >= pResampler->config.sampleRateOut) {
  41693. pResampler->inTimeFrac -= pResampler->config.sampleRateOut;
  41694. pResampler->inTimeInt += 1;
  41695. }
  41696. }
  41697. *pFrameCountIn = framesProcessedIn;
  41698. *pFrameCountOut = framesProcessedOut;
  41699. return MA_SUCCESS;
  41700. }
  41701. 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)
  41702. {
  41703. MA_ASSERT(pResampler != NULL);
  41704. if (pResampler->config.sampleRateIn > pResampler->config.sampleRateOut) {
  41705. return ma_linear_resampler_process_pcm_frames_f32_downsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41706. } else {
  41707. return ma_linear_resampler_process_pcm_frames_f32_upsample(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41708. }
  41709. }
  41710. 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)
  41711. {
  41712. if (pResampler == NULL) {
  41713. return MA_INVALID_ARGS;
  41714. }
  41715. /* */ if (pResampler->config.format == ma_format_s16) {
  41716. return ma_linear_resampler_process_pcm_frames_s16(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41717. } else if (pResampler->config.format == ma_format_f32) {
  41718. return ma_linear_resampler_process_pcm_frames_f32(pResampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41719. } else {
  41720. /* 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(). */
  41721. MA_ASSERT(MA_FALSE);
  41722. return MA_INVALID_ARGS;
  41723. }
  41724. }
  41725. MA_API ma_result ma_linear_resampler_set_rate(ma_linear_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  41726. {
  41727. return ma_linear_resampler_set_rate_internal(pResampler, NULL, NULL, sampleRateIn, sampleRateOut, /* isResamplerAlreadyInitialized = */ MA_TRUE);
  41728. }
  41729. MA_API ma_result ma_linear_resampler_set_rate_ratio(ma_linear_resampler* pResampler, float ratioInOut)
  41730. {
  41731. ma_uint32 n;
  41732. ma_uint32 d;
  41733. if (pResampler == NULL) {
  41734. return MA_INVALID_ARGS;
  41735. }
  41736. if (ratioInOut <= 0) {
  41737. return MA_INVALID_ARGS;
  41738. }
  41739. d = 1000;
  41740. n = (ma_uint32)(ratioInOut * d);
  41741. if (n == 0) {
  41742. return MA_INVALID_ARGS; /* Ratio too small. */
  41743. }
  41744. MA_ASSERT(n != 0);
  41745. return ma_linear_resampler_set_rate(pResampler, n, d);
  41746. }
  41747. MA_API ma_uint64 ma_linear_resampler_get_input_latency(const ma_linear_resampler* pResampler)
  41748. {
  41749. if (pResampler == NULL) {
  41750. return 0;
  41751. }
  41752. return 1 + ma_lpf_get_latency(&pResampler->lpf);
  41753. }
  41754. MA_API ma_uint64 ma_linear_resampler_get_output_latency(const ma_linear_resampler* pResampler)
  41755. {
  41756. if (pResampler == NULL) {
  41757. return 0;
  41758. }
  41759. return ma_linear_resampler_get_input_latency(pResampler) * pResampler->config.sampleRateOut / pResampler->config.sampleRateIn;
  41760. }
  41761. MA_API ma_result ma_linear_resampler_get_required_input_frame_count(const ma_linear_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  41762. {
  41763. ma_uint64 inputFrameCount;
  41764. if (pInputFrameCount == NULL) {
  41765. return MA_INVALID_ARGS;
  41766. }
  41767. *pInputFrameCount = 0;
  41768. if (pResampler == NULL) {
  41769. return MA_INVALID_ARGS;
  41770. }
  41771. if (outputFrameCount == 0) {
  41772. return MA_SUCCESS;
  41773. }
  41774. /* Any whole input frames are consumed before the first output frame is generated. */
  41775. inputFrameCount = pResampler->inTimeInt;
  41776. outputFrameCount -= 1;
  41777. /* The rest of the output frames can be calculated in constant time. */
  41778. inputFrameCount += outputFrameCount * pResampler->inAdvanceInt;
  41779. inputFrameCount += (pResampler->inTimeFrac + (outputFrameCount * pResampler->inAdvanceFrac)) / pResampler->config.sampleRateOut;
  41780. *pInputFrameCount = inputFrameCount;
  41781. return MA_SUCCESS;
  41782. }
  41783. MA_API ma_result ma_linear_resampler_get_expected_output_frame_count(const ma_linear_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  41784. {
  41785. ma_uint64 outputFrameCount;
  41786. ma_uint64 preliminaryInputFrameCountFromFrac;
  41787. ma_uint64 preliminaryInputFrameCount;
  41788. if (pOutputFrameCount == NULL) {
  41789. return MA_INVALID_ARGS;
  41790. }
  41791. *pOutputFrameCount = 0;
  41792. if (pResampler == NULL) {
  41793. return MA_INVALID_ARGS;
  41794. }
  41795. /*
  41796. 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
  41797. 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
  41798. 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
  41799. of an extra output frame. This add-by-one logic is necessary due to how the data loading logic works when processing frames.
  41800. */
  41801. outputFrameCount = (inputFrameCount * pResampler->config.sampleRateOut) / pResampler->config.sampleRateIn;
  41802. /*
  41803. We need to determine how many *whole* input frames will have been processed to generate our preliminary output frame count. This is
  41804. used in the logic below to determine whether or not we need to add an extra output frame.
  41805. */
  41806. preliminaryInputFrameCountFromFrac = (pResampler->inTimeFrac + outputFrameCount*pResampler->inAdvanceFrac) / pResampler->config.sampleRateOut;
  41807. preliminaryInputFrameCount = (pResampler->inTimeInt + outputFrameCount*pResampler->inAdvanceInt ) + preliminaryInputFrameCountFromFrac;
  41808. /*
  41809. If the total number of *whole* input frames that would be required to generate our preliminary output frame count is greather than
  41810. 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
  41811. to actually process. Otherwise we need to add the extra output frame.
  41812. */
  41813. if (preliminaryInputFrameCount <= inputFrameCount) {
  41814. outputFrameCount += 1;
  41815. }
  41816. *pOutputFrameCount = outputFrameCount;
  41817. return MA_SUCCESS;
  41818. }
  41819. MA_API ma_result ma_linear_resampler_reset(ma_linear_resampler* pResampler)
  41820. {
  41821. ma_uint32 iChannel;
  41822. if (pResampler == NULL) {
  41823. return MA_INVALID_ARGS;
  41824. }
  41825. /* Timers need to be cleared back to zero. */
  41826. pResampler->inTimeInt = 1; /* Set this to one to force an input sample to always be loaded for the first output frame. */
  41827. pResampler->inTimeFrac = 0;
  41828. /* Cached samples need to be cleared. */
  41829. if (pResampler->config.format == ma_format_f32) {
  41830. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41831. pResampler->x0.f32[iChannel] = 0;
  41832. pResampler->x1.f32[iChannel] = 0;
  41833. }
  41834. } else {
  41835. for (iChannel = 0; iChannel < pResampler->config.channels; iChannel += 1) {
  41836. pResampler->x0.s16[iChannel] = 0;
  41837. pResampler->x1.s16[iChannel] = 0;
  41838. }
  41839. }
  41840. /* The low pass filter needs to have it's cache reset. */
  41841. ma_lpf_clear_cache(&pResampler->lpf);
  41842. return MA_SUCCESS;
  41843. }
  41844. /* Linear resampler backend vtable. */
  41845. static ma_linear_resampler_config ma_resampling_backend_get_config__linear(const ma_resampler_config* pConfig)
  41846. {
  41847. ma_linear_resampler_config linearConfig;
  41848. linearConfig = ma_linear_resampler_config_init(pConfig->format, pConfig->channels, pConfig->sampleRateIn, pConfig->sampleRateOut);
  41849. linearConfig.lpfOrder = pConfig->linear.lpfOrder;
  41850. return linearConfig;
  41851. }
  41852. static ma_result ma_resampling_backend_get_heap_size__linear(void* pUserData, const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  41853. {
  41854. ma_linear_resampler_config linearConfig;
  41855. (void)pUserData;
  41856. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  41857. return ma_linear_resampler_get_heap_size(&linearConfig, pHeapSizeInBytes);
  41858. }
  41859. static ma_result ma_resampling_backend_init__linear(void* pUserData, const ma_resampler_config* pConfig, void* pHeap, ma_resampling_backend** ppBackend)
  41860. {
  41861. ma_resampler* pResampler = (ma_resampler*)pUserData;
  41862. ma_result result;
  41863. ma_linear_resampler_config linearConfig;
  41864. (void)pUserData;
  41865. linearConfig = ma_resampling_backend_get_config__linear(pConfig);
  41866. result = ma_linear_resampler_init_preallocated(&linearConfig, pHeap, &pResampler->state.linear);
  41867. if (result != MA_SUCCESS) {
  41868. return result;
  41869. }
  41870. *ppBackend = &pResampler->state.linear;
  41871. return MA_SUCCESS;
  41872. }
  41873. static void ma_resampling_backend_uninit__linear(void* pUserData, ma_resampling_backend* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  41874. {
  41875. (void)pUserData;
  41876. ma_linear_resampler_uninit((ma_linear_resampler*)pBackend, pAllocationCallbacks);
  41877. }
  41878. 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)
  41879. {
  41880. (void)pUserData;
  41881. return ma_linear_resampler_process_pcm_frames((ma_linear_resampler*)pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  41882. }
  41883. static ma_result ma_resampling_backend_set_rate__linear(void* pUserData, ma_resampling_backend* pBackend, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  41884. {
  41885. (void)pUserData;
  41886. return ma_linear_resampler_set_rate((ma_linear_resampler*)pBackend, sampleRateIn, sampleRateOut);
  41887. }
  41888. static ma_uint64 ma_resampling_backend_get_input_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  41889. {
  41890. (void)pUserData;
  41891. return ma_linear_resampler_get_input_latency((const ma_linear_resampler*)pBackend);
  41892. }
  41893. static ma_uint64 ma_resampling_backend_get_output_latency__linear(void* pUserData, const ma_resampling_backend* pBackend)
  41894. {
  41895. (void)pUserData;
  41896. return ma_linear_resampler_get_output_latency((const ma_linear_resampler*)pBackend);
  41897. }
  41898. 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)
  41899. {
  41900. (void)pUserData;
  41901. return ma_linear_resampler_get_required_input_frame_count((const ma_linear_resampler*)pBackend, outputFrameCount, pInputFrameCount);
  41902. }
  41903. 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)
  41904. {
  41905. (void)pUserData;
  41906. return ma_linear_resampler_get_expected_output_frame_count((const ma_linear_resampler*)pBackend, inputFrameCount, pOutputFrameCount);
  41907. }
  41908. static ma_result ma_resampling_backend_reset__linear(void* pUserData, ma_resampling_backend* pBackend)
  41909. {
  41910. (void)pUserData;
  41911. return ma_linear_resampler_reset((ma_linear_resampler*)pBackend);
  41912. }
  41913. static ma_resampling_backend_vtable g_ma_linear_resampler_vtable =
  41914. {
  41915. ma_resampling_backend_get_heap_size__linear,
  41916. ma_resampling_backend_init__linear,
  41917. ma_resampling_backend_uninit__linear,
  41918. ma_resampling_backend_process__linear,
  41919. ma_resampling_backend_set_rate__linear,
  41920. ma_resampling_backend_get_input_latency__linear,
  41921. ma_resampling_backend_get_output_latency__linear,
  41922. ma_resampling_backend_get_required_input_frame_count__linear,
  41923. ma_resampling_backend_get_expected_output_frame_count__linear,
  41924. ma_resampling_backend_reset__linear
  41925. };
  41926. 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)
  41927. {
  41928. ma_resampler_config config;
  41929. MA_ZERO_OBJECT(&config);
  41930. config.format = format;
  41931. config.channels = channels;
  41932. config.sampleRateIn = sampleRateIn;
  41933. config.sampleRateOut = sampleRateOut;
  41934. config.algorithm = algorithm;
  41935. /* Linear. */
  41936. config.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  41937. return config;
  41938. }
  41939. static ma_result ma_resampler_get_vtable(const ma_resampler_config* pConfig, ma_resampler* pResampler, ma_resampling_backend_vtable** ppVTable, void** ppUserData)
  41940. {
  41941. MA_ASSERT(pConfig != NULL);
  41942. MA_ASSERT(ppVTable != NULL);
  41943. MA_ASSERT(ppUserData != NULL);
  41944. /* Safety. */
  41945. *ppVTable = NULL;
  41946. *ppUserData = NULL;
  41947. switch (pConfig->algorithm)
  41948. {
  41949. case ma_resample_algorithm_linear:
  41950. {
  41951. *ppVTable = &g_ma_linear_resampler_vtable;
  41952. *ppUserData = pResampler;
  41953. } break;
  41954. case ma_resample_algorithm_custom:
  41955. {
  41956. *ppVTable = pConfig->pBackendVTable;
  41957. *ppUserData = pConfig->pBackendUserData;
  41958. } break;
  41959. default: return MA_INVALID_ARGS;
  41960. }
  41961. return MA_SUCCESS;
  41962. }
  41963. MA_API ma_result ma_resampler_get_heap_size(const ma_resampler_config* pConfig, size_t* pHeapSizeInBytes)
  41964. {
  41965. ma_result result;
  41966. ma_resampling_backend_vtable* pVTable;
  41967. void* pVTableUserData;
  41968. if (pHeapSizeInBytes == NULL) {
  41969. return MA_INVALID_ARGS;
  41970. }
  41971. *pHeapSizeInBytes = 0;
  41972. if (pConfig == NULL) {
  41973. return MA_INVALID_ARGS;
  41974. }
  41975. result = ma_resampler_get_vtable(pConfig, NULL, &pVTable, &pVTableUserData);
  41976. if (result != MA_SUCCESS) {
  41977. return result;
  41978. }
  41979. if (pVTable == NULL || pVTable->onGetHeapSize == NULL) {
  41980. return MA_NOT_IMPLEMENTED;
  41981. }
  41982. result = pVTable->onGetHeapSize(pVTableUserData, pConfig, pHeapSizeInBytes);
  41983. if (result != MA_SUCCESS) {
  41984. return result;
  41985. }
  41986. return MA_SUCCESS;
  41987. }
  41988. MA_API ma_result ma_resampler_init_preallocated(const ma_resampler_config* pConfig, void* pHeap, ma_resampler* pResampler)
  41989. {
  41990. ma_result result;
  41991. if (pResampler == NULL) {
  41992. return MA_INVALID_ARGS;
  41993. }
  41994. MA_ZERO_OBJECT(pResampler);
  41995. if (pConfig == NULL) {
  41996. return MA_INVALID_ARGS;
  41997. }
  41998. pResampler->_pHeap = pHeap;
  41999. pResampler->format = pConfig->format;
  42000. pResampler->channels = pConfig->channels;
  42001. pResampler->sampleRateIn = pConfig->sampleRateIn;
  42002. pResampler->sampleRateOut = pConfig->sampleRateOut;
  42003. result = ma_resampler_get_vtable(pConfig, pResampler, &pResampler->pBackendVTable, &pResampler->pBackendUserData);
  42004. if (result != MA_SUCCESS) {
  42005. return result;
  42006. }
  42007. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onInit == NULL) {
  42008. return MA_NOT_IMPLEMENTED; /* onInit not implemented. */
  42009. }
  42010. result = pResampler->pBackendVTable->onInit(pResampler->pBackendUserData, pConfig, pHeap, &pResampler->pBackend);
  42011. if (result != MA_SUCCESS) {
  42012. return result;
  42013. }
  42014. return MA_SUCCESS;
  42015. }
  42016. MA_API ma_result ma_resampler_init(const ma_resampler_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_resampler* pResampler)
  42017. {
  42018. ma_result result;
  42019. size_t heapSizeInBytes;
  42020. void* pHeap;
  42021. result = ma_resampler_get_heap_size(pConfig, &heapSizeInBytes);
  42022. if (result != MA_SUCCESS) {
  42023. return result;
  42024. }
  42025. if (heapSizeInBytes > 0) {
  42026. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  42027. if (pHeap == NULL) {
  42028. return MA_OUT_OF_MEMORY;
  42029. }
  42030. } else {
  42031. pHeap = NULL;
  42032. }
  42033. result = ma_resampler_init_preallocated(pConfig, pHeap, pResampler);
  42034. if (result != MA_SUCCESS) {
  42035. ma_free(pHeap, pAllocationCallbacks);
  42036. return result;
  42037. }
  42038. pResampler->_ownsHeap = MA_TRUE;
  42039. return MA_SUCCESS;
  42040. }
  42041. MA_API void ma_resampler_uninit(ma_resampler* pResampler, const ma_allocation_callbacks* pAllocationCallbacks)
  42042. {
  42043. if (pResampler == NULL) {
  42044. return;
  42045. }
  42046. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onUninit == NULL) {
  42047. return;
  42048. }
  42049. pResampler->pBackendVTable->onUninit(pResampler->pBackendUserData, pResampler->pBackend, pAllocationCallbacks);
  42050. if (pResampler->_ownsHeap) {
  42051. ma_free(pResampler->_pHeap, pAllocationCallbacks);
  42052. }
  42053. }
  42054. MA_API ma_result ma_resampler_process_pcm_frames(ma_resampler* pResampler, const void* pFramesIn, ma_uint64* pFrameCountIn, void* pFramesOut, ma_uint64* pFrameCountOut)
  42055. {
  42056. if (pResampler == NULL) {
  42057. return MA_INVALID_ARGS;
  42058. }
  42059. if (pFrameCountOut == NULL && pFrameCountIn == NULL) {
  42060. return MA_INVALID_ARGS;
  42061. }
  42062. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onProcess == NULL) {
  42063. return MA_NOT_IMPLEMENTED;
  42064. }
  42065. return pResampler->pBackendVTable->onProcess(pResampler->pBackendUserData, pResampler->pBackend, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  42066. }
  42067. MA_API ma_result ma_resampler_set_rate(ma_resampler* pResampler, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  42068. {
  42069. ma_result result;
  42070. if (pResampler == NULL) {
  42071. return MA_INVALID_ARGS;
  42072. }
  42073. if (sampleRateIn == 0 || sampleRateOut == 0) {
  42074. return MA_INVALID_ARGS;
  42075. }
  42076. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onSetRate == NULL) {
  42077. return MA_NOT_IMPLEMENTED;
  42078. }
  42079. result = pResampler->pBackendVTable->onSetRate(pResampler->pBackendUserData, pResampler->pBackend, sampleRateIn, sampleRateOut);
  42080. if (result != MA_SUCCESS) {
  42081. return result;
  42082. }
  42083. pResampler->sampleRateIn = sampleRateIn;
  42084. pResampler->sampleRateOut = sampleRateOut;
  42085. return MA_SUCCESS;
  42086. }
  42087. MA_API ma_result ma_resampler_set_rate_ratio(ma_resampler* pResampler, float ratio)
  42088. {
  42089. ma_uint32 n;
  42090. ma_uint32 d;
  42091. if (pResampler == NULL) {
  42092. return MA_INVALID_ARGS;
  42093. }
  42094. if (ratio <= 0) {
  42095. return MA_INVALID_ARGS;
  42096. }
  42097. d = 1000;
  42098. n = (ma_uint32)(ratio * d);
  42099. if (n == 0) {
  42100. return MA_INVALID_ARGS; /* Ratio too small. */
  42101. }
  42102. MA_ASSERT(n != 0);
  42103. return ma_resampler_set_rate(pResampler, n, d);
  42104. }
  42105. MA_API ma_uint64 ma_resampler_get_input_latency(const ma_resampler* pResampler)
  42106. {
  42107. if (pResampler == NULL) {
  42108. return 0;
  42109. }
  42110. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetInputLatency == NULL) {
  42111. return 0;
  42112. }
  42113. return pResampler->pBackendVTable->onGetInputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  42114. }
  42115. MA_API ma_uint64 ma_resampler_get_output_latency(const ma_resampler* pResampler)
  42116. {
  42117. if (pResampler == NULL) {
  42118. return 0;
  42119. }
  42120. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetOutputLatency == NULL) {
  42121. return 0;
  42122. }
  42123. return pResampler->pBackendVTable->onGetOutputLatency(pResampler->pBackendUserData, pResampler->pBackend);
  42124. }
  42125. MA_API ma_result ma_resampler_get_required_input_frame_count(const ma_resampler* pResampler, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  42126. {
  42127. if (pInputFrameCount == NULL) {
  42128. return MA_INVALID_ARGS;
  42129. }
  42130. *pInputFrameCount = 0;
  42131. if (pResampler == NULL) {
  42132. return MA_INVALID_ARGS;
  42133. }
  42134. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetRequiredInputFrameCount == NULL) {
  42135. return MA_NOT_IMPLEMENTED;
  42136. }
  42137. return pResampler->pBackendVTable->onGetRequiredInputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, outputFrameCount, pInputFrameCount);
  42138. }
  42139. MA_API ma_result ma_resampler_get_expected_output_frame_count(const ma_resampler* pResampler, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  42140. {
  42141. if (pOutputFrameCount == NULL) {
  42142. return MA_INVALID_ARGS;
  42143. }
  42144. *pOutputFrameCount = 0;
  42145. if (pResampler == NULL) {
  42146. return MA_INVALID_ARGS;
  42147. }
  42148. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onGetExpectedOutputFrameCount == NULL) {
  42149. return MA_NOT_IMPLEMENTED;
  42150. }
  42151. return pResampler->pBackendVTable->onGetExpectedOutputFrameCount(pResampler->pBackendUserData, pResampler->pBackend, inputFrameCount, pOutputFrameCount);
  42152. }
  42153. MA_API ma_result ma_resampler_reset(ma_resampler* pResampler)
  42154. {
  42155. if (pResampler == NULL) {
  42156. return MA_INVALID_ARGS;
  42157. }
  42158. if (pResampler->pBackendVTable == NULL || pResampler->pBackendVTable->onReset == NULL) {
  42159. return MA_NOT_IMPLEMENTED;
  42160. }
  42161. return pResampler->pBackendVTable->onReset(pResampler->pBackendUserData, pResampler->pBackend);
  42162. }
  42163. /**************************************************************************************************************************************************************
  42164. Channel Conversion
  42165. **************************************************************************************************************************************************************/
  42166. #ifndef MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT
  42167. #define MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT 12
  42168. #endif
  42169. #define MA_PLANE_LEFT 0
  42170. #define MA_PLANE_RIGHT 1
  42171. #define MA_PLANE_FRONT 2
  42172. #define MA_PLANE_BACK 3
  42173. #define MA_PLANE_BOTTOM 4
  42174. #define MA_PLANE_TOP 5
  42175. static float g_maChannelPlaneRatios[MA_CHANNEL_POSITION_COUNT][6] = {
  42176. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_NONE */
  42177. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_MONO */
  42178. { 0.5f, 0.0f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT */
  42179. { 0.0f, 0.5f, 0.5f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT */
  42180. { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_CENTER */
  42181. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_LFE */
  42182. { 0.5f, 0.0f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_LEFT */
  42183. { 0.0f, 0.5f, 0.0f, 0.5f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_RIGHT */
  42184. { 0.25f, 0.0f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_LEFT_CENTER */
  42185. { 0.0f, 0.25f, 0.75f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_FRONT_RIGHT_CENTER */
  42186. { 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f}, /* MA_CHANNEL_BACK_CENTER */
  42187. { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_LEFT */
  42188. { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_SIDE_RIGHT */
  42189. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}, /* MA_CHANNEL_TOP_CENTER */
  42190. { 0.33f, 0.0f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_LEFT */
  42191. { 0.0f, 0.0f, 0.5f, 0.0f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_FRONT_CENTER */
  42192. { 0.0f, 0.33f, 0.33f, 0.0f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_FRONT_RIGHT */
  42193. { 0.33f, 0.0f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_LEFT */
  42194. { 0.0f, 0.0f, 0.0f, 0.5f, 0.0f, 0.5f}, /* MA_CHANNEL_TOP_BACK_CENTER */
  42195. { 0.0f, 0.33f, 0.0f, 0.33f, 0.0f, 0.34f}, /* MA_CHANNEL_TOP_BACK_RIGHT */
  42196. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_0 */
  42197. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_1 */
  42198. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_2 */
  42199. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_3 */
  42200. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_4 */
  42201. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_5 */
  42202. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_6 */
  42203. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_7 */
  42204. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_8 */
  42205. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_9 */
  42206. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_10 */
  42207. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_11 */
  42208. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_12 */
  42209. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_13 */
  42210. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_14 */
  42211. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_15 */
  42212. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_16 */
  42213. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_17 */
  42214. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_18 */
  42215. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_19 */
  42216. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_20 */
  42217. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_21 */
  42218. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_22 */
  42219. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_23 */
  42220. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_24 */
  42221. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_25 */
  42222. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_26 */
  42223. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_27 */
  42224. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_28 */
  42225. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_29 */
  42226. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_30 */
  42227. { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f}, /* MA_CHANNEL_AUX_31 */
  42228. };
  42229. static float ma_calculate_channel_position_rectangular_weight(ma_channel channelPositionA, ma_channel channelPositionB)
  42230. {
  42231. /*
  42232. Imagine the following simplified example: You have a single input speaker which is the front/left speaker which you want to convert to
  42233. the following output configuration:
  42234. - front/left
  42235. - side/left
  42236. - back/left
  42237. The front/left output is easy - it the same speaker position so it receives the full contribution of the front/left input. The amount
  42238. of contribution to apply to the side/left and back/left speakers, however, is a bit more complicated.
  42239. 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
  42240. 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
  42241. 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
  42242. receive some amount of contribution from front/left speaker. The amount of contribution depends on how many planes are shared between
  42243. 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
  42244. across 3 spatial dimensions.
  42245. The first thing to do is figure out how each speaker's volume is spread over each of plane:
  42246. - front/left: 2 planes (front and left) = 1/2 = half it's total volume on each plane
  42247. - side/left: 1 plane (left only) = 1/1 = entire volume from left plane
  42248. - back/left: 2 planes (back and left) = 1/2 = half it's total volume on each plane
  42249. - top/front/left: 3 planes (top, front and left) = 1/3 = one third it's total volume on each plane
  42250. 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
  42251. 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
  42252. taken by the other to produce the final contribution.
  42253. */
  42254. /* Contribution = Sum(Volume to Give * Volume to Take) */
  42255. float contribution =
  42256. g_maChannelPlaneRatios[channelPositionA][0] * g_maChannelPlaneRatios[channelPositionB][0] +
  42257. g_maChannelPlaneRatios[channelPositionA][1] * g_maChannelPlaneRatios[channelPositionB][1] +
  42258. g_maChannelPlaneRatios[channelPositionA][2] * g_maChannelPlaneRatios[channelPositionB][2] +
  42259. g_maChannelPlaneRatios[channelPositionA][3] * g_maChannelPlaneRatios[channelPositionB][3] +
  42260. g_maChannelPlaneRatios[channelPositionA][4] * g_maChannelPlaneRatios[channelPositionB][4] +
  42261. g_maChannelPlaneRatios[channelPositionA][5] * g_maChannelPlaneRatios[channelPositionB][5];
  42262. return contribution;
  42263. }
  42264. 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)
  42265. {
  42266. ma_channel_converter_config config;
  42267. MA_ZERO_OBJECT(&config);
  42268. config.format = format;
  42269. config.channelsIn = channelsIn;
  42270. config.channelsOut = channelsOut;
  42271. config.pChannelMapIn = pChannelMapIn;
  42272. config.pChannelMapOut = pChannelMapOut;
  42273. config.mixingMode = mixingMode;
  42274. return config;
  42275. }
  42276. static ma_int32 ma_channel_converter_float_to_fixed(float x)
  42277. {
  42278. return (ma_int32)(x * (1<<MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT));
  42279. }
  42280. static ma_uint32 ma_channel_map_get_spatial_channel_count(const ma_channel* pChannelMap, ma_uint32 channels)
  42281. {
  42282. ma_uint32 spatialChannelCount = 0;
  42283. ma_uint32 iChannel;
  42284. MA_ASSERT(pChannelMap != NULL);
  42285. MA_ASSERT(channels > 0);
  42286. for (iChannel = 0; iChannel < channels; ++iChannel) {
  42287. if (ma_is_spatial_channel_position(ma_channel_map_get_channel(pChannelMap, channels, iChannel))) {
  42288. spatialChannelCount++;
  42289. }
  42290. }
  42291. return spatialChannelCount;
  42292. }
  42293. static ma_bool32 ma_is_spatial_channel_position(ma_channel channelPosition)
  42294. {
  42295. int i;
  42296. if (channelPosition == MA_CHANNEL_NONE || channelPosition == MA_CHANNEL_MONO || channelPosition == MA_CHANNEL_LFE) {
  42297. return MA_FALSE;
  42298. }
  42299. if (channelPosition >= MA_CHANNEL_AUX_0 && channelPosition <= MA_CHANNEL_AUX_31) {
  42300. return MA_FALSE;
  42301. }
  42302. for (i = 0; i < 6; ++i) { /* Each side of a cube. */
  42303. if (g_maChannelPlaneRatios[channelPosition][i] != 0) {
  42304. return MA_TRUE;
  42305. }
  42306. }
  42307. return MA_FALSE;
  42308. }
  42309. static ma_bool32 ma_channel_map_is_passthrough(const ma_channel* pChannelMapIn, ma_uint32 channelsIn, const ma_channel* pChannelMapOut, ma_uint32 channelsOut)
  42310. {
  42311. if (channelsOut == channelsIn) {
  42312. return ma_channel_map_is_equal(pChannelMapOut, pChannelMapIn, channelsOut);
  42313. } else {
  42314. return MA_FALSE; /* Channel counts differ, so cannot be a passthrough. */
  42315. }
  42316. }
  42317. 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)
  42318. {
  42319. if (ma_channel_map_is_passthrough(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut)) {
  42320. return ma_channel_conversion_path_passthrough;
  42321. }
  42322. if (channelsOut == 1 && (pChannelMapOut == NULL || pChannelMapOut[0] == MA_CHANNEL_MONO)) {
  42323. return ma_channel_conversion_path_mono_out;
  42324. }
  42325. if (channelsIn == 1 && (pChannelMapIn == NULL || pChannelMapIn[0] == MA_CHANNEL_MONO)) {
  42326. return ma_channel_conversion_path_mono_in;
  42327. }
  42328. if (mode == ma_channel_mix_mode_custom_weights) {
  42329. return ma_channel_conversion_path_weights;
  42330. }
  42331. /*
  42332. We can use a simple shuffle if both channel maps have the same channel count and all channel
  42333. positions are present in both.
  42334. */
  42335. if (channelsIn == channelsOut) {
  42336. ma_uint32 iChannelIn;
  42337. ma_bool32 areAllChannelPositionsPresent = MA_TRUE;
  42338. for (iChannelIn = 0; iChannelIn < channelsIn; ++iChannelIn) {
  42339. ma_bool32 isInputChannelPositionInOutput = MA_FALSE;
  42340. if (ma_channel_map_contains_channel_position(channelsOut, pChannelMapOut, ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn))) {
  42341. isInputChannelPositionInOutput = MA_TRUE;
  42342. break;
  42343. }
  42344. if (!isInputChannelPositionInOutput) {
  42345. areAllChannelPositionsPresent = MA_FALSE;
  42346. break;
  42347. }
  42348. }
  42349. if (areAllChannelPositionsPresent) {
  42350. return ma_channel_conversion_path_shuffle;
  42351. }
  42352. }
  42353. /* Getting here means we'll need to use weights. */
  42354. return ma_channel_conversion_path_weights;
  42355. }
  42356. 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)
  42357. {
  42358. ma_uint32 iChannelIn;
  42359. ma_uint32 iChannelOut;
  42360. if (pShuffleTable == NULL || channelCountIn == 0 || channelCountOut == 0) {
  42361. return MA_INVALID_ARGS;
  42362. }
  42363. /*
  42364. When building the shuffle table we just do a 1:1 mapping based on the first occurance of a channel. If the
  42365. input channel has more than one occurance of a channel position, the second one will be ignored.
  42366. */
  42367. for (iChannelOut = 0; iChannelOut < channelCountOut; iChannelOut += 1) {
  42368. ma_channel channelOut;
  42369. /* Default to MA_CHANNEL_INDEX_NULL so that if a mapping is not found it'll be set appropriately. */
  42370. pShuffleTable[iChannelOut] = MA_CHANNEL_INDEX_NULL;
  42371. channelOut = ma_channel_map_get_channel(pChannelMapOut, channelCountOut, iChannelOut);
  42372. for (iChannelIn = 0; iChannelIn < channelCountIn; iChannelIn += 1) {
  42373. ma_channel channelIn;
  42374. channelIn = ma_channel_map_get_channel(pChannelMapIn, channelCountIn, iChannelIn);
  42375. if (channelOut == channelIn) {
  42376. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  42377. break;
  42378. }
  42379. /*
  42380. Getting here means the channels don't exactly match, but we are going to support some
  42381. relaxed matching for practicality. If, for example, there are two stereo channel maps,
  42382. but one uses front left/right and the other uses side left/right, it makes logical
  42383. sense to just map these. The way we'll do it is we'll check if there is a logical
  42384. corresponding mapping, and if so, apply it, but we will *not* break from the loop,
  42385. thereby giving the loop a chance to find an exact match later which will take priority.
  42386. */
  42387. switch (channelOut)
  42388. {
  42389. /* Left channels. */
  42390. case MA_CHANNEL_FRONT_LEFT:
  42391. case MA_CHANNEL_SIDE_LEFT:
  42392. {
  42393. switch (channelIn) {
  42394. case MA_CHANNEL_FRONT_LEFT:
  42395. case MA_CHANNEL_SIDE_LEFT:
  42396. {
  42397. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  42398. } break;
  42399. }
  42400. } break;
  42401. /* Right channels. */
  42402. case MA_CHANNEL_FRONT_RIGHT:
  42403. case MA_CHANNEL_SIDE_RIGHT:
  42404. {
  42405. switch (channelIn) {
  42406. case MA_CHANNEL_FRONT_RIGHT:
  42407. case MA_CHANNEL_SIDE_RIGHT:
  42408. {
  42409. pShuffleTable[iChannelOut] = (ma_uint8)iChannelIn;
  42410. } break;
  42411. }
  42412. } break;
  42413. default: break;
  42414. }
  42415. }
  42416. }
  42417. return MA_SUCCESS;
  42418. }
  42419. 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)
  42420. {
  42421. ma_uint64 iFrame;
  42422. ma_uint32 iChannelOut;
  42423. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42424. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42425. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  42426. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  42427. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  42428. } else {
  42429. pFramesOut[iChannelOut] = 0;
  42430. }
  42431. }
  42432. pFramesOut += channelsOut;
  42433. pFramesIn += channelsIn;
  42434. }
  42435. }
  42436. 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)
  42437. {
  42438. ma_uint64 iFrame;
  42439. ma_uint32 iChannelOut;
  42440. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42441. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42442. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  42443. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  42444. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  42445. } else {
  42446. pFramesOut[iChannelOut] = 0;
  42447. }
  42448. }
  42449. pFramesOut += channelsOut;
  42450. pFramesIn += channelsIn;
  42451. }
  42452. }
  42453. 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)
  42454. {
  42455. ma_uint64 iFrame;
  42456. ma_uint32 iChannelOut;
  42457. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42458. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42459. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  42460. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  42461. pFramesOut[iChannelOut*3 + 0] = pFramesIn[iChannelIn*3 + 0];
  42462. pFramesOut[iChannelOut*3 + 1] = pFramesIn[iChannelIn*3 + 1];
  42463. pFramesOut[iChannelOut*3 + 2] = pFramesIn[iChannelIn*3 + 2];
  42464. } else {
  42465. pFramesOut[iChannelOut*3 + 0] = 0;
  42466. } pFramesOut[iChannelOut*3 + 1] = 0;
  42467. } pFramesOut[iChannelOut*3 + 2] = 0;
  42468. pFramesOut += channelsOut*3;
  42469. pFramesIn += channelsIn*3;
  42470. }
  42471. }
  42472. 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)
  42473. {
  42474. ma_uint64 iFrame;
  42475. ma_uint32 iChannelOut;
  42476. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42477. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42478. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  42479. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  42480. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  42481. } else {
  42482. pFramesOut[iChannelOut] = 0;
  42483. }
  42484. }
  42485. pFramesOut += channelsOut;
  42486. pFramesIn += channelsIn;
  42487. }
  42488. }
  42489. 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)
  42490. {
  42491. ma_uint64 iFrame;
  42492. ma_uint32 iChannelOut;
  42493. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42494. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42495. ma_uint8 iChannelIn = pShuffleTable[iChannelOut];
  42496. if (iChannelIn < channelsIn) { /* For safety, and to deal with MA_CHANNEL_INDEX_NULL. */
  42497. pFramesOut[iChannelOut] = pFramesIn[iChannelIn];
  42498. } else {
  42499. pFramesOut[iChannelOut] = 0;
  42500. }
  42501. }
  42502. pFramesOut += channelsOut;
  42503. pFramesIn += channelsIn;
  42504. }
  42505. }
  42506. 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)
  42507. {
  42508. if (pFramesOut == NULL || pFramesIn == NULL || channelsOut == 0 || pShuffleTable == NULL) {
  42509. return MA_INVALID_ARGS;
  42510. }
  42511. switch (format)
  42512. {
  42513. case ma_format_u8:
  42514. {
  42515. ma_channel_map_apply_shuffle_table_u8((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  42516. } break;
  42517. case ma_format_s16:
  42518. {
  42519. ma_channel_map_apply_shuffle_table_s16((ma_int16*)pFramesOut, channelsOut, (const ma_int16*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  42520. } break;
  42521. case ma_format_s24:
  42522. {
  42523. ma_channel_map_apply_shuffle_table_s24((ma_uint8*)pFramesOut, channelsOut, (const ma_uint8*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  42524. } break;
  42525. case ma_format_s32:
  42526. {
  42527. ma_channel_map_apply_shuffle_table_s32((ma_int32*)pFramesOut, channelsOut, (const ma_int32*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  42528. } break;
  42529. case ma_format_f32:
  42530. {
  42531. ma_channel_map_apply_shuffle_table_f32((float*)pFramesOut, channelsOut, (const float*)pFramesIn, channelsIn, frameCount, pShuffleTable);
  42532. } break;
  42533. default: return MA_INVALID_ARGS; /* Unknown format. */
  42534. }
  42535. return MA_SUCCESS;
  42536. }
  42537. 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)
  42538. {
  42539. ma_uint64 iFrame;
  42540. ma_uint32 iChannelIn;
  42541. ma_uint32 accumulationCount;
  42542. if (pFramesOut == NULL || pFramesIn == NULL || channelsIn == 0) {
  42543. return MA_INVALID_ARGS;
  42544. }
  42545. /* In this case the output stream needs to be the average of all channels, ignoring NONE. */
  42546. /* A quick pre-processing step to get the accumulation counter since we're ignoring NONE channels. */
  42547. accumulationCount = 0;
  42548. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  42549. if (ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn) != MA_CHANNEL_NONE) {
  42550. accumulationCount += 1;
  42551. }
  42552. }
  42553. if (accumulationCount > 0) { /* <-- Prevent a division by zero. */
  42554. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42555. float accumulation = 0;
  42556. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  42557. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  42558. if (channelIn != MA_CHANNEL_NONE) {
  42559. accumulation += pFramesIn[iChannelIn];
  42560. }
  42561. }
  42562. pFramesOut[0] = accumulation / accumulationCount;
  42563. pFramesOut += 1;
  42564. pFramesIn += channelsIn;
  42565. }
  42566. } else {
  42567. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, 1);
  42568. }
  42569. return MA_SUCCESS;
  42570. }
  42571. static ma_result ma_channel_map_apply_mono_in_f32(float* pFramesOut, const ma_channel* pChannelMapOut, ma_uint32 channelsOut, const float* pFramesIn, ma_uint64 frameCount, ma_mono_expansion_mode monoExpansionMode)
  42572. {
  42573. ma_uint64 iFrame;
  42574. ma_uint32 iChannelOut;
  42575. if (pFramesOut == NULL || channelsOut == 0 || pFramesIn == NULL) {
  42576. return MA_INVALID_ARGS;
  42577. }
  42578. /* Note that the MA_CHANNEL_NONE channel must be ignored in all cases. */
  42579. switch (monoExpansionMode)
  42580. {
  42581. case ma_mono_expansion_mode_average:
  42582. {
  42583. float weight;
  42584. ma_uint32 validChannelCount = 0;
  42585. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42586. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42587. if (channelOut != MA_CHANNEL_NONE) {
  42588. validChannelCount += 1;
  42589. }
  42590. }
  42591. weight = 1.0f / validChannelCount;
  42592. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42593. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42594. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42595. if (channelOut != MA_CHANNEL_NONE) {
  42596. pFramesOut[iChannelOut] = pFramesIn[0] * weight;
  42597. }
  42598. }
  42599. pFramesOut += channelsOut;
  42600. pFramesIn += 1;
  42601. }
  42602. } break;
  42603. case ma_mono_expansion_mode_stereo_only:
  42604. {
  42605. if (channelsOut >= 2) {
  42606. ma_uint32 iChannelLeft = (ma_uint32)-1;
  42607. ma_uint32 iChannelRight = (ma_uint32)-1;
  42608. /*
  42609. We first need to find our stereo channels. We prefer front-left and front-right, but
  42610. if they're not available, we'll also try side-left and side-right. If neither are
  42611. available we'll fall through to the default case below.
  42612. */
  42613. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42614. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42615. if (channelOut == MA_CHANNEL_SIDE_LEFT) {
  42616. iChannelLeft = iChannelOut;
  42617. }
  42618. if (channelOut == MA_CHANNEL_SIDE_RIGHT) {
  42619. iChannelRight = iChannelOut;
  42620. }
  42621. }
  42622. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42623. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42624. if (channelOut == MA_CHANNEL_FRONT_LEFT) {
  42625. iChannelLeft = iChannelOut;
  42626. }
  42627. if (channelOut == MA_CHANNEL_FRONT_RIGHT) {
  42628. iChannelRight = iChannelOut;
  42629. }
  42630. }
  42631. if (iChannelLeft != (ma_uint32)-1 && iChannelRight != (ma_uint32)-1) {
  42632. /* We found our stereo channels so we can duplicate the signal across those channels. */
  42633. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42634. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42635. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42636. if (channelOut != MA_CHANNEL_NONE) {
  42637. if (iChannelOut == iChannelLeft || iChannelOut == iChannelRight) {
  42638. pFramesOut[iChannelOut] = pFramesIn[0];
  42639. } else {
  42640. pFramesOut[iChannelOut] = 0.0f;
  42641. }
  42642. }
  42643. }
  42644. pFramesOut += channelsOut;
  42645. pFramesIn += 1;
  42646. }
  42647. break; /* Get out of the switch. */
  42648. } else {
  42649. /* Fallthrough. Does not have left and right channels. */
  42650. goto default_handler;
  42651. }
  42652. } else {
  42653. /* Fallthrough. Does not have stereo channels. */
  42654. goto default_handler;
  42655. }
  42656. }; /* Fallthrough. See comments above. */
  42657. case ma_mono_expansion_mode_duplicate:
  42658. default:
  42659. {
  42660. default_handler:
  42661. {
  42662. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42663. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42664. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42665. if (channelOut != MA_CHANNEL_NONE) {
  42666. pFramesOut[iChannelOut] = pFramesIn[0];
  42667. }
  42668. }
  42669. pFramesOut += channelsOut;
  42670. pFramesIn += 1;
  42671. }
  42672. }
  42673. } break;
  42674. }
  42675. return MA_SUCCESS;
  42676. }
  42677. 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)
  42678. {
  42679. ma_channel_conversion_path conversionPath = ma_channel_map_get_conversion_path(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, mode);
  42680. /* Optimized Path: Passthrough */
  42681. if (conversionPath == ma_channel_conversion_path_passthrough) {
  42682. ma_copy_pcm_frames(pFramesOut, pFramesIn, frameCount, ma_format_f32, channelsOut);
  42683. return;
  42684. }
  42685. /* Special Path: Mono Output. */
  42686. if (conversionPath == ma_channel_conversion_path_mono_out) {
  42687. ma_channel_map_apply_mono_out_f32(pFramesOut, pFramesIn, pChannelMapIn, channelsIn, frameCount);
  42688. return;
  42689. }
  42690. /* Special Path: Mono Input. */
  42691. if (conversionPath == ma_channel_conversion_path_mono_in) {
  42692. ma_channel_map_apply_mono_in_f32(pFramesOut, pChannelMapOut, channelsOut, pFramesIn, frameCount, monoExpansionMode);
  42693. return;
  42694. }
  42695. /* Getting here means we aren't running on an optimized conversion path. */
  42696. if (channelsOut <= MA_MAX_CHANNELS) {
  42697. ma_result result;
  42698. if (mode == ma_channel_mix_mode_simple) {
  42699. ma_channel shuffleTable[MA_MAX_CHANNELS];
  42700. result = ma_channel_map_build_shuffle_table(pChannelMapIn, channelsIn, pChannelMapOut, channelsOut, shuffleTable);
  42701. if (result != MA_SUCCESS) {
  42702. return;
  42703. }
  42704. result = ma_channel_map_apply_shuffle_table(pFramesOut, channelsOut, pFramesIn, channelsIn, frameCount, shuffleTable, ma_format_f32);
  42705. if (result != MA_SUCCESS) {
  42706. return;
  42707. }
  42708. } else {
  42709. ma_uint32 iFrame;
  42710. ma_uint32 iChannelOut;
  42711. ma_uint32 iChannelIn;
  42712. float weights[32][32]; /* Do not use MA_MAX_CHANNELS here! */
  42713. /*
  42714. If we have a small enough number of channels, pre-compute the weights. Otherwise we'll just need to
  42715. fall back to a slower path because otherwise we'll run out of stack space.
  42716. */
  42717. if (channelsIn <= ma_countof(weights) && channelsOut <= ma_countof(weights)) {
  42718. /* Pre-compute weights. */
  42719. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42720. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42721. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  42722. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  42723. weights[iChannelOut][iChannelIn] = ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  42724. }
  42725. }
  42726. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42727. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42728. float accumulation = 0;
  42729. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  42730. accumulation += pFramesIn[iChannelIn] * weights[iChannelOut][iChannelIn];
  42731. }
  42732. pFramesOut[iChannelOut] = accumulation;
  42733. }
  42734. pFramesOut += channelsOut;
  42735. pFramesIn += channelsIn;
  42736. }
  42737. } else {
  42738. /* Cannot pre-compute weights because not enough room in stack-allocated buffer. */
  42739. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  42740. for (iChannelOut = 0; iChannelOut < channelsOut; iChannelOut += 1) {
  42741. float accumulation = 0;
  42742. ma_channel channelOut = ma_channel_map_get_channel(pChannelMapOut, channelsOut, iChannelOut);
  42743. for (iChannelIn = 0; iChannelIn < channelsIn; iChannelIn += 1) {
  42744. ma_channel channelIn = ma_channel_map_get_channel(pChannelMapIn, channelsIn, iChannelIn);
  42745. accumulation += pFramesIn[iChannelIn] * ma_calculate_channel_position_rectangular_weight(channelOut, channelIn);
  42746. }
  42747. pFramesOut[iChannelOut] = accumulation;
  42748. }
  42749. pFramesOut += channelsOut;
  42750. pFramesIn += channelsIn;
  42751. }
  42752. }
  42753. }
  42754. } else {
  42755. /* Fall back to silence. If you hit this, what are you doing with so many channels?! */
  42756. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, channelsOut);
  42757. }
  42758. }
  42759. typedef struct
  42760. {
  42761. size_t sizeInBytes;
  42762. size_t channelMapInOffset;
  42763. size_t channelMapOutOffset;
  42764. size_t shuffleTableOffset;
  42765. size_t weightsOffset;
  42766. } ma_channel_converter_heap_layout;
  42767. static ma_channel_conversion_path ma_channel_converter_config_get_conversion_path(const ma_channel_converter_config* pConfig)
  42768. {
  42769. return ma_channel_map_get_conversion_path(pConfig->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapOut, pConfig->channelsOut, pConfig->mixingMode);
  42770. }
  42771. static ma_result ma_channel_converter_get_heap_layout(const ma_channel_converter_config* pConfig, ma_channel_converter_heap_layout* pHeapLayout)
  42772. {
  42773. ma_channel_conversion_path conversionPath;
  42774. MA_ASSERT(pHeapLayout != NULL);
  42775. if (pConfig == NULL) {
  42776. return MA_INVALID_ARGS;
  42777. }
  42778. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  42779. return MA_INVALID_ARGS;
  42780. }
  42781. if (!ma_channel_map_is_valid(pConfig->pChannelMapIn, pConfig->channelsIn)) {
  42782. return MA_INVALID_ARGS;
  42783. }
  42784. if (!ma_channel_map_is_valid(pConfig->pChannelMapOut, pConfig->channelsOut)) {
  42785. return MA_INVALID_ARGS;
  42786. }
  42787. pHeapLayout->sizeInBytes = 0;
  42788. /* Input channel map. Only need to allocate this if we have an input channel map (otherwise default channel map is assumed). */
  42789. pHeapLayout->channelMapInOffset = pHeapLayout->sizeInBytes;
  42790. if (pConfig->pChannelMapIn != NULL) {
  42791. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsIn;
  42792. }
  42793. /* Output channel map. Only need to allocate this if we have an output channel map (otherwise default channel map is assumed). */
  42794. pHeapLayout->channelMapOutOffset = pHeapLayout->sizeInBytes;
  42795. if (pConfig->pChannelMapOut != NULL) {
  42796. pHeapLayout->sizeInBytes += sizeof(ma_channel) * pConfig->channelsOut;
  42797. }
  42798. /* Alignment for the next section. */
  42799. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  42800. /* Whether or not we use weights of a shuffle table depends on the channel map themselves and the algorithm we've chosen. */
  42801. conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  42802. /* Shuffle table */
  42803. pHeapLayout->shuffleTableOffset = pHeapLayout->sizeInBytes;
  42804. if (conversionPath == ma_channel_conversion_path_shuffle) {
  42805. pHeapLayout->sizeInBytes += sizeof(ma_uint8) * pConfig->channelsOut;
  42806. }
  42807. /* Weights */
  42808. pHeapLayout->weightsOffset = pHeapLayout->sizeInBytes;
  42809. if (conversionPath == ma_channel_conversion_path_weights) {
  42810. pHeapLayout->sizeInBytes += sizeof(float*) * pConfig->channelsIn;
  42811. pHeapLayout->sizeInBytes += sizeof(float ) * pConfig->channelsIn * pConfig->channelsOut;
  42812. }
  42813. /* Make sure allocation size is aligned. */
  42814. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  42815. return MA_SUCCESS;
  42816. }
  42817. MA_API ma_result ma_channel_converter_get_heap_size(const ma_channel_converter_config* pConfig, size_t* pHeapSizeInBytes)
  42818. {
  42819. ma_result result;
  42820. ma_channel_converter_heap_layout heapLayout;
  42821. if (pHeapSizeInBytes == NULL) {
  42822. return MA_INVALID_ARGS;
  42823. }
  42824. *pHeapSizeInBytes = 0;
  42825. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  42826. if (result != MA_SUCCESS) {
  42827. return result;
  42828. }
  42829. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  42830. return MA_SUCCESS;
  42831. }
  42832. MA_API ma_result ma_channel_converter_init_preallocated(const ma_channel_converter_config* pConfig, void* pHeap, ma_channel_converter* pConverter)
  42833. {
  42834. ma_result result;
  42835. ma_channel_converter_heap_layout heapLayout;
  42836. if (pConverter == NULL) {
  42837. return MA_INVALID_ARGS;
  42838. }
  42839. MA_ZERO_OBJECT(pConverter);
  42840. result = ma_channel_converter_get_heap_layout(pConfig, &heapLayout);
  42841. if (result != MA_SUCCESS) {
  42842. return result;
  42843. }
  42844. pConverter->_pHeap = pHeap;
  42845. MA_ZERO_MEMORY(pConverter->_pHeap, heapLayout.sizeInBytes);
  42846. pConverter->format = pConfig->format;
  42847. pConverter->channelsIn = pConfig->channelsIn;
  42848. pConverter->channelsOut = pConfig->channelsOut;
  42849. pConverter->mixingMode = pConfig->mixingMode;
  42850. if (pConfig->pChannelMapIn != NULL) {
  42851. pConverter->pChannelMapIn = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapInOffset);
  42852. ma_channel_map_copy_or_default(pConverter->pChannelMapIn, pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsIn);
  42853. } else {
  42854. pConverter->pChannelMapIn = NULL; /* Use default channel map. */
  42855. }
  42856. if (pConfig->pChannelMapOut != NULL) {
  42857. pConverter->pChannelMapOut = (ma_channel*)ma_offset_ptr(pHeap, heapLayout.channelMapOutOffset);
  42858. ma_channel_map_copy_or_default(pConverter->pChannelMapOut, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelsOut);
  42859. } else {
  42860. pConverter->pChannelMapOut = NULL; /* Use default channel map. */
  42861. }
  42862. pConverter->conversionPath = ma_channel_converter_config_get_conversion_path(pConfig);
  42863. if (pConverter->conversionPath == ma_channel_conversion_path_shuffle) {
  42864. pConverter->pShuffleTable = (ma_uint8*)ma_offset_ptr(pHeap, heapLayout.shuffleTableOffset);
  42865. ma_channel_map_build_shuffle_table(pConverter->pChannelMapIn, pConverter->channelsIn, pConverter->pChannelMapOut, pConverter->channelsOut, pConverter->pShuffleTable);
  42866. }
  42867. if (pConverter->conversionPath == ma_channel_conversion_path_weights) {
  42868. ma_uint32 iChannelIn;
  42869. ma_uint32 iChannelOut;
  42870. if (pConverter->format == ma_format_f32) {
  42871. pConverter->weights.f32 = (float** )ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  42872. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  42873. pConverter->weights.f32[iChannelIn] = (float*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(float*) * pConverter->channelsIn) + (sizeof(float) * pConverter->channelsOut * iChannelIn)));
  42874. }
  42875. } else {
  42876. pConverter->weights.s16 = (ma_int32**)ma_offset_ptr(pHeap, heapLayout.weightsOffset);
  42877. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  42878. pConverter->weights.s16[iChannelIn] = (ma_int32*)ma_offset_ptr(pHeap, heapLayout.weightsOffset + ((sizeof(ma_int32*) * pConverter->channelsIn) + (sizeof(ma_int32) * pConverter->channelsOut * iChannelIn)));
  42879. }
  42880. }
  42881. /* Silence our weights by default. */
  42882. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  42883. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  42884. if (pConverter->format == ma_format_f32) {
  42885. pConverter->weights.f32[iChannelIn][iChannelOut] = 0.0f;
  42886. } else {
  42887. pConverter->weights.s16[iChannelIn][iChannelOut] = 0;
  42888. }
  42889. }
  42890. }
  42891. /*
  42892. We now need to fill out our weights table. This is determined by the mixing mode.
  42893. */
  42894. /* In all cases we need to make sure all channels that are present in both channel maps have a 1:1 mapping. */
  42895. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  42896. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  42897. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  42898. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  42899. if (channelPosIn == channelPosOut) {
  42900. float weight = 1;
  42901. if (pConverter->format == ma_format_f32) {
  42902. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  42903. } else {
  42904. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  42905. }
  42906. }
  42907. }
  42908. }
  42909. switch (pConverter->mixingMode)
  42910. {
  42911. case ma_channel_mix_mode_custom_weights:
  42912. {
  42913. if (pConfig->ppWeights == NULL) {
  42914. return MA_INVALID_ARGS; /* Config specified a custom weights mixing mode, but no custom weights have been specified. */
  42915. }
  42916. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; iChannelIn += 1) {
  42917. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; iChannelOut += 1) {
  42918. float weight = pConfig->ppWeights[iChannelIn][iChannelOut];
  42919. if (pConverter->format == ma_format_f32) {
  42920. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  42921. } else {
  42922. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  42923. }
  42924. }
  42925. }
  42926. } break;
  42927. case ma_channel_mix_mode_simple:
  42928. {
  42929. /*
  42930. In simple mode, only set weights for channels that have exactly matching types, leave the rest at
  42931. zero. The 1:1 mappings have already been covered before this switch statement.
  42932. */
  42933. } break;
  42934. case ma_channel_mix_mode_rectangular:
  42935. default:
  42936. {
  42937. /* Unmapped input channels. */
  42938. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  42939. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  42940. if (ma_is_spatial_channel_position(channelPosIn)) {
  42941. if (!ma_channel_map_contains_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, channelPosIn)) {
  42942. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  42943. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  42944. if (ma_is_spatial_channel_position(channelPosOut)) {
  42945. float weight = 0;
  42946. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  42947. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  42948. }
  42949. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  42950. if (pConverter->format == ma_format_f32) {
  42951. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  42952. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  42953. }
  42954. } else {
  42955. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  42956. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  42957. }
  42958. }
  42959. }
  42960. }
  42961. }
  42962. }
  42963. }
  42964. /* Unmapped output channels. */
  42965. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  42966. ma_channel channelPosOut = ma_channel_map_get_channel(pConverter->pChannelMapOut, pConverter->channelsOut, iChannelOut);
  42967. if (ma_is_spatial_channel_position(channelPosOut)) {
  42968. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, channelPosOut)) {
  42969. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  42970. ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  42971. if (ma_is_spatial_channel_position(channelPosIn)) {
  42972. float weight = 0;
  42973. if (pConverter->mixingMode == ma_channel_mix_mode_rectangular) {
  42974. weight = ma_calculate_channel_position_rectangular_weight(channelPosIn, channelPosOut);
  42975. }
  42976. /* Only apply the weight if we haven't already got some contribution from the respective channels. */
  42977. if (pConverter->format == ma_format_f32) {
  42978. if (pConverter->weights.f32[iChannelIn][iChannelOut] == 0) {
  42979. pConverter->weights.f32[iChannelIn][iChannelOut] = weight;
  42980. }
  42981. } else {
  42982. if (pConverter->weights.s16[iChannelIn][iChannelOut] == 0) {
  42983. pConverter->weights.s16[iChannelIn][iChannelOut] = ma_channel_converter_float_to_fixed(weight);
  42984. }
  42985. }
  42986. }
  42987. }
  42988. }
  42989. }
  42990. }
  42991. /* If LFE is in the output channel map but was not present in the input channel map, configure its weight now */
  42992. if (pConfig->calculateLFEFromSpatialChannels) {
  42993. if (!ma_channel_map_contains_channel_position(pConverter->channelsIn, pConverter->pChannelMapIn, MA_CHANNEL_LFE)) {
  42994. ma_uint32 spatialChannelCount = ma_channel_map_get_spatial_channel_count(pConverter->pChannelMapIn, pConverter->channelsIn);
  42995. ma_uint32 iChannelOutLFE;
  42996. if (spatialChannelCount > 0 && ma_channel_map_find_channel_position(pConverter->channelsOut, pConverter->pChannelMapOut, MA_CHANNEL_LFE, &iChannelOutLFE)) {
  42997. const float weightForLFE = 1.0f / spatialChannelCount;
  42998. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  42999. const ma_channel channelPosIn = ma_channel_map_get_channel(pConverter->pChannelMapIn, pConverter->channelsIn, iChannelIn);
  43000. if (ma_is_spatial_channel_position(channelPosIn)) {
  43001. if (pConverter->format == ma_format_f32) {
  43002. if (pConverter->weights.f32[iChannelIn][iChannelOutLFE] == 0) {
  43003. pConverter->weights.f32[iChannelIn][iChannelOutLFE] = weightForLFE;
  43004. }
  43005. } else {
  43006. if (pConverter->weights.s16[iChannelIn][iChannelOutLFE] == 0) {
  43007. pConverter->weights.s16[iChannelIn][iChannelOutLFE] = ma_channel_converter_float_to_fixed(weightForLFE);
  43008. }
  43009. }
  43010. }
  43011. }
  43012. }
  43013. }
  43014. }
  43015. } break;
  43016. }
  43017. }
  43018. return MA_SUCCESS;
  43019. }
  43020. MA_API ma_result ma_channel_converter_init(const ma_channel_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_channel_converter* pConverter)
  43021. {
  43022. ma_result result;
  43023. size_t heapSizeInBytes;
  43024. void* pHeap;
  43025. result = ma_channel_converter_get_heap_size(pConfig, &heapSizeInBytes);
  43026. if (result != MA_SUCCESS) {
  43027. return result;
  43028. }
  43029. if (heapSizeInBytes > 0) {
  43030. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  43031. if (pHeap == NULL) {
  43032. return MA_OUT_OF_MEMORY;
  43033. }
  43034. } else {
  43035. pHeap = NULL;
  43036. }
  43037. result = ma_channel_converter_init_preallocated(pConfig, pHeap, pConverter);
  43038. if (result != MA_SUCCESS) {
  43039. ma_free(pHeap, pAllocationCallbacks);
  43040. return result;
  43041. }
  43042. pConverter->_ownsHeap = MA_TRUE;
  43043. return MA_SUCCESS;
  43044. }
  43045. MA_API void ma_channel_converter_uninit(ma_channel_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  43046. {
  43047. if (pConverter == NULL) {
  43048. return;
  43049. }
  43050. if (pConverter->_ownsHeap) {
  43051. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  43052. }
  43053. }
  43054. static ma_result ma_channel_converter_process_pcm_frames__passthrough(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43055. {
  43056. MA_ASSERT(pConverter != NULL);
  43057. MA_ASSERT(pFramesOut != NULL);
  43058. MA_ASSERT(pFramesIn != NULL);
  43059. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  43060. return MA_SUCCESS;
  43061. }
  43062. static ma_result ma_channel_converter_process_pcm_frames__shuffle(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43063. {
  43064. MA_ASSERT(pConverter != NULL);
  43065. MA_ASSERT(pFramesOut != NULL);
  43066. MA_ASSERT(pFramesIn != NULL);
  43067. MA_ASSERT(pConverter->channelsIn == pConverter->channelsOut);
  43068. return ma_channel_map_apply_shuffle_table(pFramesOut, pConverter->channelsOut, pFramesIn, pConverter->channelsIn, frameCount, pConverter->pShuffleTable, pConverter->format);
  43069. }
  43070. static ma_result ma_channel_converter_process_pcm_frames__mono_in(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43071. {
  43072. ma_uint64 iFrame;
  43073. MA_ASSERT(pConverter != NULL);
  43074. MA_ASSERT(pFramesOut != NULL);
  43075. MA_ASSERT(pFramesIn != NULL);
  43076. MA_ASSERT(pConverter->channelsIn == 1);
  43077. switch (pConverter->format)
  43078. {
  43079. case ma_format_u8:
  43080. {
  43081. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  43082. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  43083. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43084. ma_uint32 iChannel;
  43085. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  43086. pFramesOutU8[iFrame*pConverter->channelsOut + iChannel] = pFramesInU8[iFrame];
  43087. }
  43088. }
  43089. } break;
  43090. case ma_format_s16:
  43091. {
  43092. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  43093. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  43094. if (pConverter->channelsOut == 2) {
  43095. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43096. pFramesOutS16[iFrame*2 + 0] = pFramesInS16[iFrame];
  43097. pFramesOutS16[iFrame*2 + 1] = pFramesInS16[iFrame];
  43098. }
  43099. } else {
  43100. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43101. ma_uint32 iChannel;
  43102. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  43103. pFramesOutS16[iFrame*pConverter->channelsOut + iChannel] = pFramesInS16[iFrame];
  43104. }
  43105. }
  43106. }
  43107. } break;
  43108. case ma_format_s24:
  43109. {
  43110. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  43111. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  43112. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43113. ma_uint32 iChannel;
  43114. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  43115. ma_uint64 iSampleOut = iFrame*pConverter->channelsOut + iChannel;
  43116. ma_uint64 iSampleIn = iFrame;
  43117. pFramesOutS24[iSampleOut*3 + 0] = pFramesInS24[iSampleIn*3 + 0];
  43118. pFramesOutS24[iSampleOut*3 + 1] = pFramesInS24[iSampleIn*3 + 1];
  43119. pFramesOutS24[iSampleOut*3 + 2] = pFramesInS24[iSampleIn*3 + 2];
  43120. }
  43121. }
  43122. } break;
  43123. case ma_format_s32:
  43124. {
  43125. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  43126. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  43127. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43128. ma_uint32 iChannel;
  43129. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  43130. pFramesOutS32[iFrame*pConverter->channelsOut + iChannel] = pFramesInS32[iFrame];
  43131. }
  43132. }
  43133. } break;
  43134. case ma_format_f32:
  43135. {
  43136. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  43137. const float* pFramesInF32 = (const float*)pFramesIn;
  43138. if (pConverter->channelsOut == 2) {
  43139. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43140. pFramesOutF32[iFrame*2 + 0] = pFramesInF32[iFrame];
  43141. pFramesOutF32[iFrame*2 + 1] = pFramesInF32[iFrame];
  43142. }
  43143. } else {
  43144. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43145. ma_uint32 iChannel;
  43146. for (iChannel = 0; iChannel < pConverter->channelsOut; iChannel += 1) {
  43147. pFramesOutF32[iFrame*pConverter->channelsOut + iChannel] = pFramesInF32[iFrame];
  43148. }
  43149. }
  43150. }
  43151. } break;
  43152. default: return MA_INVALID_OPERATION; /* Unknown format. */
  43153. }
  43154. return MA_SUCCESS;
  43155. }
  43156. static ma_result ma_channel_converter_process_pcm_frames__mono_out(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43157. {
  43158. ma_uint64 iFrame;
  43159. ma_uint32 iChannel;
  43160. MA_ASSERT(pConverter != NULL);
  43161. MA_ASSERT(pFramesOut != NULL);
  43162. MA_ASSERT(pFramesIn != NULL);
  43163. MA_ASSERT(pConverter->channelsOut == 1);
  43164. switch (pConverter->format)
  43165. {
  43166. case ma_format_u8:
  43167. {
  43168. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  43169. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  43170. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43171. ma_int32 t = 0;
  43172. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  43173. t += ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8[iFrame*pConverter->channelsIn + iChannel]);
  43174. }
  43175. pFramesOutU8[iFrame] = ma_clip_u8(t / pConverter->channelsOut);
  43176. }
  43177. } break;
  43178. case ma_format_s16:
  43179. {
  43180. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  43181. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  43182. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43183. ma_int32 t = 0;
  43184. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  43185. t += pFramesInS16[iFrame*pConverter->channelsIn + iChannel];
  43186. }
  43187. pFramesOutS16[iFrame] = (ma_int16)(t / pConverter->channelsIn);
  43188. }
  43189. } break;
  43190. case ma_format_s24:
  43191. {
  43192. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  43193. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  43194. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43195. ma_int64 t = 0;
  43196. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  43197. t += ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24[(iFrame*pConverter->channelsIn + iChannel)*3]);
  43198. }
  43199. ma_pcm_sample_s32_to_s24_no_scale(t / pConverter->channelsIn, &pFramesOutS24[iFrame*3]);
  43200. }
  43201. } break;
  43202. case ma_format_s32:
  43203. {
  43204. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  43205. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  43206. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43207. ma_int64 t = 0;
  43208. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  43209. t += pFramesInS32[iFrame*pConverter->channelsIn + iChannel];
  43210. }
  43211. pFramesOutS32[iFrame] = (ma_int32)(t / pConverter->channelsIn);
  43212. }
  43213. } break;
  43214. case ma_format_f32:
  43215. {
  43216. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  43217. const float* pFramesInF32 = (const float*)pFramesIn;
  43218. for (iFrame = 0; iFrame < frameCount; ++iFrame) {
  43219. float t = 0;
  43220. for (iChannel = 0; iChannel < pConverter->channelsIn; iChannel += 1) {
  43221. t += pFramesInF32[iFrame*pConverter->channelsIn + iChannel];
  43222. }
  43223. pFramesOutF32[iFrame] = t / pConverter->channelsIn;
  43224. }
  43225. } break;
  43226. default: return MA_INVALID_OPERATION; /* Unknown format. */
  43227. }
  43228. return MA_SUCCESS;
  43229. }
  43230. static ma_result ma_channel_converter_process_pcm_frames__weights(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43231. {
  43232. ma_uint32 iFrame;
  43233. ma_uint32 iChannelIn;
  43234. ma_uint32 iChannelOut;
  43235. MA_ASSERT(pConverter != NULL);
  43236. MA_ASSERT(pFramesOut != NULL);
  43237. MA_ASSERT(pFramesIn != NULL);
  43238. /* This is the more complicated case. Each of the output channels is accumulated with 0 or more input channels. */
  43239. /* Clear. */
  43240. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  43241. /* Accumulate. */
  43242. switch (pConverter->format)
  43243. {
  43244. case ma_format_u8:
  43245. {
  43246. /* */ ma_uint8* pFramesOutU8 = ( ma_uint8*)pFramesOut;
  43247. const ma_uint8* pFramesInU8 = (const ma_uint8*)pFramesIn;
  43248. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43249. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  43250. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  43251. ma_int16 u8_O = ma_pcm_sample_u8_to_s16_no_scale(pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut]);
  43252. ma_int16 u8_I = ma_pcm_sample_u8_to_s16_no_scale(pFramesInU8 [iFrame*pConverter->channelsIn + iChannelIn ]);
  43253. ma_int32 s = (ma_int32)ma_clamp(u8_O + ((u8_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -128, 127);
  43254. pFramesOutU8[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_u8((ma_int16)s);
  43255. }
  43256. }
  43257. }
  43258. } break;
  43259. case ma_format_s16:
  43260. {
  43261. /* */ ma_int16* pFramesOutS16 = ( ma_int16*)pFramesOut;
  43262. const ma_int16* pFramesInS16 = (const ma_int16*)pFramesIn;
  43263. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43264. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  43265. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  43266. ma_int32 s = pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut];
  43267. s += (pFramesInS16[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  43268. pFramesOutS16[iFrame*pConverter->channelsOut + iChannelOut] = (ma_int16)ma_clamp(s, -32768, 32767);
  43269. }
  43270. }
  43271. }
  43272. } break;
  43273. case ma_format_s24:
  43274. {
  43275. /* */ ma_uint8* pFramesOutS24 = ( ma_uint8*)pFramesOut;
  43276. const ma_uint8* pFramesInS24 = (const ma_uint8*)pFramesIn;
  43277. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43278. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  43279. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  43280. ma_int64 s24_O = ma_pcm_sample_s24_to_s32_no_scale(&pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  43281. ma_int64 s24_I = ma_pcm_sample_s24_to_s32_no_scale(&pFramesInS24 [(iFrame*pConverter->channelsIn + iChannelIn )*3]);
  43282. ma_int64 s24 = (ma_int32)ma_clamp(s24_O + ((s24_I * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT), -8388608, 8388607);
  43283. ma_pcm_sample_s32_to_s24_no_scale(s24, &pFramesOutS24[(iFrame*pConverter->channelsOut + iChannelOut)*3]);
  43284. }
  43285. }
  43286. }
  43287. } break;
  43288. case ma_format_s32:
  43289. {
  43290. /* */ ma_int32* pFramesOutS32 = ( ma_int32*)pFramesOut;
  43291. const ma_int32* pFramesInS32 = (const ma_int32*)pFramesIn;
  43292. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43293. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  43294. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  43295. ma_int64 s = pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut];
  43296. s += ((ma_int64)pFramesInS32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.s16[iChannelIn][iChannelOut]) >> MA_CHANNEL_CONVERTER_FIXED_POINT_SHIFT;
  43297. pFramesOutS32[iFrame*pConverter->channelsOut + iChannelOut] = ma_clip_s32(s);
  43298. }
  43299. }
  43300. }
  43301. } break;
  43302. case ma_format_f32:
  43303. {
  43304. /* */ float* pFramesOutF32 = ( float*)pFramesOut;
  43305. const float* pFramesInF32 = (const float*)pFramesIn;
  43306. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  43307. for (iChannelIn = 0; iChannelIn < pConverter->channelsIn; ++iChannelIn) {
  43308. for (iChannelOut = 0; iChannelOut < pConverter->channelsOut; ++iChannelOut) {
  43309. pFramesOutF32[iFrame*pConverter->channelsOut + iChannelOut] += pFramesInF32[iFrame*pConverter->channelsIn + iChannelIn] * pConverter->weights.f32[iChannelIn][iChannelOut];
  43310. }
  43311. }
  43312. }
  43313. } break;
  43314. default: return MA_INVALID_OPERATION; /* Unknown format. */
  43315. }
  43316. return MA_SUCCESS;
  43317. }
  43318. MA_API ma_result ma_channel_converter_process_pcm_frames(ma_channel_converter* pConverter, void* pFramesOut, const void* pFramesIn, ma_uint64 frameCount)
  43319. {
  43320. if (pConverter == NULL) {
  43321. return MA_INVALID_ARGS;
  43322. }
  43323. if (pFramesOut == NULL) {
  43324. return MA_INVALID_ARGS;
  43325. }
  43326. if (pFramesIn == NULL) {
  43327. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->format, pConverter->channelsOut));
  43328. return MA_SUCCESS;
  43329. }
  43330. switch (pConverter->conversionPath)
  43331. {
  43332. case ma_channel_conversion_path_passthrough: return ma_channel_converter_process_pcm_frames__passthrough(pConverter, pFramesOut, pFramesIn, frameCount);
  43333. case ma_channel_conversion_path_mono_out: return ma_channel_converter_process_pcm_frames__mono_out(pConverter, pFramesOut, pFramesIn, frameCount);
  43334. case ma_channel_conversion_path_mono_in: return ma_channel_converter_process_pcm_frames__mono_in(pConverter, pFramesOut, pFramesIn, frameCount);
  43335. case ma_channel_conversion_path_shuffle: return ma_channel_converter_process_pcm_frames__shuffle(pConverter, pFramesOut, pFramesIn, frameCount);
  43336. case ma_channel_conversion_path_weights:
  43337. default:
  43338. {
  43339. return ma_channel_converter_process_pcm_frames__weights(pConverter, pFramesOut, pFramesIn, frameCount);
  43340. }
  43341. }
  43342. }
  43343. MA_API ma_result ma_channel_converter_get_input_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  43344. {
  43345. if (pConverter == NULL || pChannelMap == NULL) {
  43346. return MA_INVALID_ARGS;
  43347. }
  43348. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapIn, pConverter->channelsIn);
  43349. return MA_SUCCESS;
  43350. }
  43351. MA_API ma_result ma_channel_converter_get_output_channel_map(const ma_channel_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  43352. {
  43353. if (pConverter == NULL || pChannelMap == NULL) {
  43354. return MA_INVALID_ARGS;
  43355. }
  43356. ma_channel_map_copy_or_default(pChannelMap, channelMapCap, pConverter->pChannelMapOut, pConverter->channelsOut);
  43357. return MA_SUCCESS;
  43358. }
  43359. /**************************************************************************************************************************************************************
  43360. Data Conversion
  43361. **************************************************************************************************************************************************************/
  43362. MA_API ma_data_converter_config ma_data_converter_config_init_default()
  43363. {
  43364. ma_data_converter_config config;
  43365. MA_ZERO_OBJECT(&config);
  43366. config.ditherMode = ma_dither_mode_none;
  43367. config.resampling.algorithm = ma_resample_algorithm_linear;
  43368. 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. */
  43369. /* Linear resampling defaults. */
  43370. config.resampling.linear.lpfOrder = 1;
  43371. return config;
  43372. }
  43373. 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)
  43374. {
  43375. ma_data_converter_config config = ma_data_converter_config_init_default();
  43376. config.formatIn = formatIn;
  43377. config.formatOut = formatOut;
  43378. config.channelsIn = channelsIn;
  43379. config.channelsOut = channelsOut;
  43380. config.sampleRateIn = sampleRateIn;
  43381. config.sampleRateOut = sampleRateOut;
  43382. return config;
  43383. }
  43384. typedef struct
  43385. {
  43386. size_t sizeInBytes;
  43387. size_t channelConverterOffset;
  43388. size_t resamplerOffset;
  43389. } ma_data_converter_heap_layout;
  43390. static ma_bool32 ma_data_converter_config_is_resampler_required(const ma_data_converter_config* pConfig)
  43391. {
  43392. MA_ASSERT(pConfig != NULL);
  43393. return pConfig->allowDynamicSampleRate || pConfig->sampleRateIn != pConfig->sampleRateOut;
  43394. }
  43395. static ma_format ma_data_converter_config_get_mid_format(const ma_data_converter_config* pConfig)
  43396. {
  43397. MA_ASSERT(pConfig != NULL);
  43398. /*
  43399. We want to avoid as much data conversion as possible. The channel converter and linear
  43400. resampler both support s16 and f32 natively. We need to decide on the format to use for this
  43401. stage. We call this the mid format because it's used in the middle stage of the conversion
  43402. pipeline. If the output format is either s16 or f32 we use that one. If that is not the case it
  43403. will do the same thing for the input format. If it's neither we just use f32. If we are using a
  43404. custom resampling backend, we can only guarantee that f32 will be supported so we'll be forced
  43405. to use that if resampling is required.
  43406. */
  43407. if (ma_data_converter_config_is_resampler_required(pConfig) && pConfig->resampling.algorithm != ma_resample_algorithm_linear) {
  43408. return ma_format_f32; /* <-- Force f32 since that is the only one we can guarantee will be supported by the resampler. */
  43409. } else {
  43410. /* */ if (pConfig->formatOut == ma_format_s16 || pConfig->formatOut == ma_format_f32) {
  43411. return pConfig->formatOut;
  43412. } else if (pConfig->formatIn == ma_format_s16 || pConfig->formatIn == ma_format_f32) {
  43413. return pConfig->formatIn;
  43414. } else {
  43415. return ma_format_f32;
  43416. }
  43417. }
  43418. }
  43419. static ma_channel_converter_config ma_channel_converter_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  43420. {
  43421. ma_channel_converter_config channelConverterConfig;
  43422. MA_ASSERT(pConfig != NULL);
  43423. channelConverterConfig = ma_channel_converter_config_init(ma_data_converter_config_get_mid_format(pConfig), pConfig->channelsIn, pConfig->pChannelMapIn, pConfig->channelsOut, pConfig->pChannelMapOut, pConfig->channelMixMode);
  43424. channelConverterConfig.ppWeights = pConfig->ppChannelWeights;
  43425. channelConverterConfig.calculateLFEFromSpatialChannels = pConfig->calculateLFEFromSpatialChannels;
  43426. return channelConverterConfig;
  43427. }
  43428. static ma_resampler_config ma_resampler_config_init_from_data_converter_config(const ma_data_converter_config* pConfig)
  43429. {
  43430. ma_resampler_config resamplerConfig;
  43431. ma_uint32 resamplerChannels;
  43432. MA_ASSERT(pConfig != NULL);
  43433. /* 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. */
  43434. if (pConfig->channelsIn < pConfig->channelsOut) {
  43435. resamplerChannels = pConfig->channelsIn;
  43436. } else {
  43437. resamplerChannels = pConfig->channelsOut;
  43438. }
  43439. resamplerConfig = ma_resampler_config_init(ma_data_converter_config_get_mid_format(pConfig), resamplerChannels, pConfig->sampleRateIn, pConfig->sampleRateOut, pConfig->resampling.algorithm);
  43440. resamplerConfig.linear = pConfig->resampling.linear;
  43441. resamplerConfig.pBackendVTable = pConfig->resampling.pBackendVTable;
  43442. resamplerConfig.pBackendUserData = pConfig->resampling.pBackendUserData;
  43443. return resamplerConfig;
  43444. }
  43445. static ma_result ma_data_converter_get_heap_layout(const ma_data_converter_config* pConfig, ma_data_converter_heap_layout* pHeapLayout)
  43446. {
  43447. ma_result result;
  43448. MA_ASSERT(pHeapLayout != NULL);
  43449. MA_ZERO_OBJECT(pHeapLayout);
  43450. if (pConfig == NULL) {
  43451. return MA_INVALID_ARGS;
  43452. }
  43453. if (pConfig->channelsIn == 0 || pConfig->channelsOut == 0) {
  43454. return MA_INVALID_ARGS;
  43455. }
  43456. pHeapLayout->sizeInBytes = 0;
  43457. /* Channel converter. */
  43458. pHeapLayout->channelConverterOffset = pHeapLayout->sizeInBytes;
  43459. {
  43460. size_t heapSizeInBytes;
  43461. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  43462. result = ma_channel_converter_get_heap_size(&channelConverterConfig, &heapSizeInBytes);
  43463. if (result != MA_SUCCESS) {
  43464. return result;
  43465. }
  43466. pHeapLayout->sizeInBytes += heapSizeInBytes;
  43467. }
  43468. /* Resampler. */
  43469. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  43470. if (ma_data_converter_config_is_resampler_required(pConfig)) {
  43471. size_t heapSizeInBytes;
  43472. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  43473. result = ma_resampler_get_heap_size(&resamplerConfig, &heapSizeInBytes);
  43474. if (result != MA_SUCCESS) {
  43475. return result;
  43476. }
  43477. pHeapLayout->sizeInBytes += heapSizeInBytes;
  43478. }
  43479. /* Make sure allocation size is aligned. */
  43480. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  43481. return MA_SUCCESS;
  43482. }
  43483. MA_API ma_result ma_data_converter_get_heap_size(const ma_data_converter_config* pConfig, size_t* pHeapSizeInBytes)
  43484. {
  43485. ma_result result;
  43486. ma_data_converter_heap_layout heapLayout;
  43487. if (pHeapSizeInBytes == NULL) {
  43488. return MA_INVALID_ARGS;
  43489. }
  43490. *pHeapSizeInBytes = 0;
  43491. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  43492. if (result != MA_SUCCESS) {
  43493. return result;
  43494. }
  43495. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  43496. return MA_SUCCESS;
  43497. }
  43498. MA_API ma_result ma_data_converter_init_preallocated(const ma_data_converter_config* pConfig, void* pHeap, ma_data_converter* pConverter)
  43499. {
  43500. ma_result result;
  43501. ma_data_converter_heap_layout heapLayout;
  43502. ma_format midFormat;
  43503. ma_bool32 isResamplingRequired;
  43504. if (pConverter == NULL) {
  43505. return MA_INVALID_ARGS;
  43506. }
  43507. MA_ZERO_OBJECT(pConverter);
  43508. result = ma_data_converter_get_heap_layout(pConfig, &heapLayout);
  43509. if (result != MA_SUCCESS) {
  43510. return result;
  43511. }
  43512. pConverter->_pHeap = pHeap;
  43513. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  43514. pConverter->formatIn = pConfig->formatIn;
  43515. pConverter->formatOut = pConfig->formatOut;
  43516. pConverter->channelsIn = pConfig->channelsIn;
  43517. pConverter->channelsOut = pConfig->channelsOut;
  43518. pConverter->sampleRateIn = pConfig->sampleRateIn;
  43519. pConverter->sampleRateOut = pConfig->sampleRateOut;
  43520. pConverter->ditherMode = pConfig->ditherMode;
  43521. /*
  43522. Determine if resampling is required. We need to do this so we can determine an appropriate
  43523. mid format to use. If resampling is required, the mid format must be ma_format_f32 since
  43524. that is the only one that is guaranteed to supported by custom resampling backends.
  43525. */
  43526. isResamplingRequired = ma_data_converter_config_is_resampler_required(pConfig);
  43527. midFormat = ma_data_converter_config_get_mid_format(pConfig);
  43528. /* Channel converter. We always initialize this, but we check if it configures itself as a passthrough to determine whether or not it's needed. */
  43529. {
  43530. ma_channel_converter_config channelConverterConfig = ma_channel_converter_config_init_from_data_converter_config(pConfig);
  43531. result = ma_channel_converter_init_preallocated(&channelConverterConfig, ma_offset_ptr(pHeap, heapLayout.channelConverterOffset), &pConverter->channelConverter);
  43532. if (result != MA_SUCCESS) {
  43533. return result;
  43534. }
  43535. /* If the channel converter is not a passthrough we need to enable it. Otherwise we can skip it. */
  43536. if (pConverter->channelConverter.conversionPath != ma_channel_conversion_path_passthrough) {
  43537. pConverter->hasChannelConverter = MA_TRUE;
  43538. }
  43539. }
  43540. /* Resampler. */
  43541. if (isResamplingRequired) {
  43542. ma_resampler_config resamplerConfig = ma_resampler_config_init_from_data_converter_config(pConfig);
  43543. result = ma_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pConverter->resampler);
  43544. if (result != MA_SUCCESS) {
  43545. return result;
  43546. }
  43547. pConverter->hasResampler = MA_TRUE;
  43548. }
  43549. /* We can simplify pre- and post-format conversion if we have neither channel conversion nor resampling. */
  43550. if (pConverter->hasChannelConverter == MA_FALSE && pConverter->hasResampler == MA_FALSE) {
  43551. /* 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. */
  43552. if (pConverter->formatIn == pConverter->formatOut) {
  43553. /* The formats are the same so we can just pass through. */
  43554. pConverter->hasPreFormatConversion = MA_FALSE;
  43555. pConverter->hasPostFormatConversion = MA_FALSE;
  43556. } else {
  43557. /* The formats are different so we need to do either pre- or post-format conversion. It doesn't matter which. */
  43558. pConverter->hasPreFormatConversion = MA_FALSE;
  43559. pConverter->hasPostFormatConversion = MA_TRUE;
  43560. }
  43561. } else {
  43562. /* We have a channel converter and/or resampler so we'll need channel conversion based on the mid format. */
  43563. if (pConverter->formatIn != midFormat) {
  43564. pConverter->hasPreFormatConversion = MA_TRUE;
  43565. }
  43566. if (pConverter->formatOut != midFormat) {
  43567. pConverter->hasPostFormatConversion = MA_TRUE;
  43568. }
  43569. }
  43570. /* We can enable passthrough optimizations if applicable. Note that we'll only be able to do this if the sample rate is static. */
  43571. if (pConverter->hasPreFormatConversion == MA_FALSE &&
  43572. pConverter->hasPostFormatConversion == MA_FALSE &&
  43573. pConverter->hasChannelConverter == MA_FALSE &&
  43574. pConverter->hasResampler == MA_FALSE) {
  43575. pConverter->isPassthrough = MA_TRUE;
  43576. }
  43577. /* We now need to determine our execution path. */
  43578. if (pConverter->isPassthrough) {
  43579. pConverter->executionPath = ma_data_converter_execution_path_passthrough;
  43580. } else {
  43581. if (pConverter->channelsIn < pConverter->channelsOut) {
  43582. /* Do resampling first, if necessary. */
  43583. MA_ASSERT(pConverter->hasChannelConverter == MA_TRUE);
  43584. if (pConverter->hasResampler) {
  43585. pConverter->executionPath = ma_data_converter_execution_path_resample_first;
  43586. } else {
  43587. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  43588. }
  43589. } else {
  43590. /* Do channel conversion first, if necessary. */
  43591. if (pConverter->hasChannelConverter) {
  43592. if (pConverter->hasResampler) {
  43593. pConverter->executionPath = ma_data_converter_execution_path_channels_first;
  43594. } else {
  43595. pConverter->executionPath = ma_data_converter_execution_path_channels_only;
  43596. }
  43597. } else {
  43598. /* Channel routing not required. */
  43599. if (pConverter->hasResampler) {
  43600. pConverter->executionPath = ma_data_converter_execution_path_resample_only;
  43601. } else {
  43602. pConverter->executionPath = ma_data_converter_execution_path_format_only;
  43603. }
  43604. }
  43605. }
  43606. }
  43607. return MA_SUCCESS;
  43608. }
  43609. MA_API ma_result ma_data_converter_init(const ma_data_converter_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_data_converter* pConverter)
  43610. {
  43611. ma_result result;
  43612. size_t heapSizeInBytes;
  43613. void* pHeap;
  43614. result = ma_data_converter_get_heap_size(pConfig, &heapSizeInBytes);
  43615. if (result != MA_SUCCESS) {
  43616. return result;
  43617. }
  43618. if (heapSizeInBytes > 0) {
  43619. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  43620. if (pHeap == NULL) {
  43621. return MA_OUT_OF_MEMORY;
  43622. }
  43623. } else {
  43624. pHeap = NULL;
  43625. }
  43626. result = ma_data_converter_init_preallocated(pConfig, pHeap, pConverter);
  43627. if (result != MA_SUCCESS) {
  43628. ma_free(pHeap, pAllocationCallbacks);
  43629. return result;
  43630. }
  43631. pConverter->_ownsHeap = MA_TRUE;
  43632. return MA_SUCCESS;
  43633. }
  43634. MA_API void ma_data_converter_uninit(ma_data_converter* pConverter, const ma_allocation_callbacks* pAllocationCallbacks)
  43635. {
  43636. if (pConverter == NULL) {
  43637. return;
  43638. }
  43639. if (pConverter->hasResampler) {
  43640. ma_resampler_uninit(&pConverter->resampler, pAllocationCallbacks);
  43641. }
  43642. ma_channel_converter_uninit(&pConverter->channelConverter, pAllocationCallbacks);
  43643. if (pConverter->_ownsHeap) {
  43644. ma_free(pConverter->_pHeap, pAllocationCallbacks);
  43645. }
  43646. }
  43647. 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)
  43648. {
  43649. ma_uint64 frameCountIn;
  43650. ma_uint64 frameCountOut;
  43651. ma_uint64 frameCount;
  43652. MA_ASSERT(pConverter != NULL);
  43653. frameCountIn = 0;
  43654. if (pFrameCountIn != NULL) {
  43655. frameCountIn = *pFrameCountIn;
  43656. }
  43657. frameCountOut = 0;
  43658. if (pFrameCountOut != NULL) {
  43659. frameCountOut = *pFrameCountOut;
  43660. }
  43661. frameCount = ma_min(frameCountIn, frameCountOut);
  43662. if (pFramesOut != NULL) {
  43663. if (pFramesIn != NULL) {
  43664. ma_copy_memory_64(pFramesOut, pFramesIn, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43665. } else {
  43666. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43667. }
  43668. }
  43669. if (pFrameCountIn != NULL) {
  43670. *pFrameCountIn = frameCount;
  43671. }
  43672. if (pFrameCountOut != NULL) {
  43673. *pFrameCountOut = frameCount;
  43674. }
  43675. return MA_SUCCESS;
  43676. }
  43677. 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)
  43678. {
  43679. ma_uint64 frameCountIn;
  43680. ma_uint64 frameCountOut;
  43681. ma_uint64 frameCount;
  43682. MA_ASSERT(pConverter != NULL);
  43683. frameCountIn = 0;
  43684. if (pFrameCountIn != NULL) {
  43685. frameCountIn = *pFrameCountIn;
  43686. }
  43687. frameCountOut = 0;
  43688. if (pFrameCountOut != NULL) {
  43689. frameCountOut = *pFrameCountOut;
  43690. }
  43691. frameCount = ma_min(frameCountIn, frameCountOut);
  43692. if (pFramesOut != NULL) {
  43693. if (pFramesIn != NULL) {
  43694. ma_convert_pcm_frames_format(pFramesOut, pConverter->formatOut, pFramesIn, pConverter->formatIn, frameCount, pConverter->channelsIn, pConverter->ditherMode);
  43695. } else {
  43696. ma_zero_memory_64(pFramesOut, frameCount * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43697. }
  43698. }
  43699. if (pFrameCountIn != NULL) {
  43700. *pFrameCountIn = frameCount;
  43701. }
  43702. if (pFrameCountOut != NULL) {
  43703. *pFrameCountOut = frameCount;
  43704. }
  43705. return MA_SUCCESS;
  43706. }
  43707. 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)
  43708. {
  43709. ma_result result = MA_SUCCESS;
  43710. ma_uint64 frameCountIn;
  43711. ma_uint64 frameCountOut;
  43712. ma_uint64 framesProcessedIn;
  43713. ma_uint64 framesProcessedOut;
  43714. MA_ASSERT(pConverter != NULL);
  43715. frameCountIn = 0;
  43716. if (pFrameCountIn != NULL) {
  43717. frameCountIn = *pFrameCountIn;
  43718. }
  43719. frameCountOut = 0;
  43720. if (pFrameCountOut != NULL) {
  43721. frameCountOut = *pFrameCountOut;
  43722. }
  43723. framesProcessedIn = 0;
  43724. framesProcessedOut = 0;
  43725. while (framesProcessedOut < frameCountOut) {
  43726. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  43727. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  43728. const void* pFramesInThisIteration;
  43729. /* */ void* pFramesOutThisIteration;
  43730. ma_uint64 frameCountInThisIteration;
  43731. ma_uint64 frameCountOutThisIteration;
  43732. if (pFramesIn != NULL) {
  43733. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  43734. } else {
  43735. pFramesInThisIteration = NULL;
  43736. }
  43737. if (pFramesOut != NULL) {
  43738. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43739. } else {
  43740. pFramesOutThisIteration = NULL;
  43741. }
  43742. /* Do a pre format conversion if necessary. */
  43743. if (pConverter->hasPreFormatConversion) {
  43744. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  43745. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  43746. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  43747. if (frameCountInThisIteration > tempBufferInCap) {
  43748. frameCountInThisIteration = tempBufferInCap;
  43749. }
  43750. if (pConverter->hasPostFormatConversion) {
  43751. if (frameCountInThisIteration > tempBufferOutCap) {
  43752. frameCountInThisIteration = tempBufferOutCap;
  43753. }
  43754. }
  43755. if (pFramesInThisIteration != NULL) {
  43756. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pFramesInThisIteration, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  43757. } else {
  43758. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  43759. }
  43760. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  43761. if (pConverter->hasPostFormatConversion) {
  43762. /* Both input and output conversion required. Output to the temp buffer. */
  43763. if (frameCountOutThisIteration > tempBufferOutCap) {
  43764. frameCountOutThisIteration = tempBufferOutCap;
  43765. }
  43766. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  43767. } else {
  43768. /* Only pre-format required. Output straight to the output buffer. */
  43769. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferIn, &frameCountInThisIteration, pFramesOutThisIteration, &frameCountOutThisIteration);
  43770. }
  43771. if (result != MA_SUCCESS) {
  43772. break;
  43773. }
  43774. } else {
  43775. /* No pre-format required. Just read straight from the input buffer. */
  43776. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  43777. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  43778. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  43779. if (frameCountOutThisIteration > tempBufferOutCap) {
  43780. frameCountOutThisIteration = tempBufferOutCap;
  43781. }
  43782. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesInThisIteration, &frameCountInThisIteration, pTempBufferOut, &frameCountOutThisIteration);
  43783. if (result != MA_SUCCESS) {
  43784. break;
  43785. }
  43786. }
  43787. /* If we are doing a post format conversion we need to do that now. */
  43788. if (pConverter->hasPostFormatConversion) {
  43789. if (pFramesOutThisIteration != NULL) {
  43790. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->resampler.channels, pConverter->ditherMode);
  43791. }
  43792. }
  43793. framesProcessedIn += frameCountInThisIteration;
  43794. framesProcessedOut += frameCountOutThisIteration;
  43795. MA_ASSERT(framesProcessedIn <= frameCountIn);
  43796. MA_ASSERT(framesProcessedOut <= frameCountOut);
  43797. if (frameCountOutThisIteration == 0) {
  43798. break; /* Consumed all of our input data. */
  43799. }
  43800. }
  43801. if (pFrameCountIn != NULL) {
  43802. *pFrameCountIn = framesProcessedIn;
  43803. }
  43804. if (pFrameCountOut != NULL) {
  43805. *pFrameCountOut = framesProcessedOut;
  43806. }
  43807. return result;
  43808. }
  43809. 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)
  43810. {
  43811. MA_ASSERT(pConverter != NULL);
  43812. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  43813. /* Neither pre- nor post-format required. This is simple case where only resampling is required. */
  43814. return ma_resampler_process_pcm_frames(&pConverter->resampler, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43815. } else {
  43816. /* Format conversion required. */
  43817. return ma_data_converter_process_pcm_frames__resample_with_format_conversion(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  43818. }
  43819. }
  43820. 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)
  43821. {
  43822. ma_result result;
  43823. ma_uint64 frameCountIn;
  43824. ma_uint64 frameCountOut;
  43825. ma_uint64 frameCount;
  43826. MA_ASSERT(pConverter != NULL);
  43827. frameCountIn = 0;
  43828. if (pFrameCountIn != NULL) {
  43829. frameCountIn = *pFrameCountIn;
  43830. }
  43831. frameCountOut = 0;
  43832. if (pFrameCountOut != NULL) {
  43833. frameCountOut = *pFrameCountOut;
  43834. }
  43835. frameCount = ma_min(frameCountIn, frameCountOut);
  43836. if (pConverter->hasPreFormatConversion == MA_FALSE && pConverter->hasPostFormatConversion == MA_FALSE) {
  43837. /* No format conversion required. */
  43838. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOut, pFramesIn, frameCount);
  43839. if (result != MA_SUCCESS) {
  43840. return result;
  43841. }
  43842. } else {
  43843. /* Format conversion required. */
  43844. ma_uint64 framesProcessed = 0;
  43845. while (framesProcessed < frameCount) {
  43846. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  43847. const ma_uint32 tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  43848. const void* pFramesInThisIteration;
  43849. /* */ void* pFramesOutThisIteration;
  43850. ma_uint64 frameCountThisIteration;
  43851. if (pFramesIn != NULL) {
  43852. pFramesInThisIteration = ma_offset_ptr(pFramesIn, framesProcessed * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  43853. } else {
  43854. pFramesInThisIteration = NULL;
  43855. }
  43856. if (pFramesOut != NULL) {
  43857. pFramesOutThisIteration = ma_offset_ptr(pFramesOut, framesProcessed * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43858. } else {
  43859. pFramesOutThisIteration = NULL;
  43860. }
  43861. /* Do a pre format conversion if necessary. */
  43862. if (pConverter->hasPreFormatConversion) {
  43863. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  43864. const ma_uint32 tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  43865. frameCountThisIteration = (frameCount - framesProcessed);
  43866. if (frameCountThisIteration > tempBufferInCap) {
  43867. frameCountThisIteration = tempBufferInCap;
  43868. }
  43869. if (pConverter->hasPostFormatConversion) {
  43870. if (frameCountThisIteration > tempBufferOutCap) {
  43871. frameCountThisIteration = tempBufferOutCap;
  43872. }
  43873. }
  43874. if (pFramesInThisIteration != NULL) {
  43875. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pFramesInThisIteration, pConverter->formatIn, frameCountThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  43876. } else {
  43877. MA_ZERO_MEMORY(pTempBufferIn, sizeof(pTempBufferIn));
  43878. }
  43879. if (pConverter->hasPostFormatConversion) {
  43880. /* Both input and output conversion required. Output to the temp buffer. */
  43881. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pTempBufferIn, frameCountThisIteration);
  43882. } else {
  43883. /* Only pre-format required. Output straight to the output buffer. */
  43884. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pFramesOutThisIteration, pTempBufferIn, frameCountThisIteration);
  43885. }
  43886. if (result != MA_SUCCESS) {
  43887. break;
  43888. }
  43889. } else {
  43890. /* No pre-format required. Just read straight from the input buffer. */
  43891. MA_ASSERT(pConverter->hasPostFormatConversion == MA_TRUE);
  43892. frameCountThisIteration = (frameCount - framesProcessed);
  43893. if (frameCountThisIteration > tempBufferOutCap) {
  43894. frameCountThisIteration = tempBufferOutCap;
  43895. }
  43896. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferOut, pFramesInThisIteration, frameCountThisIteration);
  43897. if (result != MA_SUCCESS) {
  43898. break;
  43899. }
  43900. }
  43901. /* If we are doing a post format conversion we need to do that now. */
  43902. if (pConverter->hasPostFormatConversion) {
  43903. if (pFramesOutThisIteration != NULL) {
  43904. ma_convert_pcm_frames_format(pFramesOutThisIteration, pConverter->formatOut, pTempBufferOut, pConverter->channelConverter.format, frameCountThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  43905. }
  43906. }
  43907. framesProcessed += frameCountThisIteration;
  43908. }
  43909. }
  43910. if (pFrameCountIn != NULL) {
  43911. *pFrameCountIn = frameCount;
  43912. }
  43913. if (pFrameCountOut != NULL) {
  43914. *pFrameCountOut = frameCount;
  43915. }
  43916. return MA_SUCCESS;
  43917. }
  43918. 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)
  43919. {
  43920. ma_result result;
  43921. ma_uint64 frameCountIn;
  43922. ma_uint64 frameCountOut;
  43923. ma_uint64 framesProcessedIn;
  43924. ma_uint64 framesProcessedOut;
  43925. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  43926. ma_uint64 tempBufferInCap;
  43927. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  43928. ma_uint64 tempBufferMidCap;
  43929. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  43930. ma_uint64 tempBufferOutCap;
  43931. MA_ASSERT(pConverter != NULL);
  43932. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  43933. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsIn);
  43934. MA_ASSERT(pConverter->resampler.channels < pConverter->channelConverter.channelsOut);
  43935. frameCountIn = 0;
  43936. if (pFrameCountIn != NULL) {
  43937. frameCountIn = *pFrameCountIn;
  43938. }
  43939. frameCountOut = 0;
  43940. if (pFrameCountOut != NULL) {
  43941. frameCountOut = *pFrameCountOut;
  43942. }
  43943. framesProcessedIn = 0;
  43944. framesProcessedOut = 0;
  43945. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  43946. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  43947. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  43948. while (framesProcessedOut < frameCountOut) {
  43949. ma_uint64 frameCountInThisIteration;
  43950. ma_uint64 frameCountOutThisIteration;
  43951. const void* pRunningFramesIn = NULL;
  43952. void* pRunningFramesOut = NULL;
  43953. const void* pResampleBufferIn;
  43954. void* pChannelsBufferOut;
  43955. if (pFramesIn != NULL) {
  43956. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  43957. }
  43958. if (pFramesOut != NULL) {
  43959. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  43960. }
  43961. /* Run input data through the resampler and output it to the temporary buffer. */
  43962. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  43963. if (pConverter->hasPreFormatConversion) {
  43964. if (frameCountInThisIteration > tempBufferInCap) {
  43965. frameCountInThisIteration = tempBufferInCap;
  43966. }
  43967. }
  43968. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  43969. if (frameCountOutThisIteration > tempBufferMidCap) {
  43970. frameCountOutThisIteration = tempBufferMidCap;
  43971. }
  43972. /* We can't read more frames than can fit in the output buffer. */
  43973. if (pConverter->hasPostFormatConversion) {
  43974. if (frameCountOutThisIteration > tempBufferOutCap) {
  43975. frameCountOutThisIteration = tempBufferOutCap;
  43976. }
  43977. }
  43978. /* 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. */
  43979. /*
  43980. We need to try to predict how many input frames will be required for the resampler. If the
  43981. resampler can tell us, we'll use that. Otherwise we'll need to make a best guess. The further
  43982. off we are from this, the more wasted format conversions we'll end up doing.
  43983. */
  43984. #if 1
  43985. {
  43986. ma_uint64 requiredInputFrameCount;
  43987. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  43988. if (result != MA_SUCCESS) {
  43989. /* Fall back to a best guess. */
  43990. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  43991. }
  43992. if (frameCountInThisIteration > requiredInputFrameCount) {
  43993. frameCountInThisIteration = requiredInputFrameCount;
  43994. }
  43995. }
  43996. #endif
  43997. if (pConverter->hasPreFormatConversion) {
  43998. if (pFramesIn != NULL) {
  43999. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->resampler.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  44000. pResampleBufferIn = pTempBufferIn;
  44001. } else {
  44002. pResampleBufferIn = NULL;
  44003. }
  44004. } else {
  44005. pResampleBufferIn = pRunningFramesIn;
  44006. }
  44007. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pResampleBufferIn, &frameCountInThisIteration, pTempBufferMid, &frameCountOutThisIteration);
  44008. if (result != MA_SUCCESS) {
  44009. return result;
  44010. }
  44011. /*
  44012. 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
  44013. this part if we have an output buffer.
  44014. */
  44015. if (pFramesOut != NULL) {
  44016. if (pConverter->hasPostFormatConversion) {
  44017. pChannelsBufferOut = pTempBufferOut;
  44018. } else {
  44019. pChannelsBufferOut = pRunningFramesOut;
  44020. }
  44021. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pChannelsBufferOut, pTempBufferMid, frameCountOutThisIteration);
  44022. if (result != MA_SUCCESS) {
  44023. return result;
  44024. }
  44025. /* Finally we do post format conversion. */
  44026. if (pConverter->hasPostFormatConversion) {
  44027. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pChannelsBufferOut, pConverter->channelConverter.format, frameCountOutThisIteration, pConverter->channelConverter.channelsOut, pConverter->ditherMode);
  44028. }
  44029. }
  44030. framesProcessedIn += frameCountInThisIteration;
  44031. framesProcessedOut += frameCountOutThisIteration;
  44032. MA_ASSERT(framesProcessedIn <= frameCountIn);
  44033. MA_ASSERT(framesProcessedOut <= frameCountOut);
  44034. if (frameCountOutThisIteration == 0) {
  44035. break; /* Consumed all of our input data. */
  44036. }
  44037. }
  44038. if (pFrameCountIn != NULL) {
  44039. *pFrameCountIn = framesProcessedIn;
  44040. }
  44041. if (pFrameCountOut != NULL) {
  44042. *pFrameCountOut = framesProcessedOut;
  44043. }
  44044. return MA_SUCCESS;
  44045. }
  44046. 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)
  44047. {
  44048. ma_result result;
  44049. ma_uint64 frameCountIn;
  44050. ma_uint64 frameCountOut;
  44051. ma_uint64 framesProcessedIn;
  44052. ma_uint64 framesProcessedOut;
  44053. ma_uint8 pTempBufferIn[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format. */
  44054. ma_uint64 tempBufferInCap;
  44055. ma_uint8 pTempBufferMid[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In resampler format, channel converter input format. */
  44056. ma_uint64 tempBufferMidCap;
  44057. ma_uint8 pTempBufferOut[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In channel converter output format. */
  44058. ma_uint64 tempBufferOutCap;
  44059. MA_ASSERT(pConverter != NULL);
  44060. MA_ASSERT(pConverter->resampler.format == pConverter->channelConverter.format);
  44061. MA_ASSERT(pConverter->resampler.channels == pConverter->channelConverter.channelsOut);
  44062. MA_ASSERT(pConverter->resampler.channels <= pConverter->channelConverter.channelsIn);
  44063. frameCountIn = 0;
  44064. if (pFrameCountIn != NULL) {
  44065. frameCountIn = *pFrameCountIn;
  44066. }
  44067. frameCountOut = 0;
  44068. if (pFrameCountOut != NULL) {
  44069. frameCountOut = *pFrameCountOut;
  44070. }
  44071. framesProcessedIn = 0;
  44072. framesProcessedOut = 0;
  44073. tempBufferInCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsIn);
  44074. tempBufferMidCap = sizeof(pTempBufferIn) / ma_get_bytes_per_frame(pConverter->channelConverter.format, pConverter->channelConverter.channelsOut);
  44075. tempBufferOutCap = sizeof(pTempBufferOut) / ma_get_bytes_per_frame(pConverter->resampler.format, pConverter->resampler.channels);
  44076. while (framesProcessedOut < frameCountOut) {
  44077. ma_uint64 frameCountInThisIteration;
  44078. ma_uint64 frameCountOutThisIteration;
  44079. const void* pRunningFramesIn = NULL;
  44080. void* pRunningFramesOut = NULL;
  44081. const void* pChannelsBufferIn;
  44082. void* pResampleBufferOut;
  44083. if (pFramesIn != NULL) {
  44084. pRunningFramesIn = ma_offset_ptr(pFramesIn, framesProcessedIn * ma_get_bytes_per_frame(pConverter->formatIn, pConverter->channelsIn));
  44085. }
  44086. if (pFramesOut != NULL) {
  44087. pRunningFramesOut = ma_offset_ptr(pFramesOut, framesProcessedOut * ma_get_bytes_per_frame(pConverter->formatOut, pConverter->channelsOut));
  44088. }
  44089. /*
  44090. Before doing any processing we need to determine how many frames we should try processing
  44091. this iteration, for both input and output. The resampler requires us to perform format and
  44092. channel conversion before passing any data into it. If we get our input count wrong, we'll
  44093. end up peforming redundant pre-processing. This isn't the end of the world, but it does
  44094. result in some inefficiencies proportionate to how far our estimates are off.
  44095. If the resampler has a means to calculate exactly how much we'll need, we'll use that.
  44096. Otherwise we'll make a best guess. In order to do this, we'll need to calculate the output
  44097. frame count first.
  44098. */
  44099. frameCountOutThisIteration = (frameCountOut - framesProcessedOut);
  44100. if (frameCountOutThisIteration > tempBufferMidCap) {
  44101. frameCountOutThisIteration = tempBufferMidCap;
  44102. }
  44103. if (pConverter->hasPostFormatConversion) {
  44104. if (frameCountOutThisIteration > tempBufferOutCap) {
  44105. frameCountOutThisIteration = tempBufferOutCap;
  44106. }
  44107. }
  44108. /* Now that we have the output frame count we can determine the input frame count. */
  44109. frameCountInThisIteration = (frameCountIn - framesProcessedIn);
  44110. if (pConverter->hasPreFormatConversion) {
  44111. if (frameCountInThisIteration > tempBufferInCap) {
  44112. frameCountInThisIteration = tempBufferInCap;
  44113. }
  44114. }
  44115. if (frameCountInThisIteration > tempBufferMidCap) {
  44116. frameCountInThisIteration = tempBufferMidCap;
  44117. }
  44118. #if 1
  44119. {
  44120. ma_uint64 requiredInputFrameCount;
  44121. result = ma_resampler_get_required_input_frame_count(&pConverter->resampler, frameCountOutThisIteration, &requiredInputFrameCount);
  44122. if (result != MA_SUCCESS) {
  44123. /* Fall back to a best guess. */
  44124. requiredInputFrameCount = (frameCountOutThisIteration * pConverter->resampler.sampleRateIn) / pConverter->resampler.sampleRateOut;
  44125. }
  44126. if (frameCountInThisIteration > requiredInputFrameCount) {
  44127. frameCountInThisIteration = requiredInputFrameCount;
  44128. }
  44129. }
  44130. #endif
  44131. /* Pre format conversion. */
  44132. if (pConverter->hasPreFormatConversion) {
  44133. if (pRunningFramesIn != NULL) {
  44134. ma_convert_pcm_frames_format(pTempBufferIn, pConverter->channelConverter.format, pRunningFramesIn, pConverter->formatIn, frameCountInThisIteration, pConverter->channelsIn, pConverter->ditherMode);
  44135. pChannelsBufferIn = pTempBufferIn;
  44136. } else {
  44137. pChannelsBufferIn = NULL;
  44138. }
  44139. } else {
  44140. pChannelsBufferIn = pRunningFramesIn;
  44141. }
  44142. /* Channel conversion. */
  44143. result = ma_channel_converter_process_pcm_frames(&pConverter->channelConverter, pTempBufferMid, pChannelsBufferIn, frameCountInThisIteration);
  44144. if (result != MA_SUCCESS) {
  44145. return result;
  44146. }
  44147. /* Resampling. */
  44148. if (pConverter->hasPostFormatConversion) {
  44149. pResampleBufferOut = pTempBufferOut;
  44150. } else {
  44151. pResampleBufferOut = pRunningFramesOut;
  44152. }
  44153. result = ma_resampler_process_pcm_frames(&pConverter->resampler, pTempBufferMid, &frameCountInThisIteration, pResampleBufferOut, &frameCountOutThisIteration);
  44154. if (result != MA_SUCCESS) {
  44155. return result;
  44156. }
  44157. /* Post format conversion. */
  44158. if (pConverter->hasPostFormatConversion) {
  44159. if (pRunningFramesOut != NULL) {
  44160. ma_convert_pcm_frames_format(pRunningFramesOut, pConverter->formatOut, pResampleBufferOut, pConverter->resampler.format, frameCountOutThisIteration, pConverter->channelsOut, pConverter->ditherMode);
  44161. }
  44162. }
  44163. framesProcessedIn += frameCountInThisIteration;
  44164. framesProcessedOut += frameCountOutThisIteration;
  44165. MA_ASSERT(framesProcessedIn <= frameCountIn);
  44166. MA_ASSERT(framesProcessedOut <= frameCountOut);
  44167. if (frameCountOutThisIteration == 0) {
  44168. break; /* Consumed all of our input data. */
  44169. }
  44170. }
  44171. if (pFrameCountIn != NULL) {
  44172. *pFrameCountIn = framesProcessedIn;
  44173. }
  44174. if (pFrameCountOut != NULL) {
  44175. *pFrameCountOut = framesProcessedOut;
  44176. }
  44177. return MA_SUCCESS;
  44178. }
  44179. 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)
  44180. {
  44181. if (pConverter == NULL) {
  44182. return MA_INVALID_ARGS;
  44183. }
  44184. switch (pConverter->executionPath)
  44185. {
  44186. case ma_data_converter_execution_path_passthrough: return ma_data_converter_process_pcm_frames__passthrough(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44187. case ma_data_converter_execution_path_format_only: return ma_data_converter_process_pcm_frames__format_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44188. case ma_data_converter_execution_path_channels_only: return ma_data_converter_process_pcm_frames__channels_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44189. case ma_data_converter_execution_path_resample_only: return ma_data_converter_process_pcm_frames__resample_only(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44190. case ma_data_converter_execution_path_resample_first: return ma_data_converter_process_pcm_frames__resample_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44191. case ma_data_converter_execution_path_channels_first: return ma_data_converter_process_pcm_frames__channels_first(pConverter, pFramesIn, pFrameCountIn, pFramesOut, pFrameCountOut);
  44192. default: return MA_INVALID_OPERATION; /* Should never hit this. */
  44193. }
  44194. }
  44195. MA_API ma_result ma_data_converter_set_rate(ma_data_converter* pConverter, ma_uint32 sampleRateIn, ma_uint32 sampleRateOut)
  44196. {
  44197. if (pConverter == NULL) {
  44198. return MA_INVALID_ARGS;
  44199. }
  44200. if (pConverter->hasResampler == MA_FALSE) {
  44201. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  44202. }
  44203. return ma_resampler_set_rate(&pConverter->resampler, sampleRateIn, sampleRateOut);
  44204. }
  44205. MA_API ma_result ma_data_converter_set_rate_ratio(ma_data_converter* pConverter, float ratioInOut)
  44206. {
  44207. if (pConverter == NULL) {
  44208. return MA_INVALID_ARGS;
  44209. }
  44210. if (pConverter->hasResampler == MA_FALSE) {
  44211. return MA_INVALID_OPERATION; /* Dynamic resampling not enabled. */
  44212. }
  44213. return ma_resampler_set_rate_ratio(&pConverter->resampler, ratioInOut);
  44214. }
  44215. MA_API ma_uint64 ma_data_converter_get_input_latency(const ma_data_converter* pConverter)
  44216. {
  44217. if (pConverter == NULL) {
  44218. return 0;
  44219. }
  44220. if (pConverter->hasResampler) {
  44221. return ma_resampler_get_input_latency(&pConverter->resampler);
  44222. }
  44223. return 0; /* No latency without a resampler. */
  44224. }
  44225. MA_API ma_uint64 ma_data_converter_get_output_latency(const ma_data_converter* pConverter)
  44226. {
  44227. if (pConverter == NULL) {
  44228. return 0;
  44229. }
  44230. if (pConverter->hasResampler) {
  44231. return ma_resampler_get_output_latency(&pConverter->resampler);
  44232. }
  44233. return 0; /* No latency without a resampler. */
  44234. }
  44235. MA_API ma_result ma_data_converter_get_required_input_frame_count(const ma_data_converter* pConverter, ma_uint64 outputFrameCount, ma_uint64* pInputFrameCount)
  44236. {
  44237. if (pInputFrameCount == NULL) {
  44238. return MA_INVALID_ARGS;
  44239. }
  44240. *pInputFrameCount = 0;
  44241. if (pConverter == NULL) {
  44242. return MA_INVALID_ARGS;
  44243. }
  44244. if (pConverter->hasResampler) {
  44245. return ma_resampler_get_required_input_frame_count(&pConverter->resampler, outputFrameCount, pInputFrameCount);
  44246. } else {
  44247. *pInputFrameCount = outputFrameCount; /* 1:1 */
  44248. return MA_SUCCESS;
  44249. }
  44250. }
  44251. MA_API ma_result ma_data_converter_get_expected_output_frame_count(const ma_data_converter* pConverter, ma_uint64 inputFrameCount, ma_uint64* pOutputFrameCount)
  44252. {
  44253. if (pOutputFrameCount == NULL) {
  44254. return MA_INVALID_ARGS;
  44255. }
  44256. *pOutputFrameCount = 0;
  44257. if (pConverter == NULL) {
  44258. return MA_INVALID_ARGS;
  44259. }
  44260. if (pConverter->hasResampler) {
  44261. return ma_resampler_get_expected_output_frame_count(&pConverter->resampler, inputFrameCount, pOutputFrameCount);
  44262. } else {
  44263. *pOutputFrameCount = inputFrameCount; /* 1:1 */
  44264. return MA_SUCCESS;
  44265. }
  44266. }
  44267. MA_API ma_result ma_data_converter_get_input_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44268. {
  44269. if (pConverter == NULL || pChannelMap == NULL) {
  44270. return MA_INVALID_ARGS;
  44271. }
  44272. if (pConverter->hasChannelConverter) {
  44273. ma_channel_converter_get_output_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  44274. } else {
  44275. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsOut);
  44276. }
  44277. return MA_SUCCESS;
  44278. }
  44279. MA_API ma_result ma_data_converter_get_output_channel_map(const ma_data_converter* pConverter, ma_channel* pChannelMap, size_t channelMapCap)
  44280. {
  44281. if (pConverter == NULL || pChannelMap == NULL) {
  44282. return MA_INVALID_ARGS;
  44283. }
  44284. if (pConverter->hasChannelConverter) {
  44285. ma_channel_converter_get_input_channel_map(&pConverter->channelConverter, pChannelMap, channelMapCap);
  44286. } else {
  44287. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pConverter->channelsIn);
  44288. }
  44289. return MA_SUCCESS;
  44290. }
  44291. MA_API ma_result ma_data_converter_reset(ma_data_converter* pConverter)
  44292. {
  44293. if (pConverter == NULL) {
  44294. return MA_INVALID_ARGS;
  44295. }
  44296. /* There's nothing to do if we're not resampling. */
  44297. if (pConverter->hasResampler == MA_FALSE) {
  44298. return MA_SUCCESS;
  44299. }
  44300. return ma_resampler_reset(&pConverter->resampler);
  44301. }
  44302. /**************************************************************************************************************************************************************
  44303. Channel Maps
  44304. **************************************************************************************************************************************************************/
  44305. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex);
  44306. MA_API ma_channel ma_channel_map_get_channel(const ma_channel* pChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  44307. {
  44308. if (pChannelMap == NULL) {
  44309. return ma_channel_map_init_standard_channel(ma_standard_channel_map_default, channelCount, channelIndex);
  44310. } else {
  44311. if (channelIndex >= channelCount) {
  44312. return MA_CHANNEL_NONE;
  44313. }
  44314. return pChannelMap[channelIndex];
  44315. }
  44316. }
  44317. MA_API void ma_channel_map_init_blank(ma_channel* pChannelMap, ma_uint32 channels)
  44318. {
  44319. if (pChannelMap == NULL) {
  44320. return;
  44321. }
  44322. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channels);
  44323. }
  44324. static ma_channel ma_channel_map_init_standard_channel_microsoft(ma_uint32 channelCount, ma_uint32 channelIndex)
  44325. {
  44326. if (channelCount == 0 || channelIndex >= channelCount) {
  44327. return MA_CHANNEL_NONE;
  44328. }
  44329. /* 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 */
  44330. switch (channelCount)
  44331. {
  44332. case 0: return MA_CHANNEL_NONE;
  44333. case 1:
  44334. {
  44335. return MA_CHANNEL_MONO;
  44336. } break;
  44337. case 2:
  44338. {
  44339. switch (channelIndex) {
  44340. case 0: return MA_CHANNEL_FRONT_LEFT;
  44341. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44342. }
  44343. } break;
  44344. case 3: /* No defined, but best guess. */
  44345. {
  44346. switch (channelIndex) {
  44347. case 0: return MA_CHANNEL_FRONT_LEFT;
  44348. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44349. case 2: return MA_CHANNEL_FRONT_CENTER;
  44350. }
  44351. } break;
  44352. case 4:
  44353. {
  44354. switch (channelIndex) {
  44355. #ifndef MA_USE_QUAD_MICROSOFT_CHANNEL_MAP
  44356. /* Surround. Using the Surround profile has the advantage of the 3rd channel (MA_CHANNEL_FRONT_CENTER) mapping nicely with higher channel counts. */
  44357. case 0: return MA_CHANNEL_FRONT_LEFT;
  44358. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44359. case 2: return MA_CHANNEL_FRONT_CENTER;
  44360. case 3: return MA_CHANNEL_BACK_CENTER;
  44361. #else
  44362. /* Quad. */
  44363. case 0: return MA_CHANNEL_FRONT_LEFT;
  44364. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44365. case 2: return MA_CHANNEL_BACK_LEFT;
  44366. case 3: return MA_CHANNEL_BACK_RIGHT;
  44367. #endif
  44368. }
  44369. } break;
  44370. case 5: /* Not defined, but best guess. */
  44371. {
  44372. switch (channelIndex) {
  44373. case 0: return MA_CHANNEL_FRONT_LEFT;
  44374. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44375. case 2: return MA_CHANNEL_FRONT_CENTER;
  44376. case 3: return MA_CHANNEL_BACK_LEFT;
  44377. case 4: return MA_CHANNEL_BACK_RIGHT;
  44378. }
  44379. } break;
  44380. case 6:
  44381. {
  44382. switch (channelIndex) {
  44383. case 0: return MA_CHANNEL_FRONT_LEFT;
  44384. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44385. case 2: return MA_CHANNEL_FRONT_CENTER;
  44386. case 3: return MA_CHANNEL_LFE;
  44387. case 4: return MA_CHANNEL_SIDE_LEFT;
  44388. case 5: return MA_CHANNEL_SIDE_RIGHT;
  44389. }
  44390. } break;
  44391. case 7: /* Not defined, but best guess. */
  44392. {
  44393. switch (channelIndex) {
  44394. case 0: return MA_CHANNEL_FRONT_LEFT;
  44395. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44396. case 2: return MA_CHANNEL_FRONT_CENTER;
  44397. case 3: return MA_CHANNEL_LFE;
  44398. case 4: return MA_CHANNEL_BACK_CENTER;
  44399. case 5: return MA_CHANNEL_SIDE_LEFT;
  44400. case 6: return MA_CHANNEL_SIDE_RIGHT;
  44401. }
  44402. } break;
  44403. case 8:
  44404. default:
  44405. {
  44406. switch (channelIndex) {
  44407. case 0: return MA_CHANNEL_FRONT_LEFT;
  44408. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44409. case 2: return MA_CHANNEL_FRONT_CENTER;
  44410. case 3: return MA_CHANNEL_LFE;
  44411. case 4: return MA_CHANNEL_BACK_LEFT;
  44412. case 5: return MA_CHANNEL_BACK_RIGHT;
  44413. case 6: return MA_CHANNEL_SIDE_LEFT;
  44414. case 7: return MA_CHANNEL_SIDE_RIGHT;
  44415. }
  44416. } break;
  44417. }
  44418. if (channelCount > 8) {
  44419. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44420. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  44421. }
  44422. }
  44423. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44424. return MA_CHANNEL_NONE;
  44425. }
  44426. static ma_channel ma_channel_map_init_standard_channel_alsa(ma_uint32 channelCount, ma_uint32 channelIndex)
  44427. {
  44428. switch (channelCount)
  44429. {
  44430. case 0: return MA_CHANNEL_NONE;
  44431. case 1:
  44432. {
  44433. return MA_CHANNEL_MONO;
  44434. } break;
  44435. case 2:
  44436. {
  44437. switch (channelIndex) {
  44438. case 0: return MA_CHANNEL_FRONT_LEFT;
  44439. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44440. }
  44441. } break;
  44442. case 3:
  44443. {
  44444. switch (channelIndex) {
  44445. case 0: return MA_CHANNEL_FRONT_LEFT;
  44446. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44447. case 2: return MA_CHANNEL_FRONT_CENTER;
  44448. }
  44449. } break;
  44450. case 4:
  44451. {
  44452. switch (channelIndex) {
  44453. case 0: return MA_CHANNEL_FRONT_LEFT;
  44454. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44455. case 2: return MA_CHANNEL_BACK_LEFT;
  44456. case 3: return MA_CHANNEL_BACK_RIGHT;
  44457. }
  44458. } break;
  44459. case 5:
  44460. {
  44461. switch (channelIndex) {
  44462. case 0: return MA_CHANNEL_FRONT_LEFT;
  44463. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44464. case 2: return MA_CHANNEL_BACK_LEFT;
  44465. case 3: return MA_CHANNEL_BACK_RIGHT;
  44466. case 4: return MA_CHANNEL_FRONT_CENTER;
  44467. }
  44468. } break;
  44469. case 6:
  44470. {
  44471. switch (channelIndex) {
  44472. case 0: return MA_CHANNEL_FRONT_LEFT;
  44473. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44474. case 2: return MA_CHANNEL_BACK_LEFT;
  44475. case 3: return MA_CHANNEL_BACK_RIGHT;
  44476. case 4: return MA_CHANNEL_FRONT_CENTER;
  44477. case 5: return MA_CHANNEL_LFE;
  44478. }
  44479. } break;
  44480. case 7:
  44481. {
  44482. switch (channelIndex) {
  44483. case 0: return MA_CHANNEL_FRONT_LEFT;
  44484. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44485. case 2: return MA_CHANNEL_BACK_LEFT;
  44486. case 3: return MA_CHANNEL_BACK_RIGHT;
  44487. case 4: return MA_CHANNEL_FRONT_CENTER;
  44488. case 5: return MA_CHANNEL_LFE;
  44489. case 6: return MA_CHANNEL_BACK_CENTER;
  44490. }
  44491. } break;
  44492. case 8:
  44493. default:
  44494. {
  44495. switch (channelIndex) {
  44496. case 0: return MA_CHANNEL_FRONT_LEFT;
  44497. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44498. case 2: return MA_CHANNEL_BACK_LEFT;
  44499. case 3: return MA_CHANNEL_BACK_RIGHT;
  44500. case 4: return MA_CHANNEL_FRONT_CENTER;
  44501. case 5: return MA_CHANNEL_LFE;
  44502. case 6: return MA_CHANNEL_SIDE_LEFT;
  44503. case 7: return MA_CHANNEL_SIDE_RIGHT;
  44504. }
  44505. } break;
  44506. }
  44507. if (channelCount > 8) {
  44508. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44509. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  44510. }
  44511. }
  44512. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44513. return MA_CHANNEL_NONE;
  44514. }
  44515. static ma_channel ma_channel_map_init_standard_channel_rfc3551(ma_uint32 channelCount, ma_uint32 channelIndex)
  44516. {
  44517. switch (channelCount)
  44518. {
  44519. case 0: return MA_CHANNEL_NONE;
  44520. case 1:
  44521. {
  44522. return MA_CHANNEL_MONO;
  44523. } break;
  44524. case 2:
  44525. {
  44526. switch (channelIndex) {
  44527. case 0: return MA_CHANNEL_FRONT_LEFT;
  44528. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44529. }
  44530. } break;
  44531. case 3:
  44532. {
  44533. switch (channelIndex) {
  44534. case 0: return MA_CHANNEL_FRONT_LEFT;
  44535. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44536. case 2: return MA_CHANNEL_FRONT_CENTER;
  44537. }
  44538. } break;
  44539. case 4:
  44540. {
  44541. switch (channelIndex) {
  44542. case 0: return MA_CHANNEL_FRONT_LEFT;
  44543. case 2: return MA_CHANNEL_FRONT_CENTER;
  44544. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44545. case 3: return MA_CHANNEL_BACK_CENTER;
  44546. }
  44547. } break;
  44548. case 5:
  44549. {
  44550. switch (channelIndex) {
  44551. case 0: return MA_CHANNEL_FRONT_LEFT;
  44552. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44553. case 2: return MA_CHANNEL_FRONT_CENTER;
  44554. case 3: return MA_CHANNEL_BACK_LEFT;
  44555. case 4: return MA_CHANNEL_BACK_RIGHT;
  44556. }
  44557. } break;
  44558. case 6:
  44559. default:
  44560. {
  44561. switch (channelIndex) {
  44562. case 0: return MA_CHANNEL_FRONT_LEFT;
  44563. case 1: return MA_CHANNEL_SIDE_LEFT;
  44564. case 2: return MA_CHANNEL_FRONT_CENTER;
  44565. case 3: return MA_CHANNEL_FRONT_RIGHT;
  44566. case 4: return MA_CHANNEL_SIDE_RIGHT;
  44567. case 5: return MA_CHANNEL_BACK_CENTER;
  44568. }
  44569. } break;
  44570. }
  44571. if (channelCount > 6) {
  44572. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44573. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  44574. }
  44575. }
  44576. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44577. return MA_CHANNEL_NONE;
  44578. }
  44579. static ma_channel ma_channel_map_init_standard_channel_flac(ma_uint32 channelCount, ma_uint32 channelIndex)
  44580. {
  44581. switch (channelCount)
  44582. {
  44583. case 0: return MA_CHANNEL_NONE;
  44584. case 1:
  44585. {
  44586. return MA_CHANNEL_MONO;
  44587. } break;
  44588. case 2:
  44589. {
  44590. switch (channelIndex) {
  44591. case 0: return MA_CHANNEL_FRONT_LEFT;
  44592. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44593. }
  44594. } break;
  44595. case 3:
  44596. {
  44597. switch (channelIndex) {
  44598. case 0: return MA_CHANNEL_FRONT_LEFT;
  44599. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44600. case 2: return MA_CHANNEL_FRONT_CENTER;
  44601. }
  44602. } break;
  44603. case 4:
  44604. {
  44605. switch (channelIndex) {
  44606. case 0: return MA_CHANNEL_FRONT_LEFT;
  44607. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44608. case 2: return MA_CHANNEL_BACK_LEFT;
  44609. case 3: return MA_CHANNEL_BACK_RIGHT;
  44610. }
  44611. } break;
  44612. case 5:
  44613. {
  44614. switch (channelIndex) {
  44615. case 0: return MA_CHANNEL_FRONT_LEFT;
  44616. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44617. case 2: return MA_CHANNEL_FRONT_CENTER;
  44618. case 3: return MA_CHANNEL_BACK_LEFT;
  44619. case 4: return MA_CHANNEL_BACK_RIGHT;
  44620. }
  44621. } break;
  44622. case 6:
  44623. {
  44624. switch (channelIndex) {
  44625. case 0: return MA_CHANNEL_FRONT_LEFT;
  44626. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44627. case 2: return MA_CHANNEL_FRONT_CENTER;
  44628. case 3: return MA_CHANNEL_LFE;
  44629. case 4: return MA_CHANNEL_BACK_LEFT;
  44630. case 5: return MA_CHANNEL_BACK_RIGHT;
  44631. }
  44632. } break;
  44633. case 7:
  44634. {
  44635. switch (channelIndex) {
  44636. case 0: return MA_CHANNEL_FRONT_LEFT;
  44637. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44638. case 2: return MA_CHANNEL_FRONT_CENTER;
  44639. case 3: return MA_CHANNEL_LFE;
  44640. case 4: return MA_CHANNEL_BACK_CENTER;
  44641. case 5: return MA_CHANNEL_SIDE_LEFT;
  44642. case 6: return MA_CHANNEL_SIDE_RIGHT;
  44643. }
  44644. } break;
  44645. case 8:
  44646. default:
  44647. {
  44648. switch (channelIndex) {
  44649. case 0: return MA_CHANNEL_FRONT_LEFT;
  44650. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44651. case 2: return MA_CHANNEL_FRONT_CENTER;
  44652. case 3: return MA_CHANNEL_LFE;
  44653. case 4: return MA_CHANNEL_BACK_LEFT;
  44654. case 5: return MA_CHANNEL_BACK_RIGHT;
  44655. case 6: return MA_CHANNEL_SIDE_LEFT;
  44656. case 7: return MA_CHANNEL_SIDE_RIGHT;
  44657. }
  44658. } break;
  44659. }
  44660. if (channelCount > 8) {
  44661. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44662. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  44663. }
  44664. }
  44665. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44666. return MA_CHANNEL_NONE;
  44667. }
  44668. static ma_channel ma_channel_map_init_standard_channel_vorbis(ma_uint32 channelCount, ma_uint32 channelIndex)
  44669. {
  44670. switch (channelCount)
  44671. {
  44672. case 0: return MA_CHANNEL_NONE;
  44673. case 1:
  44674. {
  44675. return MA_CHANNEL_MONO;
  44676. } break;
  44677. case 2:
  44678. {
  44679. switch (channelIndex) {
  44680. case 0: return MA_CHANNEL_FRONT_LEFT;
  44681. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44682. }
  44683. } break;
  44684. case 3:
  44685. {
  44686. switch (channelIndex) {
  44687. case 0: return MA_CHANNEL_FRONT_LEFT;
  44688. case 1: return MA_CHANNEL_FRONT_CENTER;
  44689. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44690. }
  44691. } break;
  44692. case 4:
  44693. {
  44694. switch (channelIndex) {
  44695. case 0: return MA_CHANNEL_FRONT_LEFT;
  44696. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44697. case 2: return MA_CHANNEL_BACK_LEFT;
  44698. case 3: return MA_CHANNEL_BACK_RIGHT;
  44699. }
  44700. } break;
  44701. case 5:
  44702. {
  44703. switch (channelIndex) {
  44704. case 0: return MA_CHANNEL_FRONT_LEFT;
  44705. case 1: return MA_CHANNEL_FRONT_CENTER;
  44706. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44707. case 3: return MA_CHANNEL_BACK_LEFT;
  44708. case 4: return MA_CHANNEL_BACK_RIGHT;
  44709. }
  44710. } break;
  44711. case 6:
  44712. {
  44713. switch (channelIndex) {
  44714. case 0: return MA_CHANNEL_FRONT_LEFT;
  44715. case 1: return MA_CHANNEL_FRONT_CENTER;
  44716. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44717. case 3: return MA_CHANNEL_BACK_LEFT;
  44718. case 4: return MA_CHANNEL_BACK_RIGHT;
  44719. case 5: return MA_CHANNEL_LFE;
  44720. }
  44721. } break;
  44722. case 7:
  44723. {
  44724. switch (channelIndex) {
  44725. case 0: return MA_CHANNEL_FRONT_LEFT;
  44726. case 1: return MA_CHANNEL_FRONT_CENTER;
  44727. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44728. case 3: return MA_CHANNEL_SIDE_LEFT;
  44729. case 4: return MA_CHANNEL_SIDE_RIGHT;
  44730. case 5: return MA_CHANNEL_BACK_CENTER;
  44731. case 6: return MA_CHANNEL_LFE;
  44732. }
  44733. } break;
  44734. case 8:
  44735. default:
  44736. {
  44737. switch (channelIndex) {
  44738. case 0: return MA_CHANNEL_FRONT_LEFT;
  44739. case 1: return MA_CHANNEL_FRONT_CENTER;
  44740. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44741. case 3: return MA_CHANNEL_SIDE_LEFT;
  44742. case 4: return MA_CHANNEL_SIDE_RIGHT;
  44743. case 5: return MA_CHANNEL_BACK_LEFT;
  44744. case 6: return MA_CHANNEL_BACK_RIGHT;
  44745. case 7: return MA_CHANNEL_LFE;
  44746. }
  44747. } break;
  44748. }
  44749. if (channelCount > 8) {
  44750. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44751. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  44752. }
  44753. }
  44754. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44755. return MA_CHANNEL_NONE;
  44756. }
  44757. static ma_channel ma_channel_map_init_standard_channel_sound4(ma_uint32 channelCount, ma_uint32 channelIndex)
  44758. {
  44759. switch (channelCount)
  44760. {
  44761. case 0: return MA_CHANNEL_NONE;
  44762. case 1:
  44763. {
  44764. return MA_CHANNEL_MONO;
  44765. } break;
  44766. case 2:
  44767. {
  44768. switch (channelIndex) {
  44769. case 0: return MA_CHANNEL_FRONT_LEFT;
  44770. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44771. }
  44772. } break;
  44773. case 3:
  44774. {
  44775. switch (channelIndex) {
  44776. case 0: return MA_CHANNEL_FRONT_LEFT;
  44777. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44778. case 2: return MA_CHANNEL_FRONT_CENTER;
  44779. }
  44780. } break;
  44781. case 4:
  44782. {
  44783. switch (channelIndex) {
  44784. case 0: return MA_CHANNEL_FRONT_LEFT;
  44785. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44786. case 2: return MA_CHANNEL_BACK_LEFT;
  44787. case 3: return MA_CHANNEL_BACK_RIGHT;
  44788. }
  44789. } break;
  44790. case 5:
  44791. {
  44792. switch (channelIndex) {
  44793. case 0: return MA_CHANNEL_FRONT_LEFT;
  44794. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44795. case 2: return MA_CHANNEL_FRONT_CENTER;
  44796. case 3: return MA_CHANNEL_BACK_LEFT;
  44797. case 4: return MA_CHANNEL_BACK_RIGHT;
  44798. }
  44799. } break;
  44800. case 6:
  44801. {
  44802. switch (channelIndex) {
  44803. case 0: return MA_CHANNEL_FRONT_LEFT;
  44804. case 1: return MA_CHANNEL_FRONT_CENTER;
  44805. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44806. case 3: return MA_CHANNEL_BACK_LEFT;
  44807. case 4: return MA_CHANNEL_BACK_RIGHT;
  44808. case 5: return MA_CHANNEL_LFE;
  44809. }
  44810. } break;
  44811. case 7:
  44812. {
  44813. switch (channelIndex) {
  44814. case 0: return MA_CHANNEL_FRONT_LEFT;
  44815. case 1: return MA_CHANNEL_FRONT_CENTER;
  44816. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44817. case 3: return MA_CHANNEL_SIDE_LEFT;
  44818. case 4: return MA_CHANNEL_SIDE_RIGHT;
  44819. case 5: return MA_CHANNEL_BACK_CENTER;
  44820. case 6: return MA_CHANNEL_LFE;
  44821. }
  44822. } break;
  44823. case 8:
  44824. default:
  44825. {
  44826. switch (channelIndex) {
  44827. case 0: return MA_CHANNEL_FRONT_LEFT;
  44828. case 1: return MA_CHANNEL_FRONT_CENTER;
  44829. case 2: return MA_CHANNEL_FRONT_RIGHT;
  44830. case 3: return MA_CHANNEL_SIDE_LEFT;
  44831. case 4: return MA_CHANNEL_SIDE_RIGHT;
  44832. case 5: return MA_CHANNEL_BACK_LEFT;
  44833. case 6: return MA_CHANNEL_BACK_RIGHT;
  44834. case 7: return MA_CHANNEL_LFE;
  44835. }
  44836. } break;
  44837. }
  44838. if (channelCount > 8) {
  44839. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44840. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 8));
  44841. }
  44842. }
  44843. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44844. return MA_CHANNEL_NONE;
  44845. }
  44846. static ma_channel ma_channel_map_init_standard_channel_sndio(ma_uint32 channelCount, ma_uint32 channelIndex)
  44847. {
  44848. switch (channelCount)
  44849. {
  44850. case 0: return MA_CHANNEL_NONE;
  44851. case 1:
  44852. {
  44853. return MA_CHANNEL_MONO;
  44854. } break;
  44855. case 2:
  44856. {
  44857. switch (channelIndex) {
  44858. case 0: return MA_CHANNEL_FRONT_LEFT;
  44859. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44860. }
  44861. } break;
  44862. case 3: /* No defined, but best guess. */
  44863. {
  44864. switch (channelIndex) {
  44865. case 0: return MA_CHANNEL_FRONT_LEFT;
  44866. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44867. case 2: return MA_CHANNEL_FRONT_CENTER;
  44868. }
  44869. } break;
  44870. case 4:
  44871. {
  44872. switch (channelIndex) {
  44873. case 0: return MA_CHANNEL_FRONT_LEFT;
  44874. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44875. case 2: return MA_CHANNEL_BACK_LEFT;
  44876. case 3: return MA_CHANNEL_BACK_RIGHT;
  44877. }
  44878. } break;
  44879. case 5: /* Not defined, but best guess. */
  44880. {
  44881. switch (channelIndex) {
  44882. case 0: return MA_CHANNEL_FRONT_LEFT;
  44883. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44884. case 2: return MA_CHANNEL_BACK_LEFT;
  44885. case 3: return MA_CHANNEL_BACK_RIGHT;
  44886. case 4: return MA_CHANNEL_FRONT_CENTER;
  44887. }
  44888. } break;
  44889. case 6:
  44890. default:
  44891. {
  44892. switch (channelIndex) {
  44893. case 0: return MA_CHANNEL_FRONT_LEFT;
  44894. case 1: return MA_CHANNEL_FRONT_RIGHT;
  44895. case 2: return MA_CHANNEL_BACK_LEFT;
  44896. case 3: return MA_CHANNEL_BACK_RIGHT;
  44897. case 4: return MA_CHANNEL_FRONT_CENTER;
  44898. case 5: return MA_CHANNEL_LFE;
  44899. }
  44900. } break;
  44901. }
  44902. if (channelCount > 6) {
  44903. if (channelIndex < 32) { /* We have 32 AUX channels. */
  44904. return (ma_channel)(MA_CHANNEL_AUX_0 + (channelIndex - 6));
  44905. }
  44906. }
  44907. /* Getting here means we don't know how to map the channel position so just return MA_CHANNEL_NONE. */
  44908. return MA_CHANNEL_NONE;
  44909. }
  44910. static ma_channel ma_channel_map_init_standard_channel(ma_standard_channel_map standardChannelMap, ma_uint32 channelCount, ma_uint32 channelIndex)
  44911. {
  44912. if (channelCount == 0 || channelIndex >= channelCount) {
  44913. return MA_CHANNEL_NONE;
  44914. }
  44915. switch (standardChannelMap)
  44916. {
  44917. case ma_standard_channel_map_alsa:
  44918. {
  44919. return ma_channel_map_init_standard_channel_alsa(channelCount, channelIndex);
  44920. } break;
  44921. case ma_standard_channel_map_rfc3551:
  44922. {
  44923. return ma_channel_map_init_standard_channel_rfc3551(channelCount, channelIndex);
  44924. } break;
  44925. case ma_standard_channel_map_flac:
  44926. {
  44927. return ma_channel_map_init_standard_channel_flac(channelCount, channelIndex);
  44928. } break;
  44929. case ma_standard_channel_map_vorbis:
  44930. {
  44931. return ma_channel_map_init_standard_channel_vorbis(channelCount, channelIndex);
  44932. } break;
  44933. case ma_standard_channel_map_sound4:
  44934. {
  44935. return ma_channel_map_init_standard_channel_sound4(channelCount, channelIndex);
  44936. } break;
  44937. case ma_standard_channel_map_sndio:
  44938. {
  44939. return ma_channel_map_init_standard_channel_sndio(channelCount, channelIndex);
  44940. } break;
  44941. case ma_standard_channel_map_microsoft: /* Also default. */
  44942. /*case ma_standard_channel_map_default;*/
  44943. default:
  44944. {
  44945. return ma_channel_map_init_standard_channel_microsoft(channelCount, channelIndex);
  44946. } break;
  44947. }
  44948. }
  44949. MA_API void ma_channel_map_init_standard(ma_standard_channel_map standardChannelMap, ma_channel* pChannelMap, size_t channelMapCap, ma_uint32 channels)
  44950. {
  44951. ma_uint32 iChannel;
  44952. if (pChannelMap == NULL || channelMapCap == 0 || channels == 0) {
  44953. return;
  44954. }
  44955. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  44956. if (channelMapCap == 0) {
  44957. break; /* Ran out of room. */
  44958. }
  44959. pChannelMap[0] = ma_channel_map_init_standard_channel(standardChannelMap, channels, iChannel);
  44960. pChannelMap += 1;
  44961. channelMapCap -= 1;
  44962. }
  44963. }
  44964. MA_API void ma_channel_map_copy(ma_channel* pOut, const ma_channel* pIn, ma_uint32 channels)
  44965. {
  44966. if (pOut != NULL && pIn != NULL && channels > 0) {
  44967. MA_COPY_MEMORY(pOut, pIn, sizeof(*pOut) * channels);
  44968. }
  44969. }
  44970. MA_API void ma_channel_map_copy_or_default(ma_channel* pOut, size_t channelMapCapOut, const ma_channel* pIn, ma_uint32 channels)
  44971. {
  44972. if (pOut == NULL || channels == 0) {
  44973. return;
  44974. }
  44975. if (pIn != NULL) {
  44976. ma_channel_map_copy(pOut, pIn, channels);
  44977. } else {
  44978. ma_channel_map_init_standard(ma_standard_channel_map_default, pOut, channelMapCapOut, channels);
  44979. }
  44980. }
  44981. MA_API ma_bool32 ma_channel_map_is_valid(const ma_channel* pChannelMap, ma_uint32 channels)
  44982. {
  44983. /* A channel count of 0 is invalid. */
  44984. if (channels == 0) {
  44985. return MA_FALSE;
  44986. }
  44987. /* It does not make sense to have a mono channel when there is more than 1 channel. */
  44988. if (channels > 1) {
  44989. ma_uint32 iChannel;
  44990. for (iChannel = 0; iChannel < channels; ++iChannel) {
  44991. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == MA_CHANNEL_MONO) {
  44992. return MA_FALSE;
  44993. }
  44994. }
  44995. }
  44996. return MA_TRUE;
  44997. }
  44998. MA_API ma_bool32 ma_channel_map_is_equal(const ma_channel* pChannelMapA, const ma_channel* pChannelMapB, ma_uint32 channels)
  44999. {
  45000. ma_uint32 iChannel;
  45001. if (pChannelMapA == pChannelMapB) {
  45002. return MA_TRUE;
  45003. }
  45004. for (iChannel = 0; iChannel < channels; ++iChannel) {
  45005. if (ma_channel_map_get_channel(pChannelMapA, channels, iChannel) != ma_channel_map_get_channel(pChannelMapB, channels, iChannel)) {
  45006. return MA_FALSE;
  45007. }
  45008. }
  45009. return MA_TRUE;
  45010. }
  45011. MA_API ma_bool32 ma_channel_map_is_blank(const ma_channel* pChannelMap, ma_uint32 channels)
  45012. {
  45013. ma_uint32 iChannel;
  45014. /* A null channel map is equivalent to the default channel map. */
  45015. if (pChannelMap == NULL) {
  45016. return MA_FALSE;
  45017. }
  45018. for (iChannel = 0; iChannel < channels; ++iChannel) {
  45019. if (pChannelMap[iChannel] != MA_CHANNEL_NONE) {
  45020. return MA_FALSE;
  45021. }
  45022. }
  45023. return MA_TRUE;
  45024. }
  45025. MA_API ma_bool32 ma_channel_map_contains_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition)
  45026. {
  45027. return ma_channel_map_find_channel_position(channels, pChannelMap, channelPosition, NULL);
  45028. }
  45029. MA_API ma_bool32 ma_channel_map_find_channel_position(ma_uint32 channels, const ma_channel* pChannelMap, ma_channel channelPosition, ma_uint32* pChannelIndex)
  45030. {
  45031. ma_uint32 iChannel;
  45032. if (pChannelIndex != NULL) {
  45033. *pChannelIndex = (ma_uint32)-1;
  45034. }
  45035. for (iChannel = 0; iChannel < channels; ++iChannel) {
  45036. if (ma_channel_map_get_channel(pChannelMap, channels, iChannel) == channelPosition) {
  45037. if (pChannelIndex != NULL) {
  45038. *pChannelIndex = iChannel;
  45039. }
  45040. return MA_TRUE;
  45041. }
  45042. }
  45043. /* Getting here means the channel position was not found. */
  45044. return MA_FALSE;
  45045. }
  45046. MA_API size_t ma_channel_map_to_string(const ma_channel* pChannelMap, ma_uint32 channels, char* pBufferOut, size_t bufferCap)
  45047. {
  45048. size_t len;
  45049. ma_uint32 iChannel;
  45050. len = 0;
  45051. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  45052. const char* pChannelStr = ma_channel_position_to_string(ma_channel_map_get_channel(pChannelMap, channels, iChannel));
  45053. size_t channelStrLen = strlen(pChannelStr);
  45054. /* Append the string if necessary. */
  45055. if (pBufferOut != NULL && bufferCap > len + channelStrLen) {
  45056. MA_COPY_MEMORY(pBufferOut + len, pChannelStr, channelStrLen);
  45057. }
  45058. len += channelStrLen;
  45059. /* Append a space if it's not the last item. */
  45060. if (iChannel+1 < channels) {
  45061. if (pBufferOut != NULL && bufferCap > len + 1) {
  45062. pBufferOut[len] = ' ';
  45063. }
  45064. len += 1;
  45065. }
  45066. }
  45067. /* Null terminate. Don't increment the length here. */
  45068. if (pBufferOut != NULL && bufferCap > len + 1) {
  45069. pBufferOut[len] = '\0';
  45070. }
  45071. return len;
  45072. }
  45073. MA_API const char* ma_channel_position_to_string(ma_channel channel)
  45074. {
  45075. switch (channel)
  45076. {
  45077. case MA_CHANNEL_NONE : return "CHANNEL_NONE";
  45078. case MA_CHANNEL_MONO : return "CHANNEL_MONO";
  45079. case MA_CHANNEL_FRONT_LEFT : return "CHANNEL_FRONT_LEFT";
  45080. case MA_CHANNEL_FRONT_RIGHT : return "CHANNEL_FRONT_RIGHT";
  45081. case MA_CHANNEL_FRONT_CENTER : return "CHANNEL_FRONT_CENTER";
  45082. case MA_CHANNEL_LFE : return "CHANNEL_LFE";
  45083. case MA_CHANNEL_BACK_LEFT : return "CHANNEL_BACK_LEFT";
  45084. case MA_CHANNEL_BACK_RIGHT : return "CHANNEL_BACK_RIGHT";
  45085. case MA_CHANNEL_FRONT_LEFT_CENTER : return "CHANNEL_FRONT_LEFT_CENTER ";
  45086. case MA_CHANNEL_FRONT_RIGHT_CENTER: return "CHANNEL_FRONT_RIGHT_CENTER";
  45087. case MA_CHANNEL_BACK_CENTER : return "CHANNEL_BACK_CENTER";
  45088. case MA_CHANNEL_SIDE_LEFT : return "CHANNEL_SIDE_LEFT";
  45089. case MA_CHANNEL_SIDE_RIGHT : return "CHANNEL_SIDE_RIGHT";
  45090. case MA_CHANNEL_TOP_CENTER : return "CHANNEL_TOP_CENTER";
  45091. case MA_CHANNEL_TOP_FRONT_LEFT : return "CHANNEL_TOP_FRONT_LEFT";
  45092. case MA_CHANNEL_TOP_FRONT_CENTER : return "CHANNEL_TOP_FRONT_CENTER";
  45093. case MA_CHANNEL_TOP_FRONT_RIGHT : return "CHANNEL_TOP_FRONT_RIGHT";
  45094. case MA_CHANNEL_TOP_BACK_LEFT : return "CHANNEL_TOP_BACK_LEFT";
  45095. case MA_CHANNEL_TOP_BACK_CENTER : return "CHANNEL_TOP_BACK_CENTER";
  45096. case MA_CHANNEL_TOP_BACK_RIGHT : return "CHANNEL_TOP_BACK_RIGHT";
  45097. case MA_CHANNEL_AUX_0 : return "CHANNEL_AUX_0";
  45098. case MA_CHANNEL_AUX_1 : return "CHANNEL_AUX_1";
  45099. case MA_CHANNEL_AUX_2 : return "CHANNEL_AUX_2";
  45100. case MA_CHANNEL_AUX_3 : return "CHANNEL_AUX_3";
  45101. case MA_CHANNEL_AUX_4 : return "CHANNEL_AUX_4";
  45102. case MA_CHANNEL_AUX_5 : return "CHANNEL_AUX_5";
  45103. case MA_CHANNEL_AUX_6 : return "CHANNEL_AUX_6";
  45104. case MA_CHANNEL_AUX_7 : return "CHANNEL_AUX_7";
  45105. case MA_CHANNEL_AUX_8 : return "CHANNEL_AUX_8";
  45106. case MA_CHANNEL_AUX_9 : return "CHANNEL_AUX_9";
  45107. case MA_CHANNEL_AUX_10 : return "CHANNEL_AUX_10";
  45108. case MA_CHANNEL_AUX_11 : return "CHANNEL_AUX_11";
  45109. case MA_CHANNEL_AUX_12 : return "CHANNEL_AUX_12";
  45110. case MA_CHANNEL_AUX_13 : return "CHANNEL_AUX_13";
  45111. case MA_CHANNEL_AUX_14 : return "CHANNEL_AUX_14";
  45112. case MA_CHANNEL_AUX_15 : return "CHANNEL_AUX_15";
  45113. case MA_CHANNEL_AUX_16 : return "CHANNEL_AUX_16";
  45114. case MA_CHANNEL_AUX_17 : return "CHANNEL_AUX_17";
  45115. case MA_CHANNEL_AUX_18 : return "CHANNEL_AUX_18";
  45116. case MA_CHANNEL_AUX_19 : return "CHANNEL_AUX_19";
  45117. case MA_CHANNEL_AUX_20 : return "CHANNEL_AUX_20";
  45118. case MA_CHANNEL_AUX_21 : return "CHANNEL_AUX_21";
  45119. case MA_CHANNEL_AUX_22 : return "CHANNEL_AUX_22";
  45120. case MA_CHANNEL_AUX_23 : return "CHANNEL_AUX_23";
  45121. case MA_CHANNEL_AUX_24 : return "CHANNEL_AUX_24";
  45122. case MA_CHANNEL_AUX_25 : return "CHANNEL_AUX_25";
  45123. case MA_CHANNEL_AUX_26 : return "CHANNEL_AUX_26";
  45124. case MA_CHANNEL_AUX_27 : return "CHANNEL_AUX_27";
  45125. case MA_CHANNEL_AUX_28 : return "CHANNEL_AUX_28";
  45126. case MA_CHANNEL_AUX_29 : return "CHANNEL_AUX_29";
  45127. case MA_CHANNEL_AUX_30 : return "CHANNEL_AUX_30";
  45128. case MA_CHANNEL_AUX_31 : return "CHANNEL_AUX_31";
  45129. default: break;
  45130. }
  45131. return "UNKNOWN";
  45132. }
  45133. /**************************************************************************************************************************************************************
  45134. Conversion Helpers
  45135. **************************************************************************************************************************************************************/
  45136. 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)
  45137. {
  45138. ma_data_converter_config config;
  45139. config = ma_data_converter_config_init(formatIn, formatOut, channelsIn, channelsOut, sampleRateIn, sampleRateOut);
  45140. config.resampling.linear.lpfOrder = ma_min(MA_DEFAULT_RESAMPLER_LPF_ORDER, MA_MAX_FILTER_ORDER);
  45141. return ma_convert_frames_ex(pOut, frameCountOut, pIn, frameCountIn, &config);
  45142. }
  45143. 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)
  45144. {
  45145. ma_result result;
  45146. ma_data_converter converter;
  45147. if (frameCountIn == 0 || pConfig == NULL) {
  45148. return 0;
  45149. }
  45150. result = ma_data_converter_init(pConfig, NULL, &converter);
  45151. if (result != MA_SUCCESS) {
  45152. return 0; /* Failed to initialize the data converter. */
  45153. }
  45154. if (pOut == NULL) {
  45155. result = ma_data_converter_get_expected_output_frame_count(&converter, frameCountIn, &frameCountOut);
  45156. if (result != MA_SUCCESS) {
  45157. if (result == MA_NOT_IMPLEMENTED) {
  45158. /* No way to calculate the number of frames, so we'll need to brute force it and loop. */
  45159. frameCountOut = 0;
  45160. while (frameCountIn > 0) {
  45161. ma_uint64 framesProcessedIn = frameCountIn;
  45162. ma_uint64 framesProcessedOut = 0xFFFFFFFF;
  45163. result = ma_data_converter_process_pcm_frames(&converter, pIn, &framesProcessedIn, NULL, &framesProcessedOut);
  45164. if (result != MA_SUCCESS) {
  45165. break;
  45166. }
  45167. frameCountIn -= framesProcessedIn;
  45168. }
  45169. }
  45170. }
  45171. } else {
  45172. result = ma_data_converter_process_pcm_frames(&converter, pIn, &frameCountIn, pOut, &frameCountOut);
  45173. if (result != MA_SUCCESS) {
  45174. frameCountOut = 0;
  45175. }
  45176. }
  45177. ma_data_converter_uninit(&converter, NULL);
  45178. return frameCountOut;
  45179. }
  45180. /**************************************************************************************************************************************************************
  45181. Ring Buffer
  45182. **************************************************************************************************************************************************************/
  45183. static MA_INLINE ma_uint32 ma_rb__extract_offset_in_bytes(ma_uint32 encodedOffset)
  45184. {
  45185. return encodedOffset & 0x7FFFFFFF;
  45186. }
  45187. static MA_INLINE ma_uint32 ma_rb__extract_offset_loop_flag(ma_uint32 encodedOffset)
  45188. {
  45189. return encodedOffset & 0x80000000;
  45190. }
  45191. static MA_INLINE void* ma_rb__get_read_ptr(ma_rb* pRB)
  45192. {
  45193. MA_ASSERT(pRB != NULL);
  45194. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(c89atomic_load_32(&pRB->encodedReadOffset)));
  45195. }
  45196. static MA_INLINE void* ma_rb__get_write_ptr(ma_rb* pRB)
  45197. {
  45198. MA_ASSERT(pRB != NULL);
  45199. return ma_offset_ptr(pRB->pBuffer, ma_rb__extract_offset_in_bytes(c89atomic_load_32(&pRB->encodedWriteOffset)));
  45200. }
  45201. static MA_INLINE ma_uint32 ma_rb__construct_offset(ma_uint32 offsetInBytes, ma_uint32 offsetLoopFlag)
  45202. {
  45203. return offsetLoopFlag | offsetInBytes;
  45204. }
  45205. static MA_INLINE void ma_rb__deconstruct_offset(ma_uint32 encodedOffset, ma_uint32* pOffsetInBytes, ma_uint32* pOffsetLoopFlag)
  45206. {
  45207. MA_ASSERT(pOffsetInBytes != NULL);
  45208. MA_ASSERT(pOffsetLoopFlag != NULL);
  45209. *pOffsetInBytes = ma_rb__extract_offset_in_bytes(encodedOffset);
  45210. *pOffsetLoopFlag = ma_rb__extract_offset_loop_flag(encodedOffset);
  45211. }
  45212. 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)
  45213. {
  45214. ma_result result;
  45215. const ma_uint32 maxSubBufferSize = 0x7FFFFFFF - (MA_SIMD_ALIGNMENT-1);
  45216. if (pRB == NULL) {
  45217. return MA_INVALID_ARGS;
  45218. }
  45219. if (subbufferSizeInBytes == 0 || subbufferCount == 0) {
  45220. return MA_INVALID_ARGS;
  45221. }
  45222. if (subbufferSizeInBytes > maxSubBufferSize) {
  45223. return MA_INVALID_ARGS; /* Maximum buffer size is ~2GB. The most significant bit is a flag for use internally. */
  45224. }
  45225. MA_ZERO_OBJECT(pRB);
  45226. result = ma_allocation_callbacks_init_copy(&pRB->allocationCallbacks, pAllocationCallbacks);
  45227. if (result != MA_SUCCESS) {
  45228. return result;
  45229. }
  45230. pRB->subbufferSizeInBytes = (ma_uint32)subbufferSizeInBytes;
  45231. pRB->subbufferCount = (ma_uint32)subbufferCount;
  45232. if (pOptionalPreallocatedBuffer != NULL) {
  45233. pRB->subbufferStrideInBytes = (ma_uint32)subbufferStrideInBytes;
  45234. pRB->pBuffer = pOptionalPreallocatedBuffer;
  45235. } else {
  45236. size_t bufferSizeInBytes;
  45237. /*
  45238. 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
  45239. we need to make sure the stride is a multiple of MA_SIMD_ALIGNMENT.
  45240. */
  45241. pRB->subbufferStrideInBytes = (pRB->subbufferSizeInBytes + (MA_SIMD_ALIGNMENT-1)) & ~MA_SIMD_ALIGNMENT;
  45242. bufferSizeInBytes = (size_t)pRB->subbufferCount*pRB->subbufferStrideInBytes;
  45243. pRB->pBuffer = ma_aligned_malloc(bufferSizeInBytes, MA_SIMD_ALIGNMENT, &pRB->allocationCallbacks);
  45244. if (pRB->pBuffer == NULL) {
  45245. return MA_OUT_OF_MEMORY;
  45246. }
  45247. MA_ZERO_MEMORY(pRB->pBuffer, bufferSizeInBytes);
  45248. pRB->ownsBuffer = MA_TRUE;
  45249. }
  45250. return MA_SUCCESS;
  45251. }
  45252. MA_API ma_result ma_rb_init(size_t bufferSizeInBytes, void* pOptionalPreallocatedBuffer, const ma_allocation_callbacks* pAllocationCallbacks, ma_rb* pRB)
  45253. {
  45254. return ma_rb_init_ex(bufferSizeInBytes, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  45255. }
  45256. MA_API void ma_rb_uninit(ma_rb* pRB)
  45257. {
  45258. if (pRB == NULL) {
  45259. return;
  45260. }
  45261. if (pRB->ownsBuffer) {
  45262. ma_aligned_free(pRB->pBuffer, &pRB->allocationCallbacks);
  45263. }
  45264. }
  45265. MA_API void ma_rb_reset(ma_rb* pRB)
  45266. {
  45267. if (pRB == NULL) {
  45268. return;
  45269. }
  45270. c89atomic_exchange_32(&pRB->encodedReadOffset, 0);
  45271. c89atomic_exchange_32(&pRB->encodedWriteOffset, 0);
  45272. }
  45273. MA_API ma_result ma_rb_acquire_read(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  45274. {
  45275. ma_uint32 writeOffset;
  45276. ma_uint32 writeOffsetInBytes;
  45277. ma_uint32 writeOffsetLoopFlag;
  45278. ma_uint32 readOffset;
  45279. ma_uint32 readOffsetInBytes;
  45280. ma_uint32 readOffsetLoopFlag;
  45281. size_t bytesAvailable;
  45282. size_t bytesRequested;
  45283. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  45284. return MA_INVALID_ARGS;
  45285. }
  45286. /* The returned buffer should never move ahead of the write pointer. */
  45287. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45288. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45289. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45290. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45291. /*
  45292. The number of bytes available depends on whether or not the read and write pointers are on the same loop iteration. If so, we
  45293. can only read up to the write pointer. If not, we can only read up to the end of the buffer.
  45294. */
  45295. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  45296. bytesAvailable = writeOffsetInBytes - readOffsetInBytes;
  45297. } else {
  45298. bytesAvailable = pRB->subbufferSizeInBytes - readOffsetInBytes;
  45299. }
  45300. bytesRequested = *pSizeInBytes;
  45301. if (bytesRequested > bytesAvailable) {
  45302. bytesRequested = bytesAvailable;
  45303. }
  45304. *pSizeInBytes = bytesRequested;
  45305. (*ppBufferOut) = ma_rb__get_read_ptr(pRB);
  45306. return MA_SUCCESS;
  45307. }
  45308. MA_API ma_result ma_rb_commit_read(ma_rb* pRB, size_t sizeInBytes)
  45309. {
  45310. ma_uint32 readOffset;
  45311. ma_uint32 readOffsetInBytes;
  45312. ma_uint32 readOffsetLoopFlag;
  45313. ma_uint32 newReadOffsetInBytes;
  45314. ma_uint32 newReadOffsetLoopFlag;
  45315. if (pRB == NULL) {
  45316. return MA_INVALID_ARGS;
  45317. }
  45318. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45319. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45320. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  45321. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + sizeInBytes);
  45322. if (newReadOffsetInBytes > pRB->subbufferSizeInBytes) {
  45323. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  45324. }
  45325. /* Move the read pointer back to the start if necessary. */
  45326. newReadOffsetLoopFlag = readOffsetLoopFlag;
  45327. if (newReadOffsetInBytes == pRB->subbufferSizeInBytes) {
  45328. newReadOffsetInBytes = 0;
  45329. newReadOffsetLoopFlag ^= 0x80000000;
  45330. }
  45331. c89atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetLoopFlag, newReadOffsetInBytes));
  45332. if (ma_rb_pointer_distance(pRB) == 0) {
  45333. return MA_AT_END;
  45334. } else {
  45335. return MA_SUCCESS;
  45336. }
  45337. }
  45338. MA_API ma_result ma_rb_acquire_write(ma_rb* pRB, size_t* pSizeInBytes, void** ppBufferOut)
  45339. {
  45340. ma_uint32 readOffset;
  45341. ma_uint32 readOffsetInBytes;
  45342. ma_uint32 readOffsetLoopFlag;
  45343. ma_uint32 writeOffset;
  45344. ma_uint32 writeOffsetInBytes;
  45345. ma_uint32 writeOffsetLoopFlag;
  45346. size_t bytesAvailable;
  45347. size_t bytesRequested;
  45348. if (pRB == NULL || pSizeInBytes == NULL || ppBufferOut == NULL) {
  45349. return MA_INVALID_ARGS;
  45350. }
  45351. /* The returned buffer should never overtake the read buffer. */
  45352. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45353. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45354. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45355. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45356. /*
  45357. In the case of writing, if the write pointer and the read pointer are on the same loop iteration we can only
  45358. write up to the end of the buffer. Otherwise we can only write up to the read pointer. The write pointer should
  45359. never overtake the read pointer.
  45360. */
  45361. if (writeOffsetLoopFlag == readOffsetLoopFlag) {
  45362. bytesAvailable = pRB->subbufferSizeInBytes - writeOffsetInBytes;
  45363. } else {
  45364. bytesAvailable = readOffsetInBytes - writeOffsetInBytes;
  45365. }
  45366. bytesRequested = *pSizeInBytes;
  45367. if (bytesRequested > bytesAvailable) {
  45368. bytesRequested = bytesAvailable;
  45369. }
  45370. *pSizeInBytes = bytesRequested;
  45371. *ppBufferOut = ma_rb__get_write_ptr(pRB);
  45372. /* Clear the buffer if desired. */
  45373. if (pRB->clearOnWriteAcquire) {
  45374. MA_ZERO_MEMORY(*ppBufferOut, *pSizeInBytes);
  45375. }
  45376. return MA_SUCCESS;
  45377. }
  45378. MA_API ma_result ma_rb_commit_write(ma_rb* pRB, size_t sizeInBytes)
  45379. {
  45380. ma_uint32 writeOffset;
  45381. ma_uint32 writeOffsetInBytes;
  45382. ma_uint32 writeOffsetLoopFlag;
  45383. ma_uint32 newWriteOffsetInBytes;
  45384. ma_uint32 newWriteOffsetLoopFlag;
  45385. if (pRB == NULL) {
  45386. return MA_INVALID_ARGS;
  45387. }
  45388. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45389. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45390. /* Check that sizeInBytes is correct. It should never go beyond the end of the buffer. */
  45391. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + sizeInBytes);
  45392. if (newWriteOffsetInBytes > pRB->subbufferSizeInBytes) {
  45393. return MA_INVALID_ARGS; /* <-- sizeInBytes will cause the read offset to overflow. */
  45394. }
  45395. /* Move the read pointer back to the start if necessary. */
  45396. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  45397. if (newWriteOffsetInBytes == pRB->subbufferSizeInBytes) {
  45398. newWriteOffsetInBytes = 0;
  45399. newWriteOffsetLoopFlag ^= 0x80000000;
  45400. }
  45401. c89atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetLoopFlag, newWriteOffsetInBytes));
  45402. if (ma_rb_pointer_distance(pRB) == 0) {
  45403. return MA_AT_END;
  45404. } else {
  45405. return MA_SUCCESS;
  45406. }
  45407. }
  45408. MA_API ma_result ma_rb_seek_read(ma_rb* pRB, size_t offsetInBytes)
  45409. {
  45410. ma_uint32 readOffset;
  45411. ma_uint32 readOffsetInBytes;
  45412. ma_uint32 readOffsetLoopFlag;
  45413. ma_uint32 writeOffset;
  45414. ma_uint32 writeOffsetInBytes;
  45415. ma_uint32 writeOffsetLoopFlag;
  45416. ma_uint32 newReadOffsetInBytes;
  45417. ma_uint32 newReadOffsetLoopFlag;
  45418. if (pRB == NULL || offsetInBytes > pRB->subbufferSizeInBytes) {
  45419. return MA_INVALID_ARGS;
  45420. }
  45421. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45422. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45423. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45424. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45425. newReadOffsetLoopFlag = readOffsetLoopFlag;
  45426. /* We cannot go past the write buffer. */
  45427. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  45428. if ((readOffsetInBytes + offsetInBytes) > writeOffsetInBytes) {
  45429. newReadOffsetInBytes = writeOffsetInBytes;
  45430. } else {
  45431. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  45432. }
  45433. } else {
  45434. /* May end up looping. */
  45435. if ((readOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  45436. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  45437. newReadOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  45438. } else {
  45439. newReadOffsetInBytes = (ma_uint32)(readOffsetInBytes + offsetInBytes);
  45440. }
  45441. }
  45442. c89atomic_exchange_32(&pRB->encodedReadOffset, ma_rb__construct_offset(newReadOffsetInBytes, newReadOffsetLoopFlag));
  45443. return MA_SUCCESS;
  45444. }
  45445. MA_API ma_result ma_rb_seek_write(ma_rb* pRB, size_t offsetInBytes)
  45446. {
  45447. ma_uint32 readOffset;
  45448. ma_uint32 readOffsetInBytes;
  45449. ma_uint32 readOffsetLoopFlag;
  45450. ma_uint32 writeOffset;
  45451. ma_uint32 writeOffsetInBytes;
  45452. ma_uint32 writeOffsetLoopFlag;
  45453. ma_uint32 newWriteOffsetInBytes;
  45454. ma_uint32 newWriteOffsetLoopFlag;
  45455. if (pRB == NULL) {
  45456. return MA_INVALID_ARGS;
  45457. }
  45458. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45459. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45460. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45461. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45462. newWriteOffsetLoopFlag = writeOffsetLoopFlag;
  45463. /* We cannot go past the write buffer. */
  45464. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  45465. /* May end up looping. */
  45466. if ((writeOffsetInBytes + offsetInBytes) >= pRB->subbufferSizeInBytes) {
  45467. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes) - pRB->subbufferSizeInBytes;
  45468. newWriteOffsetLoopFlag ^= 0x80000000; /* <-- Looped. */
  45469. } else {
  45470. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  45471. }
  45472. } else {
  45473. if ((writeOffsetInBytes + offsetInBytes) > readOffsetInBytes) {
  45474. newWriteOffsetInBytes = readOffsetInBytes;
  45475. } else {
  45476. newWriteOffsetInBytes = (ma_uint32)(writeOffsetInBytes + offsetInBytes);
  45477. }
  45478. }
  45479. c89atomic_exchange_32(&pRB->encodedWriteOffset, ma_rb__construct_offset(newWriteOffsetInBytes, newWriteOffsetLoopFlag));
  45480. return MA_SUCCESS;
  45481. }
  45482. MA_API ma_int32 ma_rb_pointer_distance(ma_rb* pRB)
  45483. {
  45484. ma_uint32 readOffset;
  45485. ma_uint32 readOffsetInBytes;
  45486. ma_uint32 readOffsetLoopFlag;
  45487. ma_uint32 writeOffset;
  45488. ma_uint32 writeOffsetInBytes;
  45489. ma_uint32 writeOffsetLoopFlag;
  45490. if (pRB == NULL) {
  45491. return 0;
  45492. }
  45493. readOffset = c89atomic_load_32(&pRB->encodedReadOffset);
  45494. ma_rb__deconstruct_offset(readOffset, &readOffsetInBytes, &readOffsetLoopFlag);
  45495. writeOffset = c89atomic_load_32(&pRB->encodedWriteOffset);
  45496. ma_rb__deconstruct_offset(writeOffset, &writeOffsetInBytes, &writeOffsetLoopFlag);
  45497. if (readOffsetLoopFlag == writeOffsetLoopFlag) {
  45498. return writeOffsetInBytes - readOffsetInBytes;
  45499. } else {
  45500. return writeOffsetInBytes + (pRB->subbufferSizeInBytes - readOffsetInBytes);
  45501. }
  45502. }
  45503. MA_API ma_uint32 ma_rb_available_read(ma_rb* pRB)
  45504. {
  45505. ma_int32 dist;
  45506. if (pRB == NULL) {
  45507. return 0;
  45508. }
  45509. dist = ma_rb_pointer_distance(pRB);
  45510. if (dist < 0) {
  45511. return 0;
  45512. }
  45513. return dist;
  45514. }
  45515. MA_API ma_uint32 ma_rb_available_write(ma_rb* pRB)
  45516. {
  45517. if (pRB == NULL) {
  45518. return 0;
  45519. }
  45520. return (ma_uint32)(ma_rb_get_subbuffer_size(pRB) - ma_rb_pointer_distance(pRB));
  45521. }
  45522. MA_API size_t ma_rb_get_subbuffer_size(ma_rb* pRB)
  45523. {
  45524. if (pRB == NULL) {
  45525. return 0;
  45526. }
  45527. return pRB->subbufferSizeInBytes;
  45528. }
  45529. MA_API size_t ma_rb_get_subbuffer_stride(ma_rb* pRB)
  45530. {
  45531. if (pRB == NULL) {
  45532. return 0;
  45533. }
  45534. if (pRB->subbufferStrideInBytes == 0) {
  45535. return (size_t)pRB->subbufferSizeInBytes;
  45536. }
  45537. return (size_t)pRB->subbufferStrideInBytes;
  45538. }
  45539. MA_API size_t ma_rb_get_subbuffer_offset(ma_rb* pRB, size_t subbufferIndex)
  45540. {
  45541. if (pRB == NULL) {
  45542. return 0;
  45543. }
  45544. return subbufferIndex * ma_rb_get_subbuffer_stride(pRB);
  45545. }
  45546. MA_API void* ma_rb_get_subbuffer_ptr(ma_rb* pRB, size_t subbufferIndex, void* pBuffer)
  45547. {
  45548. if (pRB == NULL) {
  45549. return NULL;
  45550. }
  45551. return ma_offset_ptr(pBuffer, ma_rb_get_subbuffer_offset(pRB, subbufferIndex));
  45552. }
  45553. static MA_INLINE ma_uint32 ma_pcm_rb_get_bpf(ma_pcm_rb* pRB)
  45554. {
  45555. MA_ASSERT(pRB != NULL);
  45556. return ma_get_bytes_per_frame(pRB->format, pRB->channels);
  45557. }
  45558. 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)
  45559. {
  45560. ma_uint32 bpf;
  45561. ma_result result;
  45562. if (pRB == NULL) {
  45563. return MA_INVALID_ARGS;
  45564. }
  45565. MA_ZERO_OBJECT(pRB);
  45566. bpf = ma_get_bytes_per_frame(format, channels);
  45567. if (bpf == 0) {
  45568. return MA_INVALID_ARGS;
  45569. }
  45570. result = ma_rb_init_ex(subbufferSizeInFrames*bpf, subbufferCount, subbufferStrideInFrames*bpf, pOptionalPreallocatedBuffer, pAllocationCallbacks, &pRB->rb);
  45571. if (result != MA_SUCCESS) {
  45572. return result;
  45573. }
  45574. pRB->format = format;
  45575. pRB->channels = channels;
  45576. return MA_SUCCESS;
  45577. }
  45578. 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)
  45579. {
  45580. return ma_pcm_rb_init_ex(format, channels, bufferSizeInFrames, 1, 0, pOptionalPreallocatedBuffer, pAllocationCallbacks, pRB);
  45581. }
  45582. MA_API void ma_pcm_rb_uninit(ma_pcm_rb* pRB)
  45583. {
  45584. if (pRB == NULL) {
  45585. return;
  45586. }
  45587. ma_rb_uninit(&pRB->rb);
  45588. }
  45589. MA_API void ma_pcm_rb_reset(ma_pcm_rb* pRB)
  45590. {
  45591. if (pRB == NULL) {
  45592. return;
  45593. }
  45594. ma_rb_reset(&pRB->rb);
  45595. }
  45596. MA_API ma_result ma_pcm_rb_acquire_read(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  45597. {
  45598. size_t sizeInBytes;
  45599. ma_result result;
  45600. if (pRB == NULL || pSizeInFrames == NULL) {
  45601. return MA_INVALID_ARGS;
  45602. }
  45603. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  45604. result = ma_rb_acquire_read(&pRB->rb, &sizeInBytes, ppBufferOut);
  45605. if (result != MA_SUCCESS) {
  45606. return result;
  45607. }
  45608. *pSizeInFrames = (ma_uint32)(sizeInBytes / (size_t)ma_pcm_rb_get_bpf(pRB));
  45609. return MA_SUCCESS;
  45610. }
  45611. MA_API ma_result ma_pcm_rb_commit_read(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  45612. {
  45613. if (pRB == NULL) {
  45614. return MA_INVALID_ARGS;
  45615. }
  45616. return ma_rb_commit_read(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  45617. }
  45618. MA_API ma_result ma_pcm_rb_acquire_write(ma_pcm_rb* pRB, ma_uint32* pSizeInFrames, void** ppBufferOut)
  45619. {
  45620. size_t sizeInBytes;
  45621. ma_result result;
  45622. if (pRB == NULL) {
  45623. return MA_INVALID_ARGS;
  45624. }
  45625. sizeInBytes = *pSizeInFrames * ma_pcm_rb_get_bpf(pRB);
  45626. result = ma_rb_acquire_write(&pRB->rb, &sizeInBytes, ppBufferOut);
  45627. if (result != MA_SUCCESS) {
  45628. return result;
  45629. }
  45630. *pSizeInFrames = (ma_uint32)(sizeInBytes / ma_pcm_rb_get_bpf(pRB));
  45631. return MA_SUCCESS;
  45632. }
  45633. MA_API ma_result ma_pcm_rb_commit_write(ma_pcm_rb* pRB, ma_uint32 sizeInFrames)
  45634. {
  45635. if (pRB == NULL) {
  45636. return MA_INVALID_ARGS;
  45637. }
  45638. return ma_rb_commit_write(&pRB->rb, sizeInFrames * ma_pcm_rb_get_bpf(pRB));
  45639. }
  45640. MA_API ma_result ma_pcm_rb_seek_read(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  45641. {
  45642. if (pRB == NULL) {
  45643. return MA_INVALID_ARGS;
  45644. }
  45645. return ma_rb_seek_read(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  45646. }
  45647. MA_API ma_result ma_pcm_rb_seek_write(ma_pcm_rb* pRB, ma_uint32 offsetInFrames)
  45648. {
  45649. if (pRB == NULL) {
  45650. return MA_INVALID_ARGS;
  45651. }
  45652. return ma_rb_seek_write(&pRB->rb, offsetInFrames * ma_pcm_rb_get_bpf(pRB));
  45653. }
  45654. MA_API ma_int32 ma_pcm_rb_pointer_distance(ma_pcm_rb* pRB)
  45655. {
  45656. if (pRB == NULL) {
  45657. return 0;
  45658. }
  45659. return ma_rb_pointer_distance(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  45660. }
  45661. MA_API ma_uint32 ma_pcm_rb_available_read(ma_pcm_rb* pRB)
  45662. {
  45663. if (pRB == NULL) {
  45664. return 0;
  45665. }
  45666. return ma_rb_available_read(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  45667. }
  45668. MA_API ma_uint32 ma_pcm_rb_available_write(ma_pcm_rb* pRB)
  45669. {
  45670. if (pRB == NULL) {
  45671. return 0;
  45672. }
  45673. return ma_rb_available_write(&pRB->rb) / ma_pcm_rb_get_bpf(pRB);
  45674. }
  45675. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_size(ma_pcm_rb* pRB)
  45676. {
  45677. if (pRB == NULL) {
  45678. return 0;
  45679. }
  45680. return (ma_uint32)(ma_rb_get_subbuffer_size(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  45681. }
  45682. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_stride(ma_pcm_rb* pRB)
  45683. {
  45684. if (pRB == NULL) {
  45685. return 0;
  45686. }
  45687. return (ma_uint32)(ma_rb_get_subbuffer_stride(&pRB->rb) / ma_pcm_rb_get_bpf(pRB));
  45688. }
  45689. MA_API ma_uint32 ma_pcm_rb_get_subbuffer_offset(ma_pcm_rb* pRB, ma_uint32 subbufferIndex)
  45690. {
  45691. if (pRB == NULL) {
  45692. return 0;
  45693. }
  45694. return (ma_uint32)(ma_rb_get_subbuffer_offset(&pRB->rb, subbufferIndex) / ma_pcm_rb_get_bpf(pRB));
  45695. }
  45696. MA_API void* ma_pcm_rb_get_subbuffer_ptr(ma_pcm_rb* pRB, ma_uint32 subbufferIndex, void* pBuffer)
  45697. {
  45698. if (pRB == NULL) {
  45699. return NULL;
  45700. }
  45701. return ma_rb_get_subbuffer_ptr(&pRB->rb, subbufferIndex, pBuffer);
  45702. }
  45703. 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)
  45704. {
  45705. ma_result result;
  45706. ma_uint32 sizeInFrames;
  45707. sizeInFrames = (ma_uint32)ma_calculate_frame_count_after_resampling(sampleRate, captureInternalSampleRate, captureInternalPeriodSizeInFrames * 5);
  45708. if (sizeInFrames == 0) {
  45709. return MA_INVALID_ARGS;
  45710. }
  45711. result = ma_pcm_rb_init(captureFormat, captureChannels, sizeInFrames, NULL, pAllocationCallbacks, &pRB->rb);
  45712. if (result != MA_SUCCESS) {
  45713. return result;
  45714. }
  45715. /* Seek forward a bit so we have a bit of a buffer in case of desyncs. */
  45716. ma_pcm_rb_seek_write((ma_pcm_rb*)pRB, captureInternalPeriodSizeInFrames * 2);
  45717. return MA_SUCCESS;
  45718. }
  45719. MA_API ma_result ma_duplex_rb_uninit(ma_duplex_rb* pRB)
  45720. {
  45721. ma_pcm_rb_uninit((ma_pcm_rb*)pRB);
  45722. return MA_SUCCESS;
  45723. }
  45724. /**************************************************************************************************************************************************************
  45725. Miscellaneous Helpers
  45726. **************************************************************************************************************************************************************/
  45727. MA_API const char* ma_result_description(ma_result result)
  45728. {
  45729. switch (result)
  45730. {
  45731. case MA_SUCCESS: return "No error";
  45732. case MA_ERROR: return "Unknown error";
  45733. case MA_INVALID_ARGS: return "Invalid argument";
  45734. case MA_INVALID_OPERATION: return "Invalid operation";
  45735. case MA_OUT_OF_MEMORY: return "Out of memory";
  45736. case MA_OUT_OF_RANGE: return "Out of range";
  45737. case MA_ACCESS_DENIED: return "Permission denied";
  45738. case MA_DOES_NOT_EXIST: return "Resource does not exist";
  45739. case MA_ALREADY_EXISTS: return "Resource already exists";
  45740. case MA_TOO_MANY_OPEN_FILES: return "Too many open files";
  45741. case MA_INVALID_FILE: return "Invalid file";
  45742. case MA_TOO_BIG: return "Too large";
  45743. case MA_PATH_TOO_LONG: return "Path too long";
  45744. case MA_NAME_TOO_LONG: return "Name too long";
  45745. case MA_NOT_DIRECTORY: return "Not a directory";
  45746. case MA_IS_DIRECTORY: return "Is a directory";
  45747. case MA_DIRECTORY_NOT_EMPTY: return "Directory not empty";
  45748. case MA_AT_END: return "At end";
  45749. case MA_NO_SPACE: return "No space available";
  45750. case MA_BUSY: return "Device or resource busy";
  45751. case MA_IO_ERROR: return "Input/output error";
  45752. case MA_INTERRUPT: return "Interrupted";
  45753. case MA_UNAVAILABLE: return "Resource unavailable";
  45754. case MA_ALREADY_IN_USE: return "Resource already in use";
  45755. case MA_BAD_ADDRESS: return "Bad address";
  45756. case MA_BAD_SEEK: return "Illegal seek";
  45757. case MA_BAD_PIPE: return "Broken pipe";
  45758. case MA_DEADLOCK: return "Deadlock";
  45759. case MA_TOO_MANY_LINKS: return "Too many links";
  45760. case MA_NOT_IMPLEMENTED: return "Not implemented";
  45761. case MA_NO_MESSAGE: return "No message of desired type";
  45762. case MA_BAD_MESSAGE: return "Invalid message";
  45763. case MA_NO_DATA_AVAILABLE: return "No data available";
  45764. case MA_INVALID_DATA: return "Invalid data";
  45765. case MA_TIMEOUT: return "Timeout";
  45766. case MA_NO_NETWORK: return "Network unavailable";
  45767. case MA_NOT_UNIQUE: return "Not unique";
  45768. case MA_NOT_SOCKET: return "Socket operation on non-socket";
  45769. case MA_NO_ADDRESS: return "Destination address required";
  45770. case MA_BAD_PROTOCOL: return "Protocol wrong type for socket";
  45771. case MA_PROTOCOL_UNAVAILABLE: return "Protocol not available";
  45772. case MA_PROTOCOL_NOT_SUPPORTED: return "Protocol not supported";
  45773. case MA_PROTOCOL_FAMILY_NOT_SUPPORTED: return "Protocol family not supported";
  45774. case MA_ADDRESS_FAMILY_NOT_SUPPORTED: return "Address family not supported";
  45775. case MA_SOCKET_NOT_SUPPORTED: return "Socket type not supported";
  45776. case MA_CONNECTION_RESET: return "Connection reset";
  45777. case MA_ALREADY_CONNECTED: return "Already connected";
  45778. case MA_NOT_CONNECTED: return "Not connected";
  45779. case MA_CONNECTION_REFUSED: return "Connection refused";
  45780. case MA_NO_HOST: return "No host";
  45781. case MA_IN_PROGRESS: return "Operation in progress";
  45782. case MA_CANCELLED: return "Operation cancelled";
  45783. case MA_MEMORY_ALREADY_MAPPED: return "Memory already mapped";
  45784. case MA_FORMAT_NOT_SUPPORTED: return "Format not supported";
  45785. case MA_DEVICE_TYPE_NOT_SUPPORTED: return "Device type not supported";
  45786. case MA_SHARE_MODE_NOT_SUPPORTED: return "Share mode not supported";
  45787. case MA_NO_BACKEND: return "No backend";
  45788. case MA_NO_DEVICE: return "No device";
  45789. case MA_API_NOT_FOUND: return "API not found";
  45790. case MA_INVALID_DEVICE_CONFIG: return "Invalid device config";
  45791. case MA_DEVICE_NOT_INITIALIZED: return "Device not initialized";
  45792. case MA_DEVICE_NOT_STARTED: return "Device not started";
  45793. case MA_FAILED_TO_INIT_BACKEND: return "Failed to initialize backend";
  45794. case MA_FAILED_TO_OPEN_BACKEND_DEVICE: return "Failed to open backend device";
  45795. case MA_FAILED_TO_START_BACKEND_DEVICE: return "Failed to start backend device";
  45796. case MA_FAILED_TO_STOP_BACKEND_DEVICE: return "Failed to stop backend device";
  45797. default: return "Unknown error";
  45798. }
  45799. }
  45800. MA_API void* ma_malloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  45801. {
  45802. if (pAllocationCallbacks != NULL) {
  45803. if (pAllocationCallbacks->onMalloc != NULL) {
  45804. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  45805. } else {
  45806. return NULL; /* Do not fall back to the default implementation. */
  45807. }
  45808. } else {
  45809. return ma__malloc_default(sz, NULL);
  45810. }
  45811. }
  45812. MA_API void* ma_calloc(size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  45813. {
  45814. void* p = ma_malloc(sz, pAllocationCallbacks);
  45815. if (p != NULL) {
  45816. MA_ZERO_MEMORY(p, sz);
  45817. }
  45818. return p;
  45819. }
  45820. MA_API void* ma_realloc(void* p, size_t sz, const ma_allocation_callbacks* pAllocationCallbacks)
  45821. {
  45822. if (pAllocationCallbacks != NULL) {
  45823. if (pAllocationCallbacks->onRealloc != NULL) {
  45824. return pAllocationCallbacks->onRealloc(p, sz, pAllocationCallbacks->pUserData);
  45825. } else {
  45826. return NULL; /* Do not fall back to the default implementation. */
  45827. }
  45828. } else {
  45829. return ma__realloc_default(p, sz, NULL);
  45830. }
  45831. }
  45832. MA_API void ma_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  45833. {
  45834. if (p == NULL) {
  45835. return;
  45836. }
  45837. if (pAllocationCallbacks != NULL) {
  45838. if (pAllocationCallbacks->onFree != NULL) {
  45839. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  45840. } else {
  45841. return; /* Do no fall back to the default implementation. */
  45842. }
  45843. } else {
  45844. ma__free_default(p, NULL);
  45845. }
  45846. }
  45847. MA_API void* ma_aligned_malloc(size_t sz, size_t alignment, const ma_allocation_callbacks* pAllocationCallbacks)
  45848. {
  45849. size_t extraBytes;
  45850. void* pUnaligned;
  45851. void* pAligned;
  45852. if (alignment == 0) {
  45853. return 0;
  45854. }
  45855. extraBytes = alignment-1 + sizeof(void*);
  45856. pUnaligned = ma_malloc(sz + extraBytes, pAllocationCallbacks);
  45857. if (pUnaligned == NULL) {
  45858. return NULL;
  45859. }
  45860. pAligned = (void*)(((ma_uintptr)pUnaligned + extraBytes) & ~((ma_uintptr)(alignment-1)));
  45861. ((void**)pAligned)[-1] = pUnaligned;
  45862. return pAligned;
  45863. }
  45864. MA_API void ma_aligned_free(void* p, const ma_allocation_callbacks* pAllocationCallbacks)
  45865. {
  45866. ma_free(((void**)p)[-1], pAllocationCallbacks);
  45867. }
  45868. MA_API const char* ma_get_format_name(ma_format format)
  45869. {
  45870. switch (format)
  45871. {
  45872. case ma_format_unknown: return "Unknown";
  45873. case ma_format_u8: return "8-bit Unsigned Integer";
  45874. case ma_format_s16: return "16-bit Signed Integer";
  45875. case ma_format_s24: return "24-bit Signed Integer (Tightly Packed)";
  45876. case ma_format_s32: return "32-bit Signed Integer";
  45877. case ma_format_f32: return "32-bit IEEE Floating Point";
  45878. default: return "Invalid";
  45879. }
  45880. }
  45881. MA_API void ma_blend_f32(float* pOut, float* pInA, float* pInB, float factor, ma_uint32 channels)
  45882. {
  45883. ma_uint32 i;
  45884. for (i = 0; i < channels; ++i) {
  45885. pOut[i] = ma_mix_f32(pInA[i], pInB[i], factor);
  45886. }
  45887. }
  45888. MA_API ma_uint32 ma_get_bytes_per_sample(ma_format format)
  45889. {
  45890. ma_uint32 sizes[] = {
  45891. 0, /* unknown */
  45892. 1, /* u8 */
  45893. 2, /* s16 */
  45894. 3, /* s24 */
  45895. 4, /* s32 */
  45896. 4, /* f32 */
  45897. };
  45898. return sizes[format];
  45899. }
  45900. MA_API ma_data_source_config ma_data_source_config_init(void)
  45901. {
  45902. ma_data_source_config config;
  45903. MA_ZERO_OBJECT(&config);
  45904. return config;
  45905. }
  45906. MA_API ma_result ma_data_source_init(const ma_data_source_config* pConfig, ma_data_source* pDataSource)
  45907. {
  45908. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  45909. if (pDataSource == NULL) {
  45910. return MA_INVALID_ARGS;
  45911. }
  45912. MA_ZERO_OBJECT(pDataSourceBase);
  45913. if (pConfig == NULL) {
  45914. return MA_INVALID_ARGS;
  45915. }
  45916. pDataSourceBase->vtable = pConfig->vtable;
  45917. pDataSourceBase->rangeBegInFrames = 0;
  45918. pDataSourceBase->rangeEndInFrames = ~((ma_uint64)0);
  45919. pDataSourceBase->loopBegInFrames = 0;
  45920. pDataSourceBase->loopEndInFrames = ~((ma_uint64)0);
  45921. pDataSourceBase->pCurrent = pDataSource; /* Always read from ourself by default. */
  45922. pDataSourceBase->pNext = NULL;
  45923. pDataSourceBase->onGetNext = NULL;
  45924. return MA_SUCCESS;
  45925. }
  45926. MA_API void ma_data_source_uninit(ma_data_source* pDataSource)
  45927. {
  45928. if (pDataSource == NULL) {
  45929. return;
  45930. }
  45931. /*
  45932. This is placeholder in case we need this later. Data sources need to call this in their
  45933. uninitialization routine to ensure things work later on if something is added here.
  45934. */
  45935. }
  45936. static ma_result ma_data_source_resolve_current(ma_data_source* pDataSource, ma_data_source** ppCurrentDataSource)
  45937. {
  45938. ma_data_source_base* pCurrentDataSource = (ma_data_source_base*)pDataSource;
  45939. MA_ASSERT(pDataSource != NULL);
  45940. MA_ASSERT(ppCurrentDataSource != NULL);
  45941. if (pCurrentDataSource->pCurrent == NULL) {
  45942. /*
  45943. The current data source is NULL. If we're using this in the context of a chain we need to return NULL
  45944. here so that we don't end up looping. Otherwise we just return the data source itself.
  45945. */
  45946. if (pCurrentDataSource->pNext != NULL || pCurrentDataSource->onGetNext != NULL) {
  45947. pCurrentDataSource = NULL;
  45948. } else {
  45949. 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. */
  45950. }
  45951. } else {
  45952. pCurrentDataSource = (ma_data_source_base*)pCurrentDataSource->pCurrent;
  45953. }
  45954. *ppCurrentDataSource = pCurrentDataSource;
  45955. return MA_SUCCESS;
  45956. }
  45957. static ma_result ma_data_source_read_pcm_frames_within_range(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  45958. {
  45959. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  45960. ma_result result;
  45961. ma_uint64 framesRead = 0;
  45962. ma_bool32 loop = ma_data_source_is_looping(pDataSource);
  45963. if (pDataSourceBase == NULL) {
  45964. return MA_AT_END;
  45965. }
  45966. if (frameCount == 0) {
  45967. return MA_INVALID_ARGS;
  45968. }
  45969. 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))) {
  45970. /* 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. */
  45971. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  45972. } else {
  45973. /* Need to clamp to within the range. */
  45974. ma_uint64 cursor;
  45975. result = ma_data_source_get_cursor_in_pcm_frames(pDataSourceBase, &cursor);
  45976. if (result != MA_SUCCESS) {
  45977. /* 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. */
  45978. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  45979. } else {
  45980. ma_uint64 rangeEnd;
  45981. /* We have the cursor. We need to make sure we don't read beyond our range. */
  45982. rangeEnd = pDataSourceBase->rangeEndInFrames;
  45983. /* If looping, make sure we're within range. */
  45984. if (loop) {
  45985. if (pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  45986. rangeEnd = ma_min(rangeEnd, pDataSourceBase->rangeBegInFrames + pDataSourceBase->loopEndInFrames);
  45987. }
  45988. }
  45989. if (frameCount > (rangeEnd - cursor) && rangeEnd != ~((ma_uint64)0)) {
  45990. frameCount = (rangeEnd - cursor);
  45991. }
  45992. /*
  45993. If the cursor is sitting on the end of the range the frame count will be set to 0 which can
  45994. result in MA_INVALID_ARGS. In this case, we don't want to try reading, but instead return
  45995. MA_AT_END so the higher level function can know about it.
  45996. */
  45997. if (frameCount > 0) {
  45998. result = pDataSourceBase->vtable->onRead(pDataSourceBase, pFramesOut, frameCount, &framesRead);
  45999. } else {
  46000. result = MA_AT_END; /* The cursor is sitting on the end of the range which means we're at the end. */
  46001. }
  46002. }
  46003. }
  46004. if (pFramesRead != NULL) {
  46005. *pFramesRead = framesRead;
  46006. }
  46007. /* We need to make sure MA_AT_END is returned if we hit the end of the range. */
  46008. if (result == MA_SUCCESS && framesRead == 0) {
  46009. result = MA_AT_END;
  46010. }
  46011. return result;
  46012. }
  46013. MA_API ma_result ma_data_source_read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  46014. {
  46015. ma_result result = MA_SUCCESS;
  46016. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46017. ma_data_source_base* pCurrentDataSource;
  46018. void* pRunningFramesOut = pFramesOut;
  46019. ma_uint64 totalFramesProcessed = 0;
  46020. ma_format format;
  46021. ma_uint32 channels;
  46022. 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. */
  46023. ma_bool32 loop;
  46024. if (pFramesRead != NULL) {
  46025. *pFramesRead = 0;
  46026. }
  46027. if (frameCount == 0) {
  46028. return MA_INVALID_ARGS;
  46029. }
  46030. if (pDataSourceBase == NULL) {
  46031. return MA_INVALID_ARGS;
  46032. }
  46033. loop = ma_data_source_is_looping(pDataSource);
  46034. /*
  46035. We need to know the data format so we can advance the output buffer as we read frames. If this
  46036. fails, chaining will not work and we'll just read as much as we can from the current source.
  46037. */
  46038. if (ma_data_source_get_data_format(pDataSource, &format, &channels, NULL, NULL, 0) != MA_SUCCESS) {
  46039. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  46040. if (result != MA_SUCCESS) {
  46041. return result;
  46042. }
  46043. return ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pFramesOut, frameCount, pFramesRead);
  46044. }
  46045. /*
  46046. Looping is a bit of a special case. When the `loop` argument is true, chaining will not work and
  46047. only the current data source will be read from.
  46048. */
  46049. /* Keep reading until we've read as many frames as possible. */
  46050. while (totalFramesProcessed < frameCount) {
  46051. ma_uint64 framesProcessed;
  46052. ma_uint64 framesRemaining = frameCount - totalFramesProcessed;
  46053. /* We need to resolve the data source that we'll actually be reading from. */
  46054. result = ma_data_source_resolve_current(pDataSource, (ma_data_source**)&pCurrentDataSource);
  46055. if (result != MA_SUCCESS) {
  46056. break;
  46057. }
  46058. if (pCurrentDataSource == NULL) {
  46059. break;
  46060. }
  46061. result = ma_data_source_read_pcm_frames_within_range(pCurrentDataSource, pRunningFramesOut, framesRemaining, &framesProcessed);
  46062. totalFramesProcessed += framesProcessed;
  46063. /*
  46064. 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
  46065. not necessarily considered an error.
  46066. */
  46067. if (result != MA_SUCCESS && result != MA_AT_END) {
  46068. break;
  46069. }
  46070. /*
  46071. We can determine if we've reached the end by checking if ma_data_source_read_pcm_frames_within_range() returned
  46072. MA_AT_END. To loop back to the start, all we need to do is seek back to the first frame.
  46073. */
  46074. if (result == MA_AT_END) {
  46075. /*
  46076. The result needs to be reset back to MA_SUCCESS (from MA_AT_END) so that we don't
  46077. accidentally return MA_AT_END when data has been read in prior loop iterations. at the
  46078. end of this function, the result will be checked for MA_SUCCESS, and if the total
  46079. number of frames processed is 0, will be explicitly set to MA_AT_END.
  46080. */
  46081. result = MA_SUCCESS;
  46082. /*
  46083. We reached the end. If we're looping, we just loop back to the start of the current
  46084. data source. If we're not looping we need to check if we have another in the chain, and
  46085. if so, switch to it.
  46086. */
  46087. if (loop) {
  46088. if (framesProcessed == 0) {
  46089. emptyLoopCounter += 1;
  46090. if (emptyLoopCounter > 1) {
  46091. break; /* Infinite loop detected. Get out. */
  46092. }
  46093. } else {
  46094. emptyLoopCounter = 0;
  46095. }
  46096. result = ma_data_source_seek_to_pcm_frame(pCurrentDataSource, pCurrentDataSource->loopBegInFrames);
  46097. if (result != MA_SUCCESS) {
  46098. break; /* Failed to loop. Abort. */
  46099. }
  46100. /* Don't return MA_AT_END for looping sounds. */
  46101. result = MA_SUCCESS;
  46102. } else {
  46103. if (pCurrentDataSource->pNext != NULL) {
  46104. pDataSourceBase->pCurrent = pCurrentDataSource->pNext;
  46105. } else if (pCurrentDataSource->onGetNext != NULL) {
  46106. pDataSourceBase->pCurrent = pCurrentDataSource->onGetNext(pCurrentDataSource);
  46107. if (pDataSourceBase->pCurrent == NULL) {
  46108. break; /* Our callback did not return a next data source. We're done. */
  46109. }
  46110. } else {
  46111. /* Reached the end of the chain. We're done. */
  46112. break;
  46113. }
  46114. /* The next data source needs to be rewound to ensure data is read in looping scenarios. */
  46115. result = ma_data_source_seek_to_pcm_frame(pDataSourceBase->pCurrent, 0);
  46116. if (result != MA_SUCCESS) {
  46117. break;
  46118. }
  46119. }
  46120. }
  46121. if (pRunningFramesOut != NULL) {
  46122. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesProcessed * ma_get_bytes_per_frame(format, channels));
  46123. }
  46124. }
  46125. if (pFramesRead != NULL) {
  46126. *pFramesRead = totalFramesProcessed;
  46127. }
  46128. MA_ASSERT(!(result == MA_AT_END && totalFramesProcessed > 0)); /* We should never be returning MA_AT_END if we read some data. */
  46129. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  46130. result = MA_AT_END;
  46131. }
  46132. return result;
  46133. }
  46134. MA_API ma_result ma_data_source_seek_pcm_frames(ma_data_source* pDataSource, ma_uint64 frameCount, ma_uint64* pFramesSeeked)
  46135. {
  46136. return ma_data_source_read_pcm_frames(pDataSource, NULL, frameCount, pFramesSeeked);
  46137. }
  46138. MA_API ma_result ma_data_source_seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  46139. {
  46140. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46141. if (pDataSourceBase == NULL) {
  46142. return MA_SUCCESS;
  46143. }
  46144. if (pDataSourceBase->vtable->onSeek == NULL) {
  46145. return MA_NOT_IMPLEMENTED;
  46146. }
  46147. if (frameIndex > pDataSourceBase->rangeEndInFrames) {
  46148. return MA_INVALID_OPERATION; /* Trying to seek to far forward. */
  46149. }
  46150. return pDataSourceBase->vtable->onSeek(pDataSource, pDataSourceBase->rangeBegInFrames + frameIndex);
  46151. }
  46152. 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)
  46153. {
  46154. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46155. ma_result result;
  46156. ma_format format;
  46157. ma_uint32 channels;
  46158. ma_uint32 sampleRate;
  46159. /* Initialize to defaults for safety just in case the data source does not implement this callback. */
  46160. if (pFormat != NULL) {
  46161. *pFormat = ma_format_unknown;
  46162. }
  46163. if (pChannels != NULL) {
  46164. *pChannels = 0;
  46165. }
  46166. if (pSampleRate != NULL) {
  46167. *pSampleRate = 0;
  46168. }
  46169. if (pChannelMap != NULL) {
  46170. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  46171. }
  46172. if (pDataSourceBase == NULL) {
  46173. return MA_INVALID_ARGS;
  46174. }
  46175. if (pDataSourceBase->vtable->onGetDataFormat == NULL) {
  46176. return MA_NOT_IMPLEMENTED;
  46177. }
  46178. result = pDataSourceBase->vtable->onGetDataFormat(pDataSource, &format, &channels, &sampleRate, pChannelMap, channelMapCap);
  46179. if (result != MA_SUCCESS) {
  46180. return result;
  46181. }
  46182. if (pFormat != NULL) {
  46183. *pFormat = format;
  46184. }
  46185. if (pChannels != NULL) {
  46186. *pChannels = channels;
  46187. }
  46188. if (pSampleRate != NULL) {
  46189. *pSampleRate = sampleRate;
  46190. }
  46191. /* Channel map was passed in directly to the callback. This is safe due to the channelMapCap parameter. */
  46192. return MA_SUCCESS;
  46193. }
  46194. MA_API ma_result ma_data_source_get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  46195. {
  46196. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46197. ma_result result;
  46198. ma_uint64 cursor;
  46199. if (pCursor == NULL) {
  46200. return MA_INVALID_ARGS;
  46201. }
  46202. *pCursor = 0;
  46203. if (pDataSourceBase == NULL) {
  46204. return MA_SUCCESS;
  46205. }
  46206. if (pDataSourceBase->vtable->onGetCursor == NULL) {
  46207. return MA_NOT_IMPLEMENTED;
  46208. }
  46209. result = pDataSourceBase->vtable->onGetCursor(pDataSourceBase, &cursor);
  46210. if (result != MA_SUCCESS) {
  46211. return result;
  46212. }
  46213. /* The cursor needs to be made relative to the start of the range. */
  46214. if (cursor < pDataSourceBase->rangeBegInFrames) { /* Safety check so we don't return some huge number. */
  46215. *pCursor = 0;
  46216. } else {
  46217. *pCursor = cursor - pDataSourceBase->rangeBegInFrames;
  46218. }
  46219. return MA_SUCCESS;
  46220. }
  46221. MA_API ma_result ma_data_source_get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  46222. {
  46223. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46224. if (pLength == NULL) {
  46225. return MA_INVALID_ARGS;
  46226. }
  46227. *pLength = 0;
  46228. if (pDataSourceBase == NULL) {
  46229. return MA_INVALID_ARGS;
  46230. }
  46231. /*
  46232. If we have a range defined we'll use that to determine the length. This is one of rare times
  46233. where we'll actually trust the caller. If they've set the range, I think it's mostly safe to
  46234. assume they've set it based on some higher level knowledge of the structure of the sound bank.
  46235. */
  46236. if (pDataSourceBase->rangeEndInFrames != ~((ma_uint64)0)) {
  46237. *pLength = pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames;
  46238. return MA_SUCCESS;
  46239. }
  46240. /*
  46241. Getting here means a range is not defined so we'll need to get the data source itself to tell
  46242. us the length.
  46243. */
  46244. if (pDataSourceBase->vtable->onGetLength == NULL) {
  46245. return MA_NOT_IMPLEMENTED;
  46246. }
  46247. return pDataSourceBase->vtable->onGetLength(pDataSource, pLength);
  46248. }
  46249. MA_API ma_result ma_data_source_get_cursor_in_seconds(ma_data_source* pDataSource, float* pCursor)
  46250. {
  46251. ma_result result;
  46252. ma_uint64 cursorInPCMFrames;
  46253. ma_uint32 sampleRate;
  46254. if (pCursor == NULL) {
  46255. return MA_INVALID_ARGS;
  46256. }
  46257. *pCursor = 0;
  46258. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursorInPCMFrames);
  46259. if (result != MA_SUCCESS) {
  46260. return result;
  46261. }
  46262. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  46263. if (result != MA_SUCCESS) {
  46264. return result;
  46265. }
  46266. /* 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. */
  46267. *pCursor = (ma_int64)cursorInPCMFrames / (float)sampleRate;
  46268. return MA_SUCCESS;
  46269. }
  46270. MA_API ma_result ma_data_source_get_length_in_seconds(ma_data_source* pDataSource, float* pLength)
  46271. {
  46272. ma_result result;
  46273. ma_uint64 lengthInPCMFrames;
  46274. ma_uint32 sampleRate;
  46275. if (pLength == NULL) {
  46276. return MA_INVALID_ARGS;
  46277. }
  46278. *pLength = 0;
  46279. result = ma_data_source_get_length_in_pcm_frames(pDataSource, &lengthInPCMFrames);
  46280. if (result != MA_SUCCESS) {
  46281. return result;
  46282. }
  46283. result = ma_data_source_get_data_format(pDataSource, NULL, NULL, &sampleRate, NULL, 0);
  46284. if (result != MA_SUCCESS) {
  46285. return result;
  46286. }
  46287. /* 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. */
  46288. *pLength = (ma_int64)lengthInPCMFrames / (float)sampleRate;
  46289. return MA_SUCCESS;
  46290. }
  46291. MA_API ma_result ma_data_source_set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  46292. {
  46293. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46294. if (pDataSource == NULL) {
  46295. return MA_INVALID_ARGS;
  46296. }
  46297. c89atomic_exchange_32(&pDataSourceBase->isLooping, isLooping);
  46298. /* If there's no callback for this just treat it as a successful no-op. */
  46299. if (pDataSourceBase->vtable->onSetLooping == NULL) {
  46300. return MA_SUCCESS;
  46301. }
  46302. return pDataSourceBase->vtable->onSetLooping(pDataSource, isLooping);
  46303. }
  46304. MA_API ma_bool32 ma_data_source_is_looping(const ma_data_source* pDataSource)
  46305. {
  46306. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46307. if (pDataSource == NULL) {
  46308. return MA_FALSE;
  46309. }
  46310. return c89atomic_load_32(&pDataSourceBase->isLooping);
  46311. }
  46312. MA_API ma_result ma_data_source_set_range_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 rangeBegInFrames, ma_uint64 rangeEndInFrames)
  46313. {
  46314. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46315. ma_result result;
  46316. ma_uint64 cursor;
  46317. ma_uint64 loopBegAbsolute;
  46318. ma_uint64 loopEndAbsolute;
  46319. if (pDataSource == NULL) {
  46320. return MA_INVALID_ARGS;
  46321. }
  46322. if (rangeEndInFrames < rangeBegInFrames) {
  46323. return MA_INVALID_ARGS; /* The end of the range must come after the beginning. */
  46324. }
  46325. /*
  46326. The loop points need to be updated. We'll be storing the loop points relative to the range. We'll update
  46327. these so that they maintain their absolute positioning. The loop points will then be clamped to the range.
  46328. */
  46329. loopBegAbsolute = pDataSourceBase->loopBegInFrames + pDataSourceBase->rangeBegInFrames;
  46330. loopEndAbsolute = pDataSourceBase->loopEndInFrames + ((pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) ? pDataSourceBase->rangeBegInFrames : 0);
  46331. pDataSourceBase->rangeBegInFrames = rangeBegInFrames;
  46332. pDataSourceBase->rangeEndInFrames = rangeEndInFrames;
  46333. /* Make the loop points relative again, and make sure they're clamped to within the range. */
  46334. if (loopBegAbsolute > pDataSourceBase->rangeBegInFrames) {
  46335. pDataSourceBase->loopBegInFrames = loopBegAbsolute - pDataSourceBase->rangeBegInFrames;
  46336. } else {
  46337. pDataSourceBase->loopBegInFrames = 0;
  46338. }
  46339. if (pDataSourceBase->loopBegInFrames > pDataSourceBase->rangeEndInFrames) {
  46340. pDataSourceBase->loopBegInFrames = pDataSourceBase->rangeEndInFrames;
  46341. }
  46342. /* Only need to update the loop end point if it's not -1. */
  46343. if (loopEndAbsolute != ~((ma_uint64)0)) {
  46344. if (loopEndAbsolute > pDataSourceBase->rangeBegInFrames) {
  46345. pDataSourceBase->loopEndInFrames = loopEndAbsolute - pDataSourceBase->rangeBegInFrames;
  46346. } else {
  46347. pDataSourceBase->loopEndInFrames = 0;
  46348. }
  46349. if (pDataSourceBase->loopEndInFrames > pDataSourceBase->rangeEndInFrames && pDataSourceBase->loopEndInFrames) {
  46350. pDataSourceBase->loopEndInFrames = pDataSourceBase->rangeEndInFrames;
  46351. }
  46352. }
  46353. /* If the new range is past the current cursor position we need to seek to it. */
  46354. result = ma_data_source_get_cursor_in_pcm_frames(pDataSource, &cursor);
  46355. if (result == MA_SUCCESS) {
  46356. /* Seek to within range. Note that our seek positions here are relative to the new range. */
  46357. if (cursor < rangeBegInFrames) {
  46358. ma_data_source_seek_to_pcm_frame(pDataSource, 0);
  46359. } else if (cursor > rangeEndInFrames) {
  46360. ma_data_source_seek_to_pcm_frame(pDataSource, rangeEndInFrames - rangeBegInFrames);
  46361. }
  46362. } else {
  46363. /* We failed to get the cursor position. Probably means the data source has no notion of a cursor such a noise data source. Just pretend the seeking worked. */
  46364. }
  46365. return MA_SUCCESS;
  46366. }
  46367. MA_API void ma_data_source_get_range_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pRangeBegInFrames, ma_uint64* pRangeEndInFrames)
  46368. {
  46369. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46370. if (pDataSource == NULL) {
  46371. return;
  46372. }
  46373. if (pRangeBegInFrames != NULL) {
  46374. *pRangeBegInFrames = pDataSourceBase->rangeBegInFrames;
  46375. }
  46376. if (pRangeEndInFrames != NULL) {
  46377. *pRangeEndInFrames = pDataSourceBase->rangeEndInFrames;
  46378. }
  46379. }
  46380. MA_API ma_result ma_data_source_set_loop_point_in_pcm_frames(ma_data_source* pDataSource, ma_uint64 loopBegInFrames, ma_uint64 loopEndInFrames)
  46381. {
  46382. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46383. if (pDataSource == NULL) {
  46384. return MA_INVALID_ARGS;
  46385. }
  46386. if (loopEndInFrames < loopBegInFrames) {
  46387. return MA_INVALID_ARGS; /* The end of the loop point must come after the beginning. */
  46388. }
  46389. if (loopEndInFrames > pDataSourceBase->rangeEndInFrames && loopEndInFrames != ~((ma_uint64)0)) {
  46390. return MA_INVALID_ARGS; /* The end of the loop point must not go beyond the range. */
  46391. }
  46392. pDataSourceBase->loopBegInFrames = loopBegInFrames;
  46393. pDataSourceBase->loopEndInFrames = loopEndInFrames;
  46394. /* The end cannot exceed the range. */
  46395. if (pDataSourceBase->loopEndInFrames > (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames) && pDataSourceBase->loopEndInFrames != ~((ma_uint64)0)) {
  46396. pDataSourceBase->loopEndInFrames = (pDataSourceBase->rangeEndInFrames - pDataSourceBase->rangeBegInFrames);
  46397. }
  46398. return MA_SUCCESS;
  46399. }
  46400. MA_API void ma_data_source_get_loop_point_in_pcm_frames(const ma_data_source* pDataSource, ma_uint64* pLoopBegInFrames, ma_uint64* pLoopEndInFrames)
  46401. {
  46402. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46403. if (pDataSource == NULL) {
  46404. return;
  46405. }
  46406. if (pLoopBegInFrames != NULL) {
  46407. *pLoopBegInFrames = pDataSourceBase->loopBegInFrames;
  46408. }
  46409. if (pLoopEndInFrames != NULL) {
  46410. *pLoopEndInFrames = pDataSourceBase->loopEndInFrames;
  46411. }
  46412. }
  46413. MA_API ma_result ma_data_source_set_current(ma_data_source* pDataSource, ma_data_source* pCurrentDataSource)
  46414. {
  46415. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46416. if (pDataSource == NULL) {
  46417. return MA_INVALID_ARGS;
  46418. }
  46419. pDataSourceBase->pCurrent = pCurrentDataSource;
  46420. return MA_SUCCESS;
  46421. }
  46422. MA_API ma_data_source* ma_data_source_get_current(const ma_data_source* pDataSource)
  46423. {
  46424. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46425. if (pDataSource == NULL) {
  46426. return NULL;
  46427. }
  46428. return pDataSourceBase->pCurrent;
  46429. }
  46430. MA_API ma_result ma_data_source_set_next(ma_data_source* pDataSource, ma_data_source* pNextDataSource)
  46431. {
  46432. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46433. if (pDataSource == NULL) {
  46434. return MA_INVALID_ARGS;
  46435. }
  46436. pDataSourceBase->pNext = pNextDataSource;
  46437. return MA_SUCCESS;
  46438. }
  46439. MA_API ma_data_source* ma_data_source_get_next(const ma_data_source* pDataSource)
  46440. {
  46441. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46442. if (pDataSource == NULL) {
  46443. return NULL;
  46444. }
  46445. return pDataSourceBase->pNext;
  46446. }
  46447. MA_API ma_result ma_data_source_set_next_callback(ma_data_source* pDataSource, ma_data_source_get_next_proc onGetNext)
  46448. {
  46449. ma_data_source_base* pDataSourceBase = (ma_data_source_base*)pDataSource;
  46450. if (pDataSource == NULL) {
  46451. return MA_INVALID_ARGS;
  46452. }
  46453. pDataSourceBase->onGetNext = onGetNext;
  46454. return MA_SUCCESS;
  46455. }
  46456. MA_API ma_data_source_get_next_proc ma_data_source_get_next_callback(const ma_data_source* pDataSource)
  46457. {
  46458. const ma_data_source_base* pDataSourceBase = (const ma_data_source_base*)pDataSource;
  46459. if (pDataSource == NULL) {
  46460. return NULL;
  46461. }
  46462. return pDataSourceBase->onGetNext;
  46463. }
  46464. static ma_result ma_audio_buffer_ref__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  46465. {
  46466. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  46467. ma_uint64 framesRead = ma_audio_buffer_ref_read_pcm_frames(pAudioBufferRef, pFramesOut, frameCount, MA_FALSE);
  46468. if (pFramesRead != NULL) {
  46469. *pFramesRead = framesRead;
  46470. }
  46471. if (framesRead < frameCount || framesRead == 0) {
  46472. return MA_AT_END;
  46473. }
  46474. return MA_SUCCESS;
  46475. }
  46476. static ma_result ma_audio_buffer_ref__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  46477. {
  46478. return ma_audio_buffer_ref_seek_to_pcm_frame((ma_audio_buffer_ref*)pDataSource, frameIndex);
  46479. }
  46480. 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)
  46481. {
  46482. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  46483. *pFormat = pAudioBufferRef->format;
  46484. *pChannels = pAudioBufferRef->channels;
  46485. *pSampleRate = pAudioBufferRef->sampleRate;
  46486. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pAudioBufferRef->channels);
  46487. return MA_SUCCESS;
  46488. }
  46489. static ma_result ma_audio_buffer_ref__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  46490. {
  46491. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  46492. *pCursor = pAudioBufferRef->cursor;
  46493. return MA_SUCCESS;
  46494. }
  46495. static ma_result ma_audio_buffer_ref__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  46496. {
  46497. ma_audio_buffer_ref* pAudioBufferRef = (ma_audio_buffer_ref*)pDataSource;
  46498. *pLength = pAudioBufferRef->sizeInFrames;
  46499. return MA_SUCCESS;
  46500. }
  46501. static ma_data_source_vtable g_ma_audio_buffer_ref_data_source_vtable =
  46502. {
  46503. ma_audio_buffer_ref__data_source_on_read,
  46504. ma_audio_buffer_ref__data_source_on_seek,
  46505. ma_audio_buffer_ref__data_source_on_get_data_format,
  46506. ma_audio_buffer_ref__data_source_on_get_cursor,
  46507. ma_audio_buffer_ref__data_source_on_get_length,
  46508. NULL, /* onSetLooping */
  46509. 0
  46510. };
  46511. 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)
  46512. {
  46513. ma_result result;
  46514. ma_data_source_config dataSourceConfig;
  46515. if (pAudioBufferRef == NULL) {
  46516. return MA_INVALID_ARGS;
  46517. }
  46518. MA_ZERO_OBJECT(pAudioBufferRef);
  46519. dataSourceConfig = ma_data_source_config_init();
  46520. dataSourceConfig.vtable = &g_ma_audio_buffer_ref_data_source_vtable;
  46521. result = ma_data_source_init(&dataSourceConfig, &pAudioBufferRef->ds);
  46522. if (result != MA_SUCCESS) {
  46523. return result;
  46524. }
  46525. pAudioBufferRef->format = format;
  46526. pAudioBufferRef->channels = channels;
  46527. pAudioBufferRef->sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  46528. pAudioBufferRef->cursor = 0;
  46529. pAudioBufferRef->sizeInFrames = sizeInFrames;
  46530. pAudioBufferRef->pData = pData;
  46531. return MA_SUCCESS;
  46532. }
  46533. MA_API void ma_audio_buffer_ref_uninit(ma_audio_buffer_ref* pAudioBufferRef)
  46534. {
  46535. if (pAudioBufferRef == NULL) {
  46536. return;
  46537. }
  46538. ma_data_source_uninit(&pAudioBufferRef->ds);
  46539. }
  46540. MA_API ma_result ma_audio_buffer_ref_set_data(ma_audio_buffer_ref* pAudioBufferRef, const void* pData, ma_uint64 sizeInFrames)
  46541. {
  46542. if (pAudioBufferRef == NULL) {
  46543. return MA_INVALID_ARGS;
  46544. }
  46545. pAudioBufferRef->cursor = 0;
  46546. pAudioBufferRef->sizeInFrames = sizeInFrames;
  46547. pAudioBufferRef->pData = pData;
  46548. return MA_SUCCESS;
  46549. }
  46550. MA_API ma_uint64 ma_audio_buffer_ref_read_pcm_frames(ma_audio_buffer_ref* pAudioBufferRef, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  46551. {
  46552. ma_uint64 totalFramesRead = 0;
  46553. if (pAudioBufferRef == NULL) {
  46554. return 0;
  46555. }
  46556. if (frameCount == 0) {
  46557. return 0;
  46558. }
  46559. while (totalFramesRead < frameCount) {
  46560. ma_uint64 framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  46561. ma_uint64 framesRemaining = frameCount - totalFramesRead;
  46562. ma_uint64 framesToRead;
  46563. framesToRead = framesRemaining;
  46564. if (framesToRead > framesAvailable) {
  46565. framesToRead = framesAvailable;
  46566. }
  46567. if (pFramesOut != NULL) {
  46568. 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);
  46569. }
  46570. totalFramesRead += framesToRead;
  46571. pAudioBufferRef->cursor += framesToRead;
  46572. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  46573. if (loop) {
  46574. pAudioBufferRef->cursor = 0;
  46575. } else {
  46576. break; /* We've reached the end and we're not looping. Done. */
  46577. }
  46578. }
  46579. MA_ASSERT(pAudioBufferRef->cursor < pAudioBufferRef->sizeInFrames);
  46580. }
  46581. return totalFramesRead;
  46582. }
  46583. MA_API ma_result ma_audio_buffer_ref_seek_to_pcm_frame(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameIndex)
  46584. {
  46585. if (pAudioBufferRef == NULL) {
  46586. return MA_INVALID_ARGS;
  46587. }
  46588. if (frameIndex > pAudioBufferRef->sizeInFrames) {
  46589. return MA_INVALID_ARGS;
  46590. }
  46591. pAudioBufferRef->cursor = (size_t)frameIndex;
  46592. return MA_SUCCESS;
  46593. }
  46594. MA_API ma_result ma_audio_buffer_ref_map(ma_audio_buffer_ref* pAudioBufferRef, void** ppFramesOut, ma_uint64* pFrameCount)
  46595. {
  46596. ma_uint64 framesAvailable;
  46597. ma_uint64 frameCount = 0;
  46598. if (ppFramesOut != NULL) {
  46599. *ppFramesOut = NULL; /* Safety. */
  46600. }
  46601. if (pFrameCount != NULL) {
  46602. frameCount = *pFrameCount;
  46603. *pFrameCount = 0; /* Safety. */
  46604. }
  46605. if (pAudioBufferRef == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  46606. return MA_INVALID_ARGS;
  46607. }
  46608. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  46609. if (frameCount > framesAvailable) {
  46610. frameCount = framesAvailable;
  46611. }
  46612. *ppFramesOut = ma_offset_ptr(pAudioBufferRef->pData, pAudioBufferRef->cursor * ma_get_bytes_per_frame(pAudioBufferRef->format, pAudioBufferRef->channels));
  46613. *pFrameCount = frameCount;
  46614. return MA_SUCCESS;
  46615. }
  46616. MA_API ma_result ma_audio_buffer_ref_unmap(ma_audio_buffer_ref* pAudioBufferRef, ma_uint64 frameCount)
  46617. {
  46618. ma_uint64 framesAvailable;
  46619. if (pAudioBufferRef == NULL) {
  46620. return MA_INVALID_ARGS;
  46621. }
  46622. framesAvailable = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  46623. if (frameCount > framesAvailable) {
  46624. 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. */
  46625. }
  46626. pAudioBufferRef->cursor += frameCount;
  46627. if (pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames) {
  46628. return MA_AT_END; /* Successful. Need to tell the caller that the end has been reached so that it can loop if desired. */
  46629. } else {
  46630. return MA_SUCCESS;
  46631. }
  46632. }
  46633. MA_API ma_bool32 ma_audio_buffer_ref_at_end(const ma_audio_buffer_ref* pAudioBufferRef)
  46634. {
  46635. if (pAudioBufferRef == NULL) {
  46636. return MA_FALSE;
  46637. }
  46638. return pAudioBufferRef->cursor == pAudioBufferRef->sizeInFrames;
  46639. }
  46640. MA_API ma_result ma_audio_buffer_ref_get_cursor_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pCursor)
  46641. {
  46642. if (pCursor == NULL) {
  46643. return MA_INVALID_ARGS;
  46644. }
  46645. *pCursor = 0;
  46646. if (pAudioBufferRef == NULL) {
  46647. return MA_INVALID_ARGS;
  46648. }
  46649. *pCursor = pAudioBufferRef->cursor;
  46650. return MA_SUCCESS;
  46651. }
  46652. MA_API ma_result ma_audio_buffer_ref_get_length_in_pcm_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pLength)
  46653. {
  46654. if (pLength == NULL) {
  46655. return MA_INVALID_ARGS;
  46656. }
  46657. *pLength = 0;
  46658. if (pAudioBufferRef == NULL) {
  46659. return MA_INVALID_ARGS;
  46660. }
  46661. *pLength = pAudioBufferRef->sizeInFrames;
  46662. return MA_SUCCESS;
  46663. }
  46664. MA_API ma_result ma_audio_buffer_ref_get_available_frames(const ma_audio_buffer_ref* pAudioBufferRef, ma_uint64* pAvailableFrames)
  46665. {
  46666. if (pAvailableFrames == NULL) {
  46667. return MA_INVALID_ARGS;
  46668. }
  46669. *pAvailableFrames = 0;
  46670. if (pAudioBufferRef == NULL) {
  46671. return MA_INVALID_ARGS;
  46672. }
  46673. if (pAudioBufferRef->sizeInFrames <= pAudioBufferRef->cursor) {
  46674. *pAvailableFrames = 0;
  46675. } else {
  46676. *pAvailableFrames = pAudioBufferRef->sizeInFrames - pAudioBufferRef->cursor;
  46677. }
  46678. return MA_SUCCESS;
  46679. }
  46680. 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)
  46681. {
  46682. ma_audio_buffer_config config;
  46683. MA_ZERO_OBJECT(&config);
  46684. config.format = format;
  46685. config.channels = channels;
  46686. config.sampleRate = 0; /* TODO: Version 0.12. Set this to sampleRate. */
  46687. config.sizeInFrames = sizeInFrames;
  46688. config.pData = pData;
  46689. ma_allocation_callbacks_init_copy(&config.allocationCallbacks, pAllocationCallbacks);
  46690. return config;
  46691. }
  46692. static ma_result ma_audio_buffer_init_ex(const ma_audio_buffer_config* pConfig, ma_bool32 doCopy, ma_audio_buffer* pAudioBuffer)
  46693. {
  46694. ma_result result;
  46695. if (pAudioBuffer == NULL) {
  46696. return MA_INVALID_ARGS;
  46697. }
  46698. MA_ZERO_MEMORY(pAudioBuffer, sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData)); /* Safety. Don't overwrite the extra data. */
  46699. if (pConfig == NULL) {
  46700. return MA_INVALID_ARGS;
  46701. }
  46702. if (pConfig->sizeInFrames == 0) {
  46703. return MA_INVALID_ARGS; /* Not allowing buffer sizes of 0 frames. */
  46704. }
  46705. result = ma_audio_buffer_ref_init(pConfig->format, pConfig->channels, NULL, 0, &pAudioBuffer->ref);
  46706. if (result != MA_SUCCESS) {
  46707. return result;
  46708. }
  46709. /* TODO: Version 0.12. Set this in ma_audio_buffer_ref_init() instead of here. */
  46710. pAudioBuffer->ref.sampleRate = pConfig->sampleRate;
  46711. ma_allocation_callbacks_init_copy(&pAudioBuffer->allocationCallbacks, &pConfig->allocationCallbacks);
  46712. if (doCopy) {
  46713. ma_uint64 allocationSizeInBytes;
  46714. void* pData;
  46715. allocationSizeInBytes = pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels);
  46716. if (allocationSizeInBytes > MA_SIZE_MAX) {
  46717. return MA_OUT_OF_MEMORY; /* Too big. */
  46718. }
  46719. pData = ma_malloc((size_t)allocationSizeInBytes, &pAudioBuffer->allocationCallbacks); /* Safe cast to size_t. */
  46720. if (pData == NULL) {
  46721. return MA_OUT_OF_MEMORY;
  46722. }
  46723. if (pConfig->pData != NULL) {
  46724. ma_copy_pcm_frames(pData, pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  46725. } else {
  46726. ma_silence_pcm_frames(pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  46727. }
  46728. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pData, pConfig->sizeInFrames);
  46729. pAudioBuffer->ownsData = MA_TRUE;
  46730. } else {
  46731. ma_audio_buffer_ref_set_data(&pAudioBuffer->ref, pConfig->pData, pConfig->sizeInFrames);
  46732. pAudioBuffer->ownsData = MA_FALSE;
  46733. }
  46734. return MA_SUCCESS;
  46735. }
  46736. static void ma_audio_buffer_uninit_ex(ma_audio_buffer* pAudioBuffer, ma_bool32 doFree)
  46737. {
  46738. if (pAudioBuffer == NULL) {
  46739. return;
  46740. }
  46741. if (pAudioBuffer->ownsData && pAudioBuffer->ref.pData != &pAudioBuffer->_pExtraData[0]) {
  46742. 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. */
  46743. }
  46744. if (doFree) {
  46745. ma_free(pAudioBuffer, &pAudioBuffer->allocationCallbacks);
  46746. }
  46747. ma_audio_buffer_ref_uninit(&pAudioBuffer->ref);
  46748. }
  46749. MA_API ma_result ma_audio_buffer_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  46750. {
  46751. return ma_audio_buffer_init_ex(pConfig, MA_FALSE, pAudioBuffer);
  46752. }
  46753. MA_API ma_result ma_audio_buffer_init_copy(const ma_audio_buffer_config* pConfig, ma_audio_buffer* pAudioBuffer)
  46754. {
  46755. return ma_audio_buffer_init_ex(pConfig, MA_TRUE, pAudioBuffer);
  46756. }
  46757. MA_API ma_result ma_audio_buffer_alloc_and_init(const ma_audio_buffer_config* pConfig, ma_audio_buffer** ppAudioBuffer)
  46758. {
  46759. ma_result result;
  46760. ma_audio_buffer* pAudioBuffer;
  46761. ma_audio_buffer_config innerConfig; /* We'll be making some changes to the config, so need to make a copy. */
  46762. ma_uint64 allocationSizeInBytes;
  46763. if (ppAudioBuffer == NULL) {
  46764. return MA_INVALID_ARGS;
  46765. }
  46766. *ppAudioBuffer = NULL; /* Safety. */
  46767. if (pConfig == NULL) {
  46768. return MA_INVALID_ARGS;
  46769. }
  46770. innerConfig = *pConfig;
  46771. ma_allocation_callbacks_init_copy(&innerConfig.allocationCallbacks, &pConfig->allocationCallbacks);
  46772. allocationSizeInBytes = sizeof(*pAudioBuffer) - sizeof(pAudioBuffer->_pExtraData) + (pConfig->sizeInFrames * ma_get_bytes_per_frame(pConfig->format, pConfig->channels));
  46773. if (allocationSizeInBytes > MA_SIZE_MAX) {
  46774. return MA_OUT_OF_MEMORY; /* Too big. */
  46775. }
  46776. pAudioBuffer = (ma_audio_buffer*)ma_malloc((size_t)allocationSizeInBytes, &innerConfig.allocationCallbacks); /* Safe cast to size_t. */
  46777. if (pAudioBuffer == NULL) {
  46778. return MA_OUT_OF_MEMORY;
  46779. }
  46780. if (pConfig->pData != NULL) {
  46781. ma_copy_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->pData, pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  46782. } else {
  46783. ma_silence_pcm_frames(&pAudioBuffer->_pExtraData[0], pConfig->sizeInFrames, pConfig->format, pConfig->channels);
  46784. }
  46785. innerConfig.pData = &pAudioBuffer->_pExtraData[0];
  46786. result = ma_audio_buffer_init_ex(&innerConfig, MA_FALSE, pAudioBuffer);
  46787. if (result != MA_SUCCESS) {
  46788. ma_free(pAudioBuffer, &innerConfig.allocationCallbacks);
  46789. return result;
  46790. }
  46791. *ppAudioBuffer = pAudioBuffer;
  46792. return MA_SUCCESS;
  46793. }
  46794. MA_API void ma_audio_buffer_uninit(ma_audio_buffer* pAudioBuffer)
  46795. {
  46796. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_FALSE);
  46797. }
  46798. MA_API void ma_audio_buffer_uninit_and_free(ma_audio_buffer* pAudioBuffer)
  46799. {
  46800. ma_audio_buffer_uninit_ex(pAudioBuffer, MA_TRUE);
  46801. }
  46802. MA_API ma_uint64 ma_audio_buffer_read_pcm_frames(ma_audio_buffer* pAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_bool32 loop)
  46803. {
  46804. if (pAudioBuffer == NULL) {
  46805. return 0;
  46806. }
  46807. return ma_audio_buffer_ref_read_pcm_frames(&pAudioBuffer->ref, pFramesOut, frameCount, loop);
  46808. }
  46809. MA_API ma_result ma_audio_buffer_seek_to_pcm_frame(ma_audio_buffer* pAudioBuffer, ma_uint64 frameIndex)
  46810. {
  46811. if (pAudioBuffer == NULL) {
  46812. return MA_INVALID_ARGS;
  46813. }
  46814. return ma_audio_buffer_ref_seek_to_pcm_frame(&pAudioBuffer->ref, frameIndex);
  46815. }
  46816. MA_API ma_result ma_audio_buffer_map(ma_audio_buffer* pAudioBuffer, void** ppFramesOut, ma_uint64* pFrameCount)
  46817. {
  46818. if (ppFramesOut != NULL) {
  46819. *ppFramesOut = NULL; /* Safety. */
  46820. }
  46821. if (pAudioBuffer == NULL) {
  46822. if (pFrameCount != NULL) {
  46823. *pFrameCount = 0;
  46824. }
  46825. return MA_INVALID_ARGS;
  46826. }
  46827. return ma_audio_buffer_ref_map(&pAudioBuffer->ref, ppFramesOut, pFrameCount);
  46828. }
  46829. MA_API ma_result ma_audio_buffer_unmap(ma_audio_buffer* pAudioBuffer, ma_uint64 frameCount)
  46830. {
  46831. if (pAudioBuffer == NULL) {
  46832. return MA_INVALID_ARGS;
  46833. }
  46834. return ma_audio_buffer_ref_unmap(&pAudioBuffer->ref, frameCount);
  46835. }
  46836. MA_API ma_bool32 ma_audio_buffer_at_end(const ma_audio_buffer* pAudioBuffer)
  46837. {
  46838. if (pAudioBuffer == NULL) {
  46839. return MA_FALSE;
  46840. }
  46841. return ma_audio_buffer_ref_at_end(&pAudioBuffer->ref);
  46842. }
  46843. MA_API ma_result ma_audio_buffer_get_cursor_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pCursor)
  46844. {
  46845. if (pAudioBuffer == NULL) {
  46846. return MA_INVALID_ARGS;
  46847. }
  46848. return ma_audio_buffer_ref_get_cursor_in_pcm_frames(&pAudioBuffer->ref, pCursor);
  46849. }
  46850. MA_API ma_result ma_audio_buffer_get_length_in_pcm_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pLength)
  46851. {
  46852. if (pAudioBuffer == NULL) {
  46853. return MA_INVALID_ARGS;
  46854. }
  46855. return ma_audio_buffer_ref_get_length_in_pcm_frames(&pAudioBuffer->ref, pLength);
  46856. }
  46857. MA_API ma_result ma_audio_buffer_get_available_frames(const ma_audio_buffer* pAudioBuffer, ma_uint64* pAvailableFrames)
  46858. {
  46859. if (pAvailableFrames == NULL) {
  46860. return MA_INVALID_ARGS;
  46861. }
  46862. *pAvailableFrames = 0;
  46863. if (pAudioBuffer == NULL) {
  46864. return MA_INVALID_ARGS;
  46865. }
  46866. return ma_audio_buffer_ref_get_available_frames(&pAudioBuffer->ref, pAvailableFrames);
  46867. }
  46868. MA_API ma_result ma_paged_audio_buffer_data_init(ma_format format, ma_uint32 channels, ma_paged_audio_buffer_data* pData)
  46869. {
  46870. if (pData == NULL) {
  46871. return MA_INVALID_ARGS;
  46872. }
  46873. MA_ZERO_OBJECT(pData);
  46874. pData->format = format;
  46875. pData->channels = channels;
  46876. pData->pTail = &pData->head;
  46877. return MA_SUCCESS;
  46878. }
  46879. MA_API void ma_paged_audio_buffer_data_uninit(ma_paged_audio_buffer_data* pData, const ma_allocation_callbacks* pAllocationCallbacks)
  46880. {
  46881. ma_paged_audio_buffer_page* pPage;
  46882. if (pData == NULL) {
  46883. return;
  46884. }
  46885. /* All pages need to be freed. */
  46886. pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->head.pNext);
  46887. while (pPage != NULL) {
  46888. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext);
  46889. ma_free(pPage, pAllocationCallbacks);
  46890. pPage = pNext;
  46891. }
  46892. }
  46893. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_head(ma_paged_audio_buffer_data* pData)
  46894. {
  46895. if (pData == NULL) {
  46896. return NULL;
  46897. }
  46898. return &pData->head;
  46899. }
  46900. MA_API ma_paged_audio_buffer_page* ma_paged_audio_buffer_data_get_tail(ma_paged_audio_buffer_data* pData)
  46901. {
  46902. if (pData == NULL) {
  46903. return NULL;
  46904. }
  46905. return pData->pTail;
  46906. }
  46907. MA_API ma_result ma_paged_audio_buffer_data_get_length_in_pcm_frames(ma_paged_audio_buffer_data* pData, ma_uint64* pLength)
  46908. {
  46909. ma_paged_audio_buffer_page* pPage;
  46910. if (pLength == NULL) {
  46911. return MA_INVALID_ARGS;
  46912. }
  46913. *pLength = 0;
  46914. if (pData == NULL) {
  46915. return MA_INVALID_ARGS;
  46916. }
  46917. /* Calculate the length from the linked list. */
  46918. for (pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->head.pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext)) {
  46919. *pLength += pPage->sizeInFrames;
  46920. }
  46921. return MA_SUCCESS;
  46922. }
  46923. 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)
  46924. {
  46925. ma_paged_audio_buffer_page* pPage;
  46926. ma_uint64 allocationSize;
  46927. if (ppPage == NULL) {
  46928. return MA_INVALID_ARGS;
  46929. }
  46930. *ppPage = NULL;
  46931. if (pData == NULL) {
  46932. return MA_INVALID_ARGS;
  46933. }
  46934. allocationSize = sizeof(*pPage) + (pageSizeInFrames * ma_get_bytes_per_frame(pData->format, pData->channels));
  46935. if (allocationSize > MA_SIZE_MAX) {
  46936. return MA_OUT_OF_MEMORY; /* Too big. */
  46937. }
  46938. pPage = (ma_paged_audio_buffer_page*)ma_malloc((size_t)allocationSize, pAllocationCallbacks); /* Safe cast to size_t. */
  46939. if (pPage == NULL) {
  46940. return MA_OUT_OF_MEMORY;
  46941. }
  46942. pPage->pNext = NULL;
  46943. pPage->sizeInFrames = pageSizeInFrames;
  46944. if (pInitialData != NULL) {
  46945. ma_copy_pcm_frames(pPage->pAudioData, pInitialData, pageSizeInFrames, pData->format, pData->channels);
  46946. }
  46947. *ppPage = pPage;
  46948. return MA_SUCCESS;
  46949. }
  46950. 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)
  46951. {
  46952. if (pData == NULL || pPage == NULL) {
  46953. return MA_INVALID_ARGS;
  46954. }
  46955. /* It's assumed the page is not attached to the list. */
  46956. ma_free(pPage, pAllocationCallbacks);
  46957. return MA_SUCCESS;
  46958. }
  46959. MA_API ma_result ma_paged_audio_buffer_data_append_page(ma_paged_audio_buffer_data* pData, ma_paged_audio_buffer_page* pPage)
  46960. {
  46961. if (pData == NULL || pPage == NULL) {
  46962. return MA_INVALID_ARGS;
  46963. }
  46964. /* 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. */
  46965. /* First thing to do is update the tail. */
  46966. for (;;) {
  46967. ma_paged_audio_buffer_page* pOldTail = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pData->pTail);
  46968. ma_paged_audio_buffer_page* pNewTail = pPage;
  46969. if (c89atomic_compare_exchange_weak_ptr((volatile void**)&pData->pTail, (void**)&pOldTail, pNewTail)) {
  46970. /* 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. */
  46971. c89atomic_exchange_ptr(&pOldTail->pNext, pPage);
  46972. break; /* Done. */
  46973. }
  46974. }
  46975. return MA_SUCCESS;
  46976. }
  46977. 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)
  46978. {
  46979. ma_result result;
  46980. ma_paged_audio_buffer_page* pPage;
  46981. result = ma_paged_audio_buffer_data_allocate_page(pData, pageSizeInFrames, pInitialData, pAllocationCallbacks, &pPage);
  46982. if (result != MA_SUCCESS) {
  46983. return result;
  46984. }
  46985. return ma_paged_audio_buffer_data_append_page(pData, pPage); /* <-- Should never fail. */
  46986. }
  46987. MA_API ma_paged_audio_buffer_config ma_paged_audio_buffer_config_init(ma_paged_audio_buffer_data* pData)
  46988. {
  46989. ma_paged_audio_buffer_config config;
  46990. MA_ZERO_OBJECT(&config);
  46991. config.pData = pData;
  46992. return config;
  46993. }
  46994. static ma_result ma_paged_audio_buffer__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  46995. {
  46996. return ma_paged_audio_buffer_read_pcm_frames((ma_paged_audio_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  46997. }
  46998. static ma_result ma_paged_audio_buffer__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  46999. {
  47000. return ma_paged_audio_buffer_seek_to_pcm_frame((ma_paged_audio_buffer*)pDataSource, frameIndex);
  47001. }
  47002. 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)
  47003. {
  47004. ma_paged_audio_buffer* pPagedAudioBuffer = (ma_paged_audio_buffer*)pDataSource;
  47005. *pFormat = pPagedAudioBuffer->pData->format;
  47006. *pChannels = pPagedAudioBuffer->pData->channels;
  47007. *pSampleRate = 0; /* There is no notion of a sample rate with audio buffers. */
  47008. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pPagedAudioBuffer->pData->channels);
  47009. return MA_SUCCESS;
  47010. }
  47011. static ma_result ma_paged_audio_buffer__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  47012. {
  47013. return ma_paged_audio_buffer_get_cursor_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pCursor);
  47014. }
  47015. static ma_result ma_paged_audio_buffer__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  47016. {
  47017. return ma_paged_audio_buffer_get_length_in_pcm_frames((ma_paged_audio_buffer*)pDataSource, pLength);
  47018. }
  47019. static ma_data_source_vtable g_ma_paged_audio_buffer_data_source_vtable =
  47020. {
  47021. ma_paged_audio_buffer__data_source_on_read,
  47022. ma_paged_audio_buffer__data_source_on_seek,
  47023. ma_paged_audio_buffer__data_source_on_get_data_format,
  47024. ma_paged_audio_buffer__data_source_on_get_cursor,
  47025. ma_paged_audio_buffer__data_source_on_get_length,
  47026. NULL, /* onSetLooping */
  47027. 0
  47028. };
  47029. MA_API ma_result ma_paged_audio_buffer_init(const ma_paged_audio_buffer_config* pConfig, ma_paged_audio_buffer* pPagedAudioBuffer)
  47030. {
  47031. ma_result result;
  47032. ma_data_source_config dataSourceConfig;
  47033. if (pPagedAudioBuffer == NULL) {
  47034. return MA_INVALID_ARGS;
  47035. }
  47036. MA_ZERO_OBJECT(pPagedAudioBuffer);
  47037. /* A config is required for the format and channel count. */
  47038. if (pConfig == NULL) {
  47039. return MA_INVALID_ARGS;
  47040. }
  47041. if (pConfig->pData == NULL) {
  47042. return MA_INVALID_ARGS; /* No underlying data specified. */
  47043. }
  47044. dataSourceConfig = ma_data_source_config_init();
  47045. dataSourceConfig.vtable = &g_ma_paged_audio_buffer_data_source_vtable;
  47046. result = ma_data_source_init(&dataSourceConfig, &pPagedAudioBuffer->ds);
  47047. if (result != MA_SUCCESS) {
  47048. return result;
  47049. }
  47050. pPagedAudioBuffer->pData = pConfig->pData;
  47051. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pConfig->pData);
  47052. pPagedAudioBuffer->relativeCursor = 0;
  47053. pPagedAudioBuffer->absoluteCursor = 0;
  47054. return MA_SUCCESS;
  47055. }
  47056. MA_API void ma_paged_audio_buffer_uninit(ma_paged_audio_buffer* pPagedAudioBuffer)
  47057. {
  47058. if (pPagedAudioBuffer == NULL) {
  47059. return;
  47060. }
  47061. /* Nothing to do. The data needs to be deleted separately. */
  47062. }
  47063. MA_API ma_result ma_paged_audio_buffer_read_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  47064. {
  47065. ma_result result = MA_SUCCESS;
  47066. ma_uint64 totalFramesRead = 0;
  47067. ma_format format;
  47068. ma_uint32 channels;
  47069. if (pPagedAudioBuffer == NULL) {
  47070. return MA_INVALID_ARGS;
  47071. }
  47072. format = pPagedAudioBuffer->pData->format;
  47073. channels = pPagedAudioBuffer->pData->channels;
  47074. while (totalFramesRead < frameCount) {
  47075. /* Read from the current page. The buffer should never be in a state where this is NULL. */
  47076. ma_uint64 framesRemainingInCurrentPage;
  47077. ma_uint64 framesRemainingToRead = frameCount - totalFramesRead;
  47078. ma_uint64 framesToReadThisIteration;
  47079. MA_ASSERT(pPagedAudioBuffer->pCurrent != NULL);
  47080. framesRemainingInCurrentPage = pPagedAudioBuffer->pCurrent->sizeInFrames - pPagedAudioBuffer->relativeCursor;
  47081. framesToReadThisIteration = ma_min(framesRemainingInCurrentPage, framesRemainingToRead);
  47082. 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);
  47083. totalFramesRead += framesToReadThisIteration;
  47084. pPagedAudioBuffer->absoluteCursor += framesToReadThisIteration;
  47085. pPagedAudioBuffer->relativeCursor += framesToReadThisIteration;
  47086. /* Move to the next page if necessary. If there's no more pages, we need to return MA_AT_END. */
  47087. MA_ASSERT(pPagedAudioBuffer->relativeCursor <= pPagedAudioBuffer->pCurrent->sizeInFrames);
  47088. if (pPagedAudioBuffer->relativeCursor == pPagedAudioBuffer->pCurrent->sizeInFrames) {
  47089. /* We reached the end of the page. Need to move to the next. If there's no more pages, we're done. */
  47090. ma_paged_audio_buffer_page* pNext = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPagedAudioBuffer->pCurrent->pNext);
  47091. if (pNext == NULL) {
  47092. result = MA_AT_END;
  47093. break; /* We've reached the end. */
  47094. } else {
  47095. pPagedAudioBuffer->pCurrent = pNext;
  47096. pPagedAudioBuffer->relativeCursor = 0;
  47097. }
  47098. }
  47099. }
  47100. if (pFramesRead != NULL) {
  47101. *pFramesRead = totalFramesRead;
  47102. }
  47103. return result;
  47104. }
  47105. MA_API ma_result ma_paged_audio_buffer_seek_to_pcm_frame(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64 frameIndex)
  47106. {
  47107. if (pPagedAudioBuffer == NULL) {
  47108. return MA_INVALID_ARGS;
  47109. }
  47110. if (frameIndex == pPagedAudioBuffer->absoluteCursor) {
  47111. return MA_SUCCESS; /* Nothing to do. */
  47112. }
  47113. if (frameIndex < pPagedAudioBuffer->absoluteCursor) {
  47114. /* Moving backwards. Need to move the cursor back to the start, and then move forward. */
  47115. pPagedAudioBuffer->pCurrent = ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData);
  47116. pPagedAudioBuffer->absoluteCursor = 0;
  47117. pPagedAudioBuffer->relativeCursor = 0;
  47118. /* Fall through to the forward seeking section below. */
  47119. }
  47120. if (frameIndex > pPagedAudioBuffer->absoluteCursor) {
  47121. /* Moving forward. */
  47122. ma_paged_audio_buffer_page* pPage;
  47123. ma_uint64 runningCursor = 0;
  47124. for (pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&ma_paged_audio_buffer_data_get_head(pPagedAudioBuffer->pData)->pNext); pPage != NULL; pPage = (ma_paged_audio_buffer_page*)c89atomic_load_ptr(&pPage->pNext)) {
  47125. ma_uint64 pageRangeBeg = runningCursor;
  47126. ma_uint64 pageRangeEnd = pageRangeBeg + pPage->sizeInFrames;
  47127. if (frameIndex >= pageRangeBeg) {
  47128. if (frameIndex < pageRangeEnd || (frameIndex == pageRangeEnd && pPage == (ma_paged_audio_buffer_page*)c89atomic_load_ptr(ma_paged_audio_buffer_data_get_tail(pPagedAudioBuffer->pData)))) { /* A small edge case - allow seeking to the very end of the buffer. */
  47129. /* We found the page. */
  47130. pPagedAudioBuffer->pCurrent = pPage;
  47131. pPagedAudioBuffer->absoluteCursor = frameIndex;
  47132. pPagedAudioBuffer->relativeCursor = frameIndex - pageRangeBeg;
  47133. return MA_SUCCESS;
  47134. }
  47135. }
  47136. runningCursor = pageRangeEnd;
  47137. }
  47138. /* Getting here means we tried seeking too far forward. Don't change any state. */
  47139. return MA_BAD_SEEK;
  47140. }
  47141. return MA_SUCCESS;
  47142. }
  47143. MA_API ma_result ma_paged_audio_buffer_get_cursor_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pCursor)
  47144. {
  47145. if (pCursor == NULL) {
  47146. return MA_INVALID_ARGS;
  47147. }
  47148. *pCursor = 0; /* Safety. */
  47149. if (pPagedAudioBuffer == NULL) {
  47150. return MA_INVALID_ARGS;
  47151. }
  47152. *pCursor = pPagedAudioBuffer->absoluteCursor;
  47153. return MA_SUCCESS;
  47154. }
  47155. MA_API ma_result ma_paged_audio_buffer_get_length_in_pcm_frames(ma_paged_audio_buffer* pPagedAudioBuffer, ma_uint64* pLength)
  47156. {
  47157. return ma_paged_audio_buffer_data_get_length_in_pcm_frames(pPagedAudioBuffer->pData, pLength);
  47158. }
  47159. /**************************************************************************************************************************************************************
  47160. VFS
  47161. **************************************************************************************************************************************************************/
  47162. MA_API ma_result ma_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47163. {
  47164. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47165. if (pFile == NULL) {
  47166. return MA_INVALID_ARGS;
  47167. }
  47168. *pFile = NULL;
  47169. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  47170. return MA_INVALID_ARGS;
  47171. }
  47172. if (pCallbacks->onOpen == NULL) {
  47173. return MA_NOT_IMPLEMENTED;
  47174. }
  47175. return pCallbacks->onOpen(pVFS, pFilePath, openMode, pFile);
  47176. }
  47177. MA_API ma_result ma_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47178. {
  47179. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47180. if (pFile == NULL) {
  47181. return MA_INVALID_ARGS;
  47182. }
  47183. *pFile = NULL;
  47184. if (pVFS == NULL || pFilePath == NULL || openMode == 0) {
  47185. return MA_INVALID_ARGS;
  47186. }
  47187. if (pCallbacks->onOpenW == NULL) {
  47188. return MA_NOT_IMPLEMENTED;
  47189. }
  47190. return pCallbacks->onOpenW(pVFS, pFilePath, openMode, pFile);
  47191. }
  47192. MA_API ma_result ma_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  47193. {
  47194. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47195. if (pVFS == NULL || file == NULL) {
  47196. return MA_INVALID_ARGS;
  47197. }
  47198. if (pCallbacks->onClose == NULL) {
  47199. return MA_NOT_IMPLEMENTED;
  47200. }
  47201. return pCallbacks->onClose(pVFS, file);
  47202. }
  47203. MA_API ma_result ma_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  47204. {
  47205. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47206. ma_result result;
  47207. size_t bytesRead;
  47208. if (pBytesRead != NULL) {
  47209. *pBytesRead = 0;
  47210. }
  47211. if (pVFS == NULL || file == NULL || pDst == NULL) {
  47212. return MA_INVALID_ARGS;
  47213. }
  47214. if (pCallbacks->onRead == NULL) {
  47215. return MA_NOT_IMPLEMENTED;
  47216. }
  47217. result = pCallbacks->onRead(pVFS, file, pDst, sizeInBytes, &bytesRead);
  47218. if (pBytesRead != NULL) {
  47219. *pBytesRead = bytesRead;
  47220. }
  47221. if (result == MA_SUCCESS && bytesRead == 0 && sizeInBytes > 0) {
  47222. result = MA_AT_END;
  47223. }
  47224. return result;
  47225. }
  47226. MA_API ma_result ma_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  47227. {
  47228. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47229. if (pBytesWritten != NULL) {
  47230. *pBytesWritten = 0;
  47231. }
  47232. if (pVFS == NULL || file == NULL || pSrc == NULL) {
  47233. return MA_INVALID_ARGS;
  47234. }
  47235. if (pCallbacks->onWrite == NULL) {
  47236. return MA_NOT_IMPLEMENTED;
  47237. }
  47238. return pCallbacks->onWrite(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  47239. }
  47240. MA_API ma_result ma_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  47241. {
  47242. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47243. if (pVFS == NULL || file == NULL) {
  47244. return MA_INVALID_ARGS;
  47245. }
  47246. if (pCallbacks->onSeek == NULL) {
  47247. return MA_NOT_IMPLEMENTED;
  47248. }
  47249. return pCallbacks->onSeek(pVFS, file, offset, origin);
  47250. }
  47251. MA_API ma_result ma_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  47252. {
  47253. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47254. if (pCursor == NULL) {
  47255. return MA_INVALID_ARGS;
  47256. }
  47257. *pCursor = 0;
  47258. if (pVFS == NULL || file == NULL) {
  47259. return MA_INVALID_ARGS;
  47260. }
  47261. if (pCallbacks->onTell == NULL) {
  47262. return MA_NOT_IMPLEMENTED;
  47263. }
  47264. return pCallbacks->onTell(pVFS, file, pCursor);
  47265. }
  47266. MA_API ma_result ma_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  47267. {
  47268. ma_vfs_callbacks* pCallbacks = (ma_vfs_callbacks*)pVFS;
  47269. if (pInfo == NULL) {
  47270. return MA_INVALID_ARGS;
  47271. }
  47272. MA_ZERO_OBJECT(pInfo);
  47273. if (pVFS == NULL || file == NULL) {
  47274. return MA_INVALID_ARGS;
  47275. }
  47276. if (pCallbacks->onInfo == NULL) {
  47277. return MA_NOT_IMPLEMENTED;
  47278. }
  47279. return pCallbacks->onInfo(pVFS, file, pInfo);
  47280. }
  47281. 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)
  47282. {
  47283. ma_result result;
  47284. ma_vfs_file file;
  47285. ma_file_info info;
  47286. void* pData;
  47287. size_t bytesRead;
  47288. if (ppData != NULL) {
  47289. *ppData = NULL;
  47290. }
  47291. if (pSize != NULL) {
  47292. *pSize = 0;
  47293. }
  47294. if (ppData == NULL) {
  47295. return MA_INVALID_ARGS;
  47296. }
  47297. if (pFilePath != NULL) {
  47298. result = ma_vfs_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  47299. } else {
  47300. result = ma_vfs_open_w(pVFS, pFilePathW, MA_OPEN_MODE_READ, &file);
  47301. }
  47302. if (result != MA_SUCCESS) {
  47303. return result;
  47304. }
  47305. result = ma_vfs_info(pVFS, file, &info);
  47306. if (result != MA_SUCCESS) {
  47307. ma_vfs_close(pVFS, file);
  47308. return result;
  47309. }
  47310. if (info.sizeInBytes > MA_SIZE_MAX) {
  47311. ma_vfs_close(pVFS, file);
  47312. return MA_TOO_BIG;
  47313. }
  47314. pData = ma_malloc((size_t)info.sizeInBytes, pAllocationCallbacks); /* Safe cast. */
  47315. if (pData == NULL) {
  47316. ma_vfs_close(pVFS, file);
  47317. return result;
  47318. }
  47319. result = ma_vfs_read(pVFS, file, pData, (size_t)info.sizeInBytes, &bytesRead); /* Safe cast. */
  47320. ma_vfs_close(pVFS, file);
  47321. if (result != MA_SUCCESS) {
  47322. ma_free(pData, pAllocationCallbacks);
  47323. return result;
  47324. }
  47325. if (pSize != NULL) {
  47326. *pSize = bytesRead;
  47327. }
  47328. MA_ASSERT(ppData != NULL);
  47329. *ppData = pData;
  47330. return MA_SUCCESS;
  47331. }
  47332. 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)
  47333. {
  47334. return ma_vfs_open_and_read_file_ex(pVFS, pFilePath, NULL, ppData, pSize, pAllocationCallbacks);
  47335. }
  47336. 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)
  47337. {
  47338. return ma_vfs_open_and_read_file_ex(pVFS, NULL, pFilePath, ppData, pSize, pAllocationCallbacks);
  47339. }
  47340. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47341. static void ma_default_vfs__get_open_settings_win32(ma_uint32 openMode, DWORD* pDesiredAccess, DWORD* pShareMode, DWORD* pCreationDisposition)
  47342. {
  47343. *pDesiredAccess = 0;
  47344. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  47345. *pDesiredAccess |= GENERIC_READ;
  47346. }
  47347. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  47348. *pDesiredAccess |= GENERIC_WRITE;
  47349. }
  47350. *pShareMode = 0;
  47351. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  47352. *pShareMode |= FILE_SHARE_READ;
  47353. }
  47354. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  47355. *pCreationDisposition = CREATE_ALWAYS; /* Opening in write mode. Truncate. */
  47356. } else {
  47357. *pCreationDisposition = OPEN_EXISTING; /* Opening in read mode. File must exist. */
  47358. }
  47359. }
  47360. static ma_result ma_default_vfs_open__win32(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47361. {
  47362. HANDLE hFile;
  47363. DWORD dwDesiredAccess;
  47364. DWORD dwShareMode;
  47365. DWORD dwCreationDisposition;
  47366. (void)pVFS;
  47367. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  47368. hFile = CreateFileA(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  47369. if (hFile == INVALID_HANDLE_VALUE) {
  47370. return ma_result_from_GetLastError(GetLastError());
  47371. }
  47372. *pFile = hFile;
  47373. return MA_SUCCESS;
  47374. }
  47375. static ma_result ma_default_vfs_open_w__win32(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47376. {
  47377. HANDLE hFile;
  47378. DWORD dwDesiredAccess;
  47379. DWORD dwShareMode;
  47380. DWORD dwCreationDisposition;
  47381. (void)pVFS;
  47382. ma_default_vfs__get_open_settings_win32(openMode, &dwDesiredAccess, &dwShareMode, &dwCreationDisposition);
  47383. hFile = CreateFileW(pFilePath, dwDesiredAccess, dwShareMode, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL);
  47384. if (hFile == INVALID_HANDLE_VALUE) {
  47385. return ma_result_from_GetLastError(GetLastError());
  47386. }
  47387. *pFile = hFile;
  47388. return MA_SUCCESS;
  47389. }
  47390. static ma_result ma_default_vfs_close__win32(ma_vfs* pVFS, ma_vfs_file file)
  47391. {
  47392. (void)pVFS;
  47393. if (CloseHandle((HANDLE)file) == 0) {
  47394. return ma_result_from_GetLastError(GetLastError());
  47395. }
  47396. return MA_SUCCESS;
  47397. }
  47398. static ma_result ma_default_vfs_read__win32(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  47399. {
  47400. ma_result result = MA_SUCCESS;
  47401. size_t totalBytesRead;
  47402. (void)pVFS;
  47403. totalBytesRead = 0;
  47404. while (totalBytesRead < sizeInBytes) {
  47405. size_t bytesRemaining;
  47406. DWORD bytesToRead;
  47407. DWORD bytesRead;
  47408. BOOL readResult;
  47409. bytesRemaining = sizeInBytes - totalBytesRead;
  47410. if (bytesRemaining >= 0xFFFFFFFF) {
  47411. bytesToRead = 0xFFFFFFFF;
  47412. } else {
  47413. bytesToRead = (DWORD)bytesRemaining;
  47414. }
  47415. readResult = ReadFile((HANDLE)file, ma_offset_ptr(pDst, totalBytesRead), bytesToRead, &bytesRead, NULL);
  47416. if (readResult == 1 && bytesRead == 0) {
  47417. result = MA_AT_END;
  47418. break; /* EOF */
  47419. }
  47420. totalBytesRead += bytesRead;
  47421. if (bytesRead < bytesToRead) {
  47422. break; /* EOF */
  47423. }
  47424. if (readResult == 0) {
  47425. result = ma_result_from_GetLastError(GetLastError());
  47426. break;
  47427. }
  47428. }
  47429. if (pBytesRead != NULL) {
  47430. *pBytesRead = totalBytesRead;
  47431. }
  47432. return result;
  47433. }
  47434. static ma_result ma_default_vfs_write__win32(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  47435. {
  47436. ma_result result = MA_SUCCESS;
  47437. size_t totalBytesWritten;
  47438. (void)pVFS;
  47439. totalBytesWritten = 0;
  47440. while (totalBytesWritten < sizeInBytes) {
  47441. size_t bytesRemaining;
  47442. DWORD bytesToWrite;
  47443. DWORD bytesWritten;
  47444. BOOL writeResult;
  47445. bytesRemaining = sizeInBytes - totalBytesWritten;
  47446. if (bytesRemaining >= 0xFFFFFFFF) {
  47447. bytesToWrite = 0xFFFFFFFF;
  47448. } else {
  47449. bytesToWrite = (DWORD)bytesRemaining;
  47450. }
  47451. writeResult = WriteFile((HANDLE)file, ma_offset_ptr(pSrc, totalBytesWritten), bytesToWrite, &bytesWritten, NULL);
  47452. totalBytesWritten += bytesWritten;
  47453. if (writeResult == 0) {
  47454. result = ma_result_from_GetLastError(GetLastError());
  47455. break;
  47456. }
  47457. }
  47458. if (pBytesWritten != NULL) {
  47459. *pBytesWritten = totalBytesWritten;
  47460. }
  47461. return result;
  47462. }
  47463. static ma_result ma_default_vfs_seek__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  47464. {
  47465. LARGE_INTEGER liDistanceToMove;
  47466. DWORD dwMoveMethod;
  47467. BOOL result;
  47468. (void)pVFS;
  47469. liDistanceToMove.QuadPart = offset;
  47470. /* */ if (origin == ma_seek_origin_current) {
  47471. dwMoveMethod = FILE_CURRENT;
  47472. } else if (origin == ma_seek_origin_end) {
  47473. dwMoveMethod = FILE_END;
  47474. } else {
  47475. dwMoveMethod = FILE_BEGIN;
  47476. }
  47477. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  47478. /* No SetFilePointerEx() so restrict to 31 bits. */
  47479. if (origin > 0x7FFFFFFF) {
  47480. return MA_OUT_OF_RANGE;
  47481. }
  47482. result = SetFilePointer((HANDLE)file, (LONG)liDistanceToMove.QuadPart, NULL, dwMoveMethod);
  47483. #else
  47484. result = SetFilePointerEx((HANDLE)file, liDistanceToMove, NULL, dwMoveMethod);
  47485. #endif
  47486. if (result == 0) {
  47487. return ma_result_from_GetLastError(GetLastError());
  47488. }
  47489. return MA_SUCCESS;
  47490. }
  47491. static ma_result ma_default_vfs_tell__win32(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  47492. {
  47493. LARGE_INTEGER liZero;
  47494. LARGE_INTEGER liTell;
  47495. BOOL result;
  47496. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  47497. LONG tell;
  47498. #endif
  47499. (void)pVFS;
  47500. liZero.QuadPart = 0;
  47501. #if (defined(_MSC_VER) && _MSC_VER <= 1200) || defined(__DMC__)
  47502. result = SetFilePointer((HANDLE)file, (LONG)liZero.QuadPart, &tell, FILE_CURRENT);
  47503. liTell.QuadPart = tell;
  47504. #else
  47505. result = SetFilePointerEx((HANDLE)file, liZero, &liTell, FILE_CURRENT);
  47506. #endif
  47507. if (result == 0) {
  47508. return ma_result_from_GetLastError(GetLastError());
  47509. }
  47510. if (pCursor != NULL) {
  47511. *pCursor = liTell.QuadPart;
  47512. }
  47513. return MA_SUCCESS;
  47514. }
  47515. static ma_result ma_default_vfs_info__win32(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  47516. {
  47517. BY_HANDLE_FILE_INFORMATION fi;
  47518. BOOL result;
  47519. (void)pVFS;
  47520. result = GetFileInformationByHandle((HANDLE)file, &fi);
  47521. if (result == 0) {
  47522. return ma_result_from_GetLastError(GetLastError());
  47523. }
  47524. pInfo->sizeInBytes = ((ma_uint64)fi.nFileSizeHigh << 32) | ((ma_uint64)fi.nFileSizeLow);
  47525. return MA_SUCCESS;
  47526. }
  47527. #else
  47528. static ma_result ma_default_vfs_open__stdio(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47529. {
  47530. ma_result result;
  47531. FILE* pFileStd;
  47532. const char* pOpenModeStr;
  47533. MA_ASSERT(pFilePath != NULL);
  47534. MA_ASSERT(openMode != 0);
  47535. MA_ASSERT(pFile != NULL);
  47536. (void)pVFS;
  47537. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  47538. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  47539. pOpenModeStr = "r+";
  47540. } else {
  47541. pOpenModeStr = "rb";
  47542. }
  47543. } else {
  47544. pOpenModeStr = "wb";
  47545. }
  47546. result = ma_fopen(&pFileStd, pFilePath, pOpenModeStr);
  47547. if (result != MA_SUCCESS) {
  47548. return result;
  47549. }
  47550. *pFile = pFileStd;
  47551. return MA_SUCCESS;
  47552. }
  47553. static ma_result ma_default_vfs_open_w__stdio(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47554. {
  47555. ma_result result;
  47556. FILE* pFileStd;
  47557. const wchar_t* pOpenModeStr;
  47558. MA_ASSERT(pFilePath != NULL);
  47559. MA_ASSERT(openMode != 0);
  47560. MA_ASSERT(pFile != NULL);
  47561. (void)pVFS;
  47562. if ((openMode & MA_OPEN_MODE_READ) != 0) {
  47563. if ((openMode & MA_OPEN_MODE_WRITE) != 0) {
  47564. pOpenModeStr = L"r+";
  47565. } else {
  47566. pOpenModeStr = L"rb";
  47567. }
  47568. } else {
  47569. pOpenModeStr = L"wb";
  47570. }
  47571. result = ma_wfopen(&pFileStd, pFilePath, pOpenModeStr, (pVFS != NULL) ? &((ma_default_vfs*)pVFS)->allocationCallbacks : NULL);
  47572. if (result != MA_SUCCESS) {
  47573. return result;
  47574. }
  47575. *pFile = pFileStd;
  47576. return MA_SUCCESS;
  47577. }
  47578. static ma_result ma_default_vfs_close__stdio(ma_vfs* pVFS, ma_vfs_file file)
  47579. {
  47580. MA_ASSERT(file != NULL);
  47581. (void)pVFS;
  47582. fclose((FILE*)file);
  47583. return MA_SUCCESS;
  47584. }
  47585. static ma_result ma_default_vfs_read__stdio(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  47586. {
  47587. size_t result;
  47588. MA_ASSERT(file != NULL);
  47589. MA_ASSERT(pDst != NULL);
  47590. (void)pVFS;
  47591. result = fread(pDst, 1, sizeInBytes, (FILE*)file);
  47592. if (pBytesRead != NULL) {
  47593. *pBytesRead = result;
  47594. }
  47595. if (result != sizeInBytes) {
  47596. if (result == 0 && feof((FILE*)file)) {
  47597. return MA_AT_END;
  47598. } else {
  47599. return ma_result_from_errno(ferror((FILE*)file));
  47600. }
  47601. }
  47602. return MA_SUCCESS;
  47603. }
  47604. static ma_result ma_default_vfs_write__stdio(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  47605. {
  47606. size_t result;
  47607. MA_ASSERT(file != NULL);
  47608. MA_ASSERT(pSrc != NULL);
  47609. (void)pVFS;
  47610. result = fwrite(pSrc, 1, sizeInBytes, (FILE*)file);
  47611. if (pBytesWritten != NULL) {
  47612. *pBytesWritten = result;
  47613. }
  47614. if (result != sizeInBytes) {
  47615. return ma_result_from_errno(ferror((FILE*)file));
  47616. }
  47617. return MA_SUCCESS;
  47618. }
  47619. static ma_result ma_default_vfs_seek__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  47620. {
  47621. int result;
  47622. int whence;
  47623. MA_ASSERT(file != NULL);
  47624. (void)pVFS;
  47625. if (origin == ma_seek_origin_start) {
  47626. whence = SEEK_SET;
  47627. } else if (origin == ma_seek_origin_end) {
  47628. whence = SEEK_END;
  47629. } else {
  47630. whence = SEEK_CUR;
  47631. }
  47632. #if defined(_WIN32)
  47633. #if defined(_MSC_VER) && _MSC_VER > 1200
  47634. result = _fseeki64((FILE*)file, offset, whence);
  47635. #else
  47636. /* No _fseeki64() so restrict to 31 bits. */
  47637. if (origin > 0x7FFFFFFF) {
  47638. return MA_OUT_OF_RANGE;
  47639. }
  47640. result = fseek((FILE*)file, (int)offset, whence);
  47641. #endif
  47642. #else
  47643. result = fseek((FILE*)file, (long int)offset, whence);
  47644. #endif
  47645. if (result != 0) {
  47646. return MA_ERROR;
  47647. }
  47648. return MA_SUCCESS;
  47649. }
  47650. static ma_result ma_default_vfs_tell__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  47651. {
  47652. ma_int64 result;
  47653. MA_ASSERT(file != NULL);
  47654. MA_ASSERT(pCursor != NULL);
  47655. (void)pVFS;
  47656. #if defined(_WIN32)
  47657. #if defined(_MSC_VER) && _MSC_VER > 1200
  47658. result = _ftelli64((FILE*)file);
  47659. #else
  47660. result = ftell((FILE*)file);
  47661. #endif
  47662. #else
  47663. result = ftell((FILE*)file);
  47664. #endif
  47665. *pCursor = result;
  47666. return MA_SUCCESS;
  47667. }
  47668. #if !defined(_MSC_VER) && !((defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 1) || defined(_XOPEN_SOURCE) || defined(_POSIX_SOURCE)) && !defined(MA_BSD)
  47669. int fileno(FILE *stream);
  47670. #endif
  47671. static ma_result ma_default_vfs_info__stdio(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  47672. {
  47673. int fd;
  47674. struct stat info;
  47675. MA_ASSERT(file != NULL);
  47676. MA_ASSERT(pInfo != NULL);
  47677. (void)pVFS;
  47678. #if defined(_MSC_VER)
  47679. fd = _fileno((FILE*)file);
  47680. #else
  47681. fd = fileno((FILE*)file);
  47682. #endif
  47683. if (fstat(fd, &info) != 0) {
  47684. return ma_result_from_errno(errno);
  47685. }
  47686. pInfo->sizeInBytes = info.st_size;
  47687. return MA_SUCCESS;
  47688. }
  47689. #endif
  47690. static ma_result ma_default_vfs_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47691. {
  47692. if (pFile == NULL) {
  47693. return MA_INVALID_ARGS;
  47694. }
  47695. *pFile = NULL;
  47696. if (pFilePath == NULL || openMode == 0) {
  47697. return MA_INVALID_ARGS;
  47698. }
  47699. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47700. return ma_default_vfs_open__win32(pVFS, pFilePath, openMode, pFile);
  47701. #else
  47702. return ma_default_vfs_open__stdio(pVFS, pFilePath, openMode, pFile);
  47703. #endif
  47704. }
  47705. static ma_result ma_default_vfs_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47706. {
  47707. if (pFile == NULL) {
  47708. return MA_INVALID_ARGS;
  47709. }
  47710. *pFile = NULL;
  47711. if (pFilePath == NULL || openMode == 0) {
  47712. return MA_INVALID_ARGS;
  47713. }
  47714. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47715. return ma_default_vfs_open_w__win32(pVFS, pFilePath, openMode, pFile);
  47716. #else
  47717. return ma_default_vfs_open_w__stdio(pVFS, pFilePath, openMode, pFile);
  47718. #endif
  47719. }
  47720. static ma_result ma_default_vfs_close(ma_vfs* pVFS, ma_vfs_file file)
  47721. {
  47722. if (file == NULL) {
  47723. return MA_INVALID_ARGS;
  47724. }
  47725. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47726. return ma_default_vfs_close__win32(pVFS, file);
  47727. #else
  47728. return ma_default_vfs_close__stdio(pVFS, file);
  47729. #endif
  47730. }
  47731. static ma_result ma_default_vfs_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  47732. {
  47733. if (pBytesRead != NULL) {
  47734. *pBytesRead = 0;
  47735. }
  47736. if (file == NULL || pDst == NULL) {
  47737. return MA_INVALID_ARGS;
  47738. }
  47739. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47740. return ma_default_vfs_read__win32(pVFS, file, pDst, sizeInBytes, pBytesRead);
  47741. #else
  47742. return ma_default_vfs_read__stdio(pVFS, file, pDst, sizeInBytes, pBytesRead);
  47743. #endif
  47744. }
  47745. static ma_result ma_default_vfs_write(ma_vfs* pVFS, ma_vfs_file file, const void* pSrc, size_t sizeInBytes, size_t* pBytesWritten)
  47746. {
  47747. if (pBytesWritten != NULL) {
  47748. *pBytesWritten = 0;
  47749. }
  47750. if (file == NULL || pSrc == NULL) {
  47751. return MA_INVALID_ARGS;
  47752. }
  47753. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47754. return ma_default_vfs_write__win32(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  47755. #else
  47756. return ma_default_vfs_write__stdio(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  47757. #endif
  47758. }
  47759. static ma_result ma_default_vfs_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  47760. {
  47761. if (file == NULL) {
  47762. return MA_INVALID_ARGS;
  47763. }
  47764. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47765. return ma_default_vfs_seek__win32(pVFS, file, offset, origin);
  47766. #else
  47767. return ma_default_vfs_seek__stdio(pVFS, file, offset, origin);
  47768. #endif
  47769. }
  47770. static ma_result ma_default_vfs_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  47771. {
  47772. if (pCursor == NULL) {
  47773. return MA_INVALID_ARGS;
  47774. }
  47775. *pCursor = 0;
  47776. if (file == NULL) {
  47777. return MA_INVALID_ARGS;
  47778. }
  47779. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47780. return ma_default_vfs_tell__win32(pVFS, file, pCursor);
  47781. #else
  47782. return ma_default_vfs_tell__stdio(pVFS, file, pCursor);
  47783. #endif
  47784. }
  47785. static ma_result ma_default_vfs_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  47786. {
  47787. if (pInfo == NULL) {
  47788. return MA_INVALID_ARGS;
  47789. }
  47790. MA_ZERO_OBJECT(pInfo);
  47791. if (file == NULL) {
  47792. return MA_INVALID_ARGS;
  47793. }
  47794. #if defined(MA_WIN32) && defined(MA_WIN32_DESKTOP) && !defined(MA_NO_WIN32_FILEIO)
  47795. return ma_default_vfs_info__win32(pVFS, file, pInfo);
  47796. #else
  47797. return ma_default_vfs_info__stdio(pVFS, file, pInfo);
  47798. #endif
  47799. }
  47800. MA_API ma_result ma_default_vfs_init(ma_default_vfs* pVFS, const ma_allocation_callbacks* pAllocationCallbacks)
  47801. {
  47802. if (pVFS == NULL) {
  47803. return MA_INVALID_ARGS;
  47804. }
  47805. pVFS->cb.onOpen = ma_default_vfs_open;
  47806. pVFS->cb.onOpenW = ma_default_vfs_open_w;
  47807. pVFS->cb.onClose = ma_default_vfs_close;
  47808. pVFS->cb.onRead = ma_default_vfs_read;
  47809. pVFS->cb.onWrite = ma_default_vfs_write;
  47810. pVFS->cb.onSeek = ma_default_vfs_seek;
  47811. pVFS->cb.onTell = ma_default_vfs_tell;
  47812. pVFS->cb.onInfo = ma_default_vfs_info;
  47813. ma_allocation_callbacks_init_copy(&pVFS->allocationCallbacks, pAllocationCallbacks);
  47814. return MA_SUCCESS;
  47815. }
  47816. MA_API ma_result ma_vfs_or_default_open(ma_vfs* pVFS, const char* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47817. {
  47818. if (pVFS != NULL) {
  47819. return ma_vfs_open(pVFS, pFilePath, openMode, pFile);
  47820. } else {
  47821. return ma_default_vfs_open(pVFS, pFilePath, openMode, pFile);
  47822. }
  47823. }
  47824. MA_API ma_result ma_vfs_or_default_open_w(ma_vfs* pVFS, const wchar_t* pFilePath, ma_uint32 openMode, ma_vfs_file* pFile)
  47825. {
  47826. if (pVFS != NULL) {
  47827. return ma_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  47828. } else {
  47829. return ma_default_vfs_open_w(pVFS, pFilePath, openMode, pFile);
  47830. }
  47831. }
  47832. MA_API ma_result ma_vfs_or_default_close(ma_vfs* pVFS, ma_vfs_file file)
  47833. {
  47834. if (pVFS != NULL) {
  47835. return ma_vfs_close(pVFS, file);
  47836. } else {
  47837. return ma_default_vfs_close(pVFS, file);
  47838. }
  47839. }
  47840. MA_API ma_result ma_vfs_or_default_read(ma_vfs* pVFS, ma_vfs_file file, void* pDst, size_t sizeInBytes, size_t* pBytesRead)
  47841. {
  47842. if (pVFS != NULL) {
  47843. return ma_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  47844. } else {
  47845. return ma_default_vfs_read(pVFS, file, pDst, sizeInBytes, pBytesRead);
  47846. }
  47847. }
  47848. 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)
  47849. {
  47850. if (pVFS != NULL) {
  47851. return ma_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  47852. } else {
  47853. return ma_default_vfs_write(pVFS, file, pSrc, sizeInBytes, pBytesWritten);
  47854. }
  47855. }
  47856. MA_API ma_result ma_vfs_or_default_seek(ma_vfs* pVFS, ma_vfs_file file, ma_int64 offset, ma_seek_origin origin)
  47857. {
  47858. if (pVFS != NULL) {
  47859. return ma_vfs_seek(pVFS, file, offset, origin);
  47860. } else {
  47861. return ma_default_vfs_seek(pVFS, file, offset, origin);
  47862. }
  47863. }
  47864. MA_API ma_result ma_vfs_or_default_tell(ma_vfs* pVFS, ma_vfs_file file, ma_int64* pCursor)
  47865. {
  47866. if (pVFS != NULL) {
  47867. return ma_vfs_tell(pVFS, file, pCursor);
  47868. } else {
  47869. return ma_default_vfs_tell(pVFS, file, pCursor);
  47870. }
  47871. }
  47872. MA_API ma_result ma_vfs_or_default_info(ma_vfs* pVFS, ma_vfs_file file, ma_file_info* pInfo)
  47873. {
  47874. if (pVFS != NULL) {
  47875. return ma_vfs_info(pVFS, file, pInfo);
  47876. } else {
  47877. return ma_default_vfs_info(pVFS, file, pInfo);
  47878. }
  47879. }
  47880. /**************************************************************************************************************************************************************
  47881. Decoding and Encoding Headers. These are auto-generated from a tool.
  47882. **************************************************************************************************************************************************************/
  47883. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  47884. /* dr_wav_h begin */
  47885. #ifndef dr_wav_h
  47886. #define dr_wav_h
  47887. #ifdef __cplusplus
  47888. extern "C" {
  47889. #endif
  47890. #define DRWAV_STRINGIFY(x) #x
  47891. #define DRWAV_XSTRINGIFY(x) DRWAV_STRINGIFY(x)
  47892. #define DRWAV_VERSION_MAJOR 0
  47893. #define DRWAV_VERSION_MINOR 13
  47894. #define DRWAV_VERSION_REVISION 7
  47895. #define DRWAV_VERSION_STRING DRWAV_XSTRINGIFY(DRWAV_VERSION_MAJOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_MINOR) "." DRWAV_XSTRINGIFY(DRWAV_VERSION_REVISION)
  47896. #include <stddef.h>
  47897. typedef signed char drwav_int8;
  47898. typedef unsigned char drwav_uint8;
  47899. typedef signed short drwav_int16;
  47900. typedef unsigned short drwav_uint16;
  47901. typedef signed int drwav_int32;
  47902. typedef unsigned int drwav_uint32;
  47903. #if defined(_MSC_VER) && !defined(__clang__)
  47904. typedef signed __int64 drwav_int64;
  47905. typedef unsigned __int64 drwav_uint64;
  47906. #else
  47907. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  47908. #pragma GCC diagnostic push
  47909. #pragma GCC diagnostic ignored "-Wlong-long"
  47910. #if defined(__clang__)
  47911. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  47912. #endif
  47913. #endif
  47914. typedef signed long long drwav_int64;
  47915. typedef unsigned long long drwav_uint64;
  47916. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  47917. #pragma GCC diagnostic pop
  47918. #endif
  47919. #endif
  47920. #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__)
  47921. typedef drwav_uint64 drwav_uintptr;
  47922. #else
  47923. typedef drwav_uint32 drwav_uintptr;
  47924. #endif
  47925. typedef drwav_uint8 drwav_bool8;
  47926. typedef drwav_uint32 drwav_bool32;
  47927. #define DRWAV_TRUE 1
  47928. #define DRWAV_FALSE 0
  47929. #if !defined(DRWAV_API)
  47930. #if defined(DRWAV_DLL)
  47931. #if defined(_WIN32)
  47932. #define DRWAV_DLL_IMPORT __declspec(dllimport)
  47933. #define DRWAV_DLL_EXPORT __declspec(dllexport)
  47934. #define DRWAV_DLL_PRIVATE static
  47935. #else
  47936. #if defined(__GNUC__) && __GNUC__ >= 4
  47937. #define DRWAV_DLL_IMPORT __attribute__((visibility("default")))
  47938. #define DRWAV_DLL_EXPORT __attribute__((visibility("default")))
  47939. #define DRWAV_DLL_PRIVATE __attribute__((visibility("hidden")))
  47940. #else
  47941. #define DRWAV_DLL_IMPORT
  47942. #define DRWAV_DLL_EXPORT
  47943. #define DRWAV_DLL_PRIVATE static
  47944. #endif
  47945. #endif
  47946. #if defined(DR_WAV_IMPLEMENTATION) || defined(DRWAV_IMPLEMENTATION)
  47947. #define DRWAV_API DRWAV_DLL_EXPORT
  47948. #else
  47949. #define DRWAV_API DRWAV_DLL_IMPORT
  47950. #endif
  47951. #define DRWAV_PRIVATE DRWAV_DLL_PRIVATE
  47952. #else
  47953. #define DRWAV_API extern
  47954. #define DRWAV_PRIVATE static
  47955. #endif
  47956. #endif
  47957. typedef drwav_int32 drwav_result;
  47958. #define DRWAV_SUCCESS 0
  47959. #define DRWAV_ERROR -1
  47960. #define DRWAV_INVALID_ARGS -2
  47961. #define DRWAV_INVALID_OPERATION -3
  47962. #define DRWAV_OUT_OF_MEMORY -4
  47963. #define DRWAV_OUT_OF_RANGE -5
  47964. #define DRWAV_ACCESS_DENIED -6
  47965. #define DRWAV_DOES_NOT_EXIST -7
  47966. #define DRWAV_ALREADY_EXISTS -8
  47967. #define DRWAV_TOO_MANY_OPEN_FILES -9
  47968. #define DRWAV_INVALID_FILE -10
  47969. #define DRWAV_TOO_BIG -11
  47970. #define DRWAV_PATH_TOO_LONG -12
  47971. #define DRWAV_NAME_TOO_LONG -13
  47972. #define DRWAV_NOT_DIRECTORY -14
  47973. #define DRWAV_IS_DIRECTORY -15
  47974. #define DRWAV_DIRECTORY_NOT_EMPTY -16
  47975. #define DRWAV_END_OF_FILE -17
  47976. #define DRWAV_NO_SPACE -18
  47977. #define DRWAV_BUSY -19
  47978. #define DRWAV_IO_ERROR -20
  47979. #define DRWAV_INTERRUPT -21
  47980. #define DRWAV_UNAVAILABLE -22
  47981. #define DRWAV_ALREADY_IN_USE -23
  47982. #define DRWAV_BAD_ADDRESS -24
  47983. #define DRWAV_BAD_SEEK -25
  47984. #define DRWAV_BAD_PIPE -26
  47985. #define DRWAV_DEADLOCK -27
  47986. #define DRWAV_TOO_MANY_LINKS -28
  47987. #define DRWAV_NOT_IMPLEMENTED -29
  47988. #define DRWAV_NO_MESSAGE -30
  47989. #define DRWAV_BAD_MESSAGE -31
  47990. #define DRWAV_NO_DATA_AVAILABLE -32
  47991. #define DRWAV_INVALID_DATA -33
  47992. #define DRWAV_TIMEOUT -34
  47993. #define DRWAV_NO_NETWORK -35
  47994. #define DRWAV_NOT_UNIQUE -36
  47995. #define DRWAV_NOT_SOCKET -37
  47996. #define DRWAV_NO_ADDRESS -38
  47997. #define DRWAV_BAD_PROTOCOL -39
  47998. #define DRWAV_PROTOCOL_UNAVAILABLE -40
  47999. #define DRWAV_PROTOCOL_NOT_SUPPORTED -41
  48000. #define DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  48001. #define DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED -43
  48002. #define DRWAV_SOCKET_NOT_SUPPORTED -44
  48003. #define DRWAV_CONNECTION_RESET -45
  48004. #define DRWAV_ALREADY_CONNECTED -46
  48005. #define DRWAV_NOT_CONNECTED -47
  48006. #define DRWAV_CONNECTION_REFUSED -48
  48007. #define DRWAV_NO_HOST -49
  48008. #define DRWAV_IN_PROGRESS -50
  48009. #define DRWAV_CANCELLED -51
  48010. #define DRWAV_MEMORY_ALREADY_MAPPED -52
  48011. #define DRWAV_AT_END -53
  48012. #define DR_WAVE_FORMAT_PCM 0x1
  48013. #define DR_WAVE_FORMAT_ADPCM 0x2
  48014. #define DR_WAVE_FORMAT_IEEE_FLOAT 0x3
  48015. #define DR_WAVE_FORMAT_ALAW 0x6
  48016. #define DR_WAVE_FORMAT_MULAW 0x7
  48017. #define DR_WAVE_FORMAT_DVI_ADPCM 0x11
  48018. #define DR_WAVE_FORMAT_EXTENSIBLE 0xFFFE
  48019. #define DRWAV_SEQUENTIAL 0x00000001
  48020. DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision);
  48021. DRWAV_API const char* drwav_version_string(void);
  48022. typedef enum
  48023. {
  48024. drwav_seek_origin_start,
  48025. drwav_seek_origin_current
  48026. } drwav_seek_origin;
  48027. typedef enum
  48028. {
  48029. drwav_container_riff,
  48030. drwav_container_w64,
  48031. drwav_container_rf64
  48032. } drwav_container;
  48033. typedef struct
  48034. {
  48035. union
  48036. {
  48037. drwav_uint8 fourcc[4];
  48038. drwav_uint8 guid[16];
  48039. } id;
  48040. drwav_uint64 sizeInBytes;
  48041. unsigned int paddingSize;
  48042. } drwav_chunk_header;
  48043. typedef struct
  48044. {
  48045. drwav_uint16 formatTag;
  48046. drwav_uint16 channels;
  48047. drwav_uint32 sampleRate;
  48048. drwav_uint32 avgBytesPerSec;
  48049. drwav_uint16 blockAlign;
  48050. drwav_uint16 bitsPerSample;
  48051. drwav_uint16 extendedSize;
  48052. drwav_uint16 validBitsPerSample;
  48053. drwav_uint32 channelMask;
  48054. drwav_uint8 subFormat[16];
  48055. } drwav_fmt;
  48056. DRWAV_API drwav_uint16 drwav_fmt_get_format(const drwav_fmt* pFMT);
  48057. typedef size_t (* drwav_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  48058. typedef size_t (* drwav_write_proc)(void* pUserData, const void* pData, size_t bytesToWrite);
  48059. typedef drwav_bool32 (* drwav_seek_proc)(void* pUserData, int offset, drwav_seek_origin origin);
  48060. typedef drwav_uint64 (* drwav_chunk_proc)(void* pChunkUserData, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_chunk_header* pChunkHeader, drwav_container container, const drwav_fmt* pFMT);
  48061. typedef struct
  48062. {
  48063. void* pUserData;
  48064. void* (* onMalloc)(size_t sz, void* pUserData);
  48065. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  48066. void (* onFree)(void* p, void* pUserData);
  48067. } drwav_allocation_callbacks;
  48068. typedef struct
  48069. {
  48070. const drwav_uint8* data;
  48071. size_t dataSize;
  48072. size_t currentReadPos;
  48073. } drwav__memory_stream;
  48074. typedef struct
  48075. {
  48076. void** ppData;
  48077. size_t* pDataSize;
  48078. size_t dataSize;
  48079. size_t dataCapacity;
  48080. size_t currentWritePos;
  48081. } drwav__memory_stream_write;
  48082. typedef struct
  48083. {
  48084. drwav_container container;
  48085. drwav_uint32 format;
  48086. drwav_uint32 channels;
  48087. drwav_uint32 sampleRate;
  48088. drwav_uint32 bitsPerSample;
  48089. } drwav_data_format;
  48090. typedef enum
  48091. {
  48092. drwav_metadata_type_none = 0,
  48093. drwav_metadata_type_unknown = 1 << 0,
  48094. drwav_metadata_type_smpl = 1 << 1,
  48095. drwav_metadata_type_inst = 1 << 2,
  48096. drwav_metadata_type_cue = 1 << 3,
  48097. drwav_metadata_type_acid = 1 << 4,
  48098. drwav_metadata_type_bext = 1 << 5,
  48099. drwav_metadata_type_list_label = 1 << 6,
  48100. drwav_metadata_type_list_note = 1 << 7,
  48101. drwav_metadata_type_list_labelled_cue_region = 1 << 8,
  48102. drwav_metadata_type_list_info_software = 1 << 9,
  48103. drwav_metadata_type_list_info_copyright = 1 << 10,
  48104. drwav_metadata_type_list_info_title = 1 << 11,
  48105. drwav_metadata_type_list_info_artist = 1 << 12,
  48106. drwav_metadata_type_list_info_comment = 1 << 13,
  48107. drwav_metadata_type_list_info_date = 1 << 14,
  48108. drwav_metadata_type_list_info_genre = 1 << 15,
  48109. drwav_metadata_type_list_info_album = 1 << 16,
  48110. drwav_metadata_type_list_info_tracknumber = 1 << 17,
  48111. drwav_metadata_type_list_all_info_strings = drwav_metadata_type_list_info_software
  48112. | drwav_metadata_type_list_info_copyright
  48113. | drwav_metadata_type_list_info_title
  48114. | drwav_metadata_type_list_info_artist
  48115. | drwav_metadata_type_list_info_comment
  48116. | drwav_metadata_type_list_info_date
  48117. | drwav_metadata_type_list_info_genre
  48118. | drwav_metadata_type_list_info_album
  48119. | drwav_metadata_type_list_info_tracknumber,
  48120. drwav_metadata_type_list_all_adtl = drwav_metadata_type_list_label
  48121. | drwav_metadata_type_list_note
  48122. | drwav_metadata_type_list_labelled_cue_region,
  48123. drwav_metadata_type_all = -2,
  48124. drwav_metadata_type_all_including_unknown = -1
  48125. } drwav_metadata_type;
  48126. typedef enum
  48127. {
  48128. drwav_smpl_loop_type_forward = 0,
  48129. drwav_smpl_loop_type_pingpong = 1,
  48130. drwav_smpl_loop_type_backward = 2
  48131. } drwav_smpl_loop_type;
  48132. typedef struct
  48133. {
  48134. drwav_uint32 cuePointId;
  48135. drwav_uint32 type;
  48136. drwav_uint32 firstSampleByteOffset;
  48137. drwav_uint32 lastSampleByteOffset;
  48138. drwav_uint32 sampleFraction;
  48139. drwav_uint32 playCount;
  48140. } drwav_smpl_loop;
  48141. typedef struct
  48142. {
  48143. drwav_uint32 manufacturerId;
  48144. drwav_uint32 productId;
  48145. drwav_uint32 samplePeriodNanoseconds;
  48146. drwav_uint32 midiUnityNote;
  48147. drwav_uint32 midiPitchFraction;
  48148. drwav_uint32 smpteFormat;
  48149. drwav_uint32 smpteOffset;
  48150. drwav_uint32 sampleLoopCount;
  48151. drwav_uint32 samplerSpecificDataSizeInBytes;
  48152. drwav_smpl_loop* pLoops;
  48153. drwav_uint8* pSamplerSpecificData;
  48154. } drwav_smpl;
  48155. typedef struct
  48156. {
  48157. drwav_int8 midiUnityNote;
  48158. drwav_int8 fineTuneCents;
  48159. drwav_int8 gainDecibels;
  48160. drwav_int8 lowNote;
  48161. drwav_int8 highNote;
  48162. drwav_int8 lowVelocity;
  48163. drwav_int8 highVelocity;
  48164. } drwav_inst;
  48165. typedef struct
  48166. {
  48167. drwav_uint32 id;
  48168. drwav_uint32 playOrderPosition;
  48169. drwav_uint8 dataChunkId[4];
  48170. drwav_uint32 chunkStart;
  48171. drwav_uint32 blockStart;
  48172. drwav_uint32 sampleByteOffset;
  48173. } drwav_cue_point;
  48174. typedef struct
  48175. {
  48176. drwav_uint32 cuePointCount;
  48177. drwav_cue_point *pCuePoints;
  48178. } drwav_cue;
  48179. typedef enum
  48180. {
  48181. drwav_acid_flag_one_shot = 1,
  48182. drwav_acid_flag_root_note_set = 2,
  48183. drwav_acid_flag_stretch = 4,
  48184. drwav_acid_flag_disk_based = 8,
  48185. drwav_acid_flag_acidizer = 16
  48186. } drwav_acid_flag;
  48187. typedef struct
  48188. {
  48189. drwav_uint32 flags;
  48190. drwav_uint16 midiUnityNote;
  48191. drwav_uint16 reserved1;
  48192. float reserved2;
  48193. drwav_uint32 numBeats;
  48194. drwav_uint16 meterDenominator;
  48195. drwav_uint16 meterNumerator;
  48196. float tempo;
  48197. } drwav_acid;
  48198. typedef struct
  48199. {
  48200. drwav_uint32 cuePointId;
  48201. drwav_uint32 stringLength;
  48202. char* pString;
  48203. } drwav_list_label_or_note;
  48204. typedef struct
  48205. {
  48206. char* pDescription;
  48207. char* pOriginatorName;
  48208. char* pOriginatorReference;
  48209. char pOriginationDate[10];
  48210. char pOriginationTime[8];
  48211. drwav_uint64 timeReference;
  48212. drwav_uint16 version;
  48213. char* pCodingHistory;
  48214. drwav_uint32 codingHistorySize;
  48215. drwav_uint8* pUMID;
  48216. drwav_uint16 loudnessValue;
  48217. drwav_uint16 loudnessRange;
  48218. drwav_uint16 maxTruePeakLevel;
  48219. drwav_uint16 maxMomentaryLoudness;
  48220. drwav_uint16 maxShortTermLoudness;
  48221. } drwav_bext;
  48222. typedef struct
  48223. {
  48224. drwav_uint32 stringLength;
  48225. char* pString;
  48226. } drwav_list_info_text;
  48227. typedef struct
  48228. {
  48229. drwav_uint32 cuePointId;
  48230. drwav_uint32 sampleLength;
  48231. drwav_uint8 purposeId[4];
  48232. drwav_uint16 country;
  48233. drwav_uint16 language;
  48234. drwav_uint16 dialect;
  48235. drwav_uint16 codePage;
  48236. drwav_uint32 stringLength;
  48237. char* pString;
  48238. } drwav_list_labelled_cue_region;
  48239. typedef enum
  48240. {
  48241. drwav_metadata_location_invalid,
  48242. drwav_metadata_location_top_level,
  48243. drwav_metadata_location_inside_info_list,
  48244. drwav_metadata_location_inside_adtl_list
  48245. } drwav_metadata_location;
  48246. typedef struct
  48247. {
  48248. drwav_uint8 id[4];
  48249. drwav_metadata_location chunkLocation;
  48250. drwav_uint32 dataSizeInBytes;
  48251. drwav_uint8* pData;
  48252. } drwav_unknown_metadata;
  48253. typedef struct
  48254. {
  48255. drwav_metadata_type type;
  48256. union
  48257. {
  48258. drwav_cue cue;
  48259. drwav_smpl smpl;
  48260. drwav_acid acid;
  48261. drwav_inst inst;
  48262. drwav_bext bext;
  48263. drwav_list_label_or_note labelOrNote;
  48264. drwav_list_labelled_cue_region labelledCueRegion;
  48265. drwav_list_info_text infoText;
  48266. drwav_unknown_metadata unknown;
  48267. } data;
  48268. } drwav_metadata;
  48269. typedef struct
  48270. {
  48271. drwav_read_proc onRead;
  48272. drwav_write_proc onWrite;
  48273. drwav_seek_proc onSeek;
  48274. void* pUserData;
  48275. drwav_allocation_callbacks allocationCallbacks;
  48276. drwav_container container;
  48277. drwav_fmt fmt;
  48278. drwav_uint32 sampleRate;
  48279. drwav_uint16 channels;
  48280. drwav_uint16 bitsPerSample;
  48281. drwav_uint16 translatedFormatTag;
  48282. drwav_uint64 totalPCMFrameCount;
  48283. drwav_uint64 dataChunkDataSize;
  48284. drwav_uint64 dataChunkDataPos;
  48285. drwav_uint64 bytesRemaining;
  48286. drwav_uint64 readCursorInPCMFrames;
  48287. drwav_uint64 dataChunkDataSizeTargetWrite;
  48288. drwav_bool32 isSequentialWrite;
  48289. drwav_metadata_type allowedMetadataTypes;
  48290. drwav_metadata* pMetadata;
  48291. drwav_uint32 metadataCount;
  48292. drwav__memory_stream memoryStream;
  48293. drwav__memory_stream_write memoryStreamWrite;
  48294. struct
  48295. {
  48296. drwav_uint32 bytesRemainingInBlock;
  48297. drwav_uint16 predictor[2];
  48298. drwav_int32 delta[2];
  48299. drwav_int32 cachedFrames[4];
  48300. drwav_uint32 cachedFrameCount;
  48301. drwav_int32 prevFrames[2][2];
  48302. } msadpcm;
  48303. struct
  48304. {
  48305. drwav_uint32 bytesRemainingInBlock;
  48306. drwav_int32 predictor[2];
  48307. drwav_int32 stepIndex[2];
  48308. drwav_int32 cachedFrames[16];
  48309. drwav_uint32 cachedFrameCount;
  48310. } ima;
  48311. } drwav;
  48312. DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  48313. DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48314. DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48315. DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  48316. DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  48317. DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks);
  48318. DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount);
  48319. DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalFrameCount, drwav_metadata* pMetadata, drwav_uint32 metadataCount);
  48320. DRWAV_API drwav_metadata* drwav_take_ownership_of_metadata(drwav* pWav);
  48321. DRWAV_API drwav_result drwav_uninit(drwav* pWav);
  48322. DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut);
  48323. DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  48324. DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  48325. DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut);
  48326. DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex);
  48327. DRWAV_API drwav_result drwav_get_cursor_in_pcm_frames(drwav* pWav, drwav_uint64* pCursor);
  48328. DRWAV_API drwav_result drwav_get_length_in_pcm_frames(drwav* pWav, drwav_uint64* pLength);
  48329. DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData);
  48330. DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  48331. DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  48332. DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData);
  48333. #ifndef DR_WAV_NO_CONVERSION_API
  48334. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  48335. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  48336. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut);
  48337. DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48338. DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48339. DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount);
  48340. DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount);
  48341. DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount);
  48342. DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48343. DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48344. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  48345. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  48346. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut);
  48347. DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48348. DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount);
  48349. DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48350. DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount);
  48351. DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount);
  48352. DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48353. DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48354. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  48355. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  48356. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut);
  48357. DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48358. DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount);
  48359. DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48360. DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount);
  48361. DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount);
  48362. DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48363. DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount);
  48364. #endif
  48365. #ifndef DR_WAV_NO_STDIO
  48366. DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
  48367. DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48368. DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks);
  48369. DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48370. DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48371. DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48372. DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  48373. DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48374. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48375. DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  48376. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48377. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48378. #endif
  48379. DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks);
  48380. DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48381. DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks);
  48382. DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks);
  48383. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48384. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks);
  48385. #ifndef DR_WAV_NO_CONVERSION_API
  48386. DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48387. DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48388. DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48389. #ifndef DR_WAV_NO_STDIO
  48390. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48391. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48392. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48393. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48394. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48395. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48396. #endif
  48397. DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48398. DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48399. DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks);
  48400. #endif
  48401. DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks);
  48402. DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data);
  48403. DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data);
  48404. DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data);
  48405. DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data);
  48406. DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data);
  48407. DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data);
  48408. DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data);
  48409. DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16]);
  48410. DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b);
  48411. #ifdef __cplusplus
  48412. }
  48413. #endif
  48414. #endif
  48415. /* dr_wav_h end */
  48416. #endif /* MA_NO_WAV */
  48417. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  48418. /* dr_flac_h begin */
  48419. #ifndef dr_flac_h
  48420. #define dr_flac_h
  48421. #ifdef __cplusplus
  48422. extern "C" {
  48423. #endif
  48424. #define DRFLAC_STRINGIFY(x) #x
  48425. #define DRFLAC_XSTRINGIFY(x) DRFLAC_STRINGIFY(x)
  48426. #define DRFLAC_VERSION_MAJOR 0
  48427. #define DRFLAC_VERSION_MINOR 12
  48428. #define DRFLAC_VERSION_REVISION 39
  48429. #define DRFLAC_VERSION_STRING DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MAJOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_MINOR) "." DRFLAC_XSTRINGIFY(DRFLAC_VERSION_REVISION)
  48430. #include <stddef.h>
  48431. typedef signed char drflac_int8;
  48432. typedef unsigned char drflac_uint8;
  48433. typedef signed short drflac_int16;
  48434. typedef unsigned short drflac_uint16;
  48435. typedef signed int drflac_int32;
  48436. typedef unsigned int drflac_uint32;
  48437. #if defined(_MSC_VER) && !defined(__clang__)
  48438. typedef signed __int64 drflac_int64;
  48439. typedef unsigned __int64 drflac_uint64;
  48440. #else
  48441. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  48442. #pragma GCC diagnostic push
  48443. #pragma GCC diagnostic ignored "-Wlong-long"
  48444. #if defined(__clang__)
  48445. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  48446. #endif
  48447. #endif
  48448. typedef signed long long drflac_int64;
  48449. typedef unsigned long long drflac_uint64;
  48450. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  48451. #pragma GCC diagnostic pop
  48452. #endif
  48453. #endif
  48454. #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__)
  48455. typedef drflac_uint64 drflac_uintptr;
  48456. #else
  48457. typedef drflac_uint32 drflac_uintptr;
  48458. #endif
  48459. typedef drflac_uint8 drflac_bool8;
  48460. typedef drflac_uint32 drflac_bool32;
  48461. #define DRFLAC_TRUE 1
  48462. #define DRFLAC_FALSE 0
  48463. #if !defined(DRFLAC_API)
  48464. #if defined(DRFLAC_DLL)
  48465. #if defined(_WIN32)
  48466. #define DRFLAC_DLL_IMPORT __declspec(dllimport)
  48467. #define DRFLAC_DLL_EXPORT __declspec(dllexport)
  48468. #define DRFLAC_DLL_PRIVATE static
  48469. #else
  48470. #if defined(__GNUC__) && __GNUC__ >= 4
  48471. #define DRFLAC_DLL_IMPORT __attribute__((visibility("default")))
  48472. #define DRFLAC_DLL_EXPORT __attribute__((visibility("default")))
  48473. #define DRFLAC_DLL_PRIVATE __attribute__((visibility("hidden")))
  48474. #else
  48475. #define DRFLAC_DLL_IMPORT
  48476. #define DRFLAC_DLL_EXPORT
  48477. #define DRFLAC_DLL_PRIVATE static
  48478. #endif
  48479. #endif
  48480. #if defined(DR_FLAC_IMPLEMENTATION) || defined(DRFLAC_IMPLEMENTATION)
  48481. #define DRFLAC_API DRFLAC_DLL_EXPORT
  48482. #else
  48483. #define DRFLAC_API DRFLAC_DLL_IMPORT
  48484. #endif
  48485. #define DRFLAC_PRIVATE DRFLAC_DLL_PRIVATE
  48486. #else
  48487. #define DRFLAC_API extern
  48488. #define DRFLAC_PRIVATE static
  48489. #endif
  48490. #endif
  48491. #if defined(_MSC_VER) && _MSC_VER >= 1700
  48492. #define DRFLAC_DEPRECATED __declspec(deprecated)
  48493. #elif (defined(__GNUC__) && __GNUC__ >= 4)
  48494. #define DRFLAC_DEPRECATED __attribute__((deprecated))
  48495. #elif defined(__has_feature)
  48496. #if __has_feature(attribute_deprecated)
  48497. #define DRFLAC_DEPRECATED __attribute__((deprecated))
  48498. #else
  48499. #define DRFLAC_DEPRECATED
  48500. #endif
  48501. #else
  48502. #define DRFLAC_DEPRECATED
  48503. #endif
  48504. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision);
  48505. DRFLAC_API const char* drflac_version_string(void);
  48506. #ifndef DR_FLAC_BUFFER_SIZE
  48507. #define DR_FLAC_BUFFER_SIZE 4096
  48508. #endif
  48509. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  48510. #define DRFLAC_64BIT
  48511. #endif
  48512. #ifdef DRFLAC_64BIT
  48513. typedef drflac_uint64 drflac_cache_t;
  48514. #else
  48515. typedef drflac_uint32 drflac_cache_t;
  48516. #endif
  48517. #define DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO 0
  48518. #define DRFLAC_METADATA_BLOCK_TYPE_PADDING 1
  48519. #define DRFLAC_METADATA_BLOCK_TYPE_APPLICATION 2
  48520. #define DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE 3
  48521. #define DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT 4
  48522. #define DRFLAC_METADATA_BLOCK_TYPE_CUESHEET 5
  48523. #define DRFLAC_METADATA_BLOCK_TYPE_PICTURE 6
  48524. #define DRFLAC_METADATA_BLOCK_TYPE_INVALID 127
  48525. #define DRFLAC_PICTURE_TYPE_OTHER 0
  48526. #define DRFLAC_PICTURE_TYPE_FILE_ICON 1
  48527. #define DRFLAC_PICTURE_TYPE_OTHER_FILE_ICON 2
  48528. #define DRFLAC_PICTURE_TYPE_COVER_FRONT 3
  48529. #define DRFLAC_PICTURE_TYPE_COVER_BACK 4
  48530. #define DRFLAC_PICTURE_TYPE_LEAFLET_PAGE 5
  48531. #define DRFLAC_PICTURE_TYPE_MEDIA 6
  48532. #define DRFLAC_PICTURE_TYPE_LEAD_ARTIST 7
  48533. #define DRFLAC_PICTURE_TYPE_ARTIST 8
  48534. #define DRFLAC_PICTURE_TYPE_CONDUCTOR 9
  48535. #define DRFLAC_PICTURE_TYPE_BAND 10
  48536. #define DRFLAC_PICTURE_TYPE_COMPOSER 11
  48537. #define DRFLAC_PICTURE_TYPE_LYRICIST 12
  48538. #define DRFLAC_PICTURE_TYPE_RECORDING_LOCATION 13
  48539. #define DRFLAC_PICTURE_TYPE_DURING_RECORDING 14
  48540. #define DRFLAC_PICTURE_TYPE_DURING_PERFORMANCE 15
  48541. #define DRFLAC_PICTURE_TYPE_SCREEN_CAPTURE 16
  48542. #define DRFLAC_PICTURE_TYPE_BRIGHT_COLORED_FISH 17
  48543. #define DRFLAC_PICTURE_TYPE_ILLUSTRATION 18
  48544. #define DRFLAC_PICTURE_TYPE_BAND_LOGOTYPE 19
  48545. #define DRFLAC_PICTURE_TYPE_PUBLISHER_LOGOTYPE 20
  48546. typedef enum
  48547. {
  48548. drflac_container_native,
  48549. drflac_container_ogg,
  48550. drflac_container_unknown
  48551. } drflac_container;
  48552. typedef enum
  48553. {
  48554. drflac_seek_origin_start,
  48555. drflac_seek_origin_current
  48556. } drflac_seek_origin;
  48557. typedef struct
  48558. {
  48559. drflac_uint64 firstPCMFrame;
  48560. drflac_uint64 flacFrameOffset;
  48561. drflac_uint16 pcmFrameCount;
  48562. } drflac_seekpoint;
  48563. typedef struct
  48564. {
  48565. drflac_uint16 minBlockSizeInPCMFrames;
  48566. drflac_uint16 maxBlockSizeInPCMFrames;
  48567. drflac_uint32 minFrameSizeInPCMFrames;
  48568. drflac_uint32 maxFrameSizeInPCMFrames;
  48569. drflac_uint32 sampleRate;
  48570. drflac_uint8 channels;
  48571. drflac_uint8 bitsPerSample;
  48572. drflac_uint64 totalPCMFrameCount;
  48573. drflac_uint8 md5[16];
  48574. } drflac_streaminfo;
  48575. typedef struct
  48576. {
  48577. drflac_uint32 type;
  48578. const void* pRawData;
  48579. drflac_uint32 rawDataSize;
  48580. union
  48581. {
  48582. drflac_streaminfo streaminfo;
  48583. struct
  48584. {
  48585. int unused;
  48586. } padding;
  48587. struct
  48588. {
  48589. drflac_uint32 id;
  48590. const void* pData;
  48591. drflac_uint32 dataSize;
  48592. } application;
  48593. struct
  48594. {
  48595. drflac_uint32 seekpointCount;
  48596. const drflac_seekpoint* pSeekpoints;
  48597. } seektable;
  48598. struct
  48599. {
  48600. drflac_uint32 vendorLength;
  48601. const char* vendor;
  48602. drflac_uint32 commentCount;
  48603. const void* pComments;
  48604. } vorbis_comment;
  48605. struct
  48606. {
  48607. char catalog[128];
  48608. drflac_uint64 leadInSampleCount;
  48609. drflac_bool32 isCD;
  48610. drflac_uint8 trackCount;
  48611. const void* pTrackData;
  48612. } cuesheet;
  48613. struct
  48614. {
  48615. drflac_uint32 type;
  48616. drflac_uint32 mimeLength;
  48617. const char* mime;
  48618. drflac_uint32 descriptionLength;
  48619. const char* description;
  48620. drflac_uint32 width;
  48621. drflac_uint32 height;
  48622. drflac_uint32 colorDepth;
  48623. drflac_uint32 indexColorCount;
  48624. drflac_uint32 pictureDataSize;
  48625. const drflac_uint8* pPictureData;
  48626. } picture;
  48627. } data;
  48628. } drflac_metadata;
  48629. typedef size_t (* drflac_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  48630. typedef drflac_bool32 (* drflac_seek_proc)(void* pUserData, int offset, drflac_seek_origin origin);
  48631. typedef void (* drflac_meta_proc)(void* pUserData, drflac_metadata* pMetadata);
  48632. typedef struct
  48633. {
  48634. void* pUserData;
  48635. void* (* onMalloc)(size_t sz, void* pUserData);
  48636. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  48637. void (* onFree)(void* p, void* pUserData);
  48638. } drflac_allocation_callbacks;
  48639. typedef struct
  48640. {
  48641. const drflac_uint8* data;
  48642. size_t dataSize;
  48643. size_t currentReadPos;
  48644. } drflac__memory_stream;
  48645. typedef struct
  48646. {
  48647. drflac_read_proc onRead;
  48648. drflac_seek_proc onSeek;
  48649. void* pUserData;
  48650. size_t unalignedByteCount;
  48651. drflac_cache_t unalignedCache;
  48652. drflac_uint32 nextL2Line;
  48653. drflac_uint32 consumedBits;
  48654. drflac_cache_t cacheL2[DR_FLAC_BUFFER_SIZE/sizeof(drflac_cache_t)];
  48655. drflac_cache_t cache;
  48656. drflac_uint16 crc16;
  48657. drflac_cache_t crc16Cache;
  48658. drflac_uint32 crc16CacheIgnoredBytes;
  48659. } drflac_bs;
  48660. typedef struct
  48661. {
  48662. drflac_uint8 subframeType;
  48663. drflac_uint8 wastedBitsPerSample;
  48664. drflac_uint8 lpcOrder;
  48665. drflac_int32* pSamplesS32;
  48666. } drflac_subframe;
  48667. typedef struct
  48668. {
  48669. drflac_uint64 pcmFrameNumber;
  48670. drflac_uint32 flacFrameNumber;
  48671. drflac_uint32 sampleRate;
  48672. drflac_uint16 blockSizeInPCMFrames;
  48673. drflac_uint8 channelAssignment;
  48674. drflac_uint8 bitsPerSample;
  48675. drflac_uint8 crc8;
  48676. } drflac_frame_header;
  48677. typedef struct
  48678. {
  48679. drflac_frame_header header;
  48680. drflac_uint32 pcmFramesRemaining;
  48681. drflac_subframe subframes[8];
  48682. } drflac_frame;
  48683. typedef struct
  48684. {
  48685. drflac_meta_proc onMeta;
  48686. void* pUserDataMD;
  48687. drflac_allocation_callbacks allocationCallbacks;
  48688. drflac_uint32 sampleRate;
  48689. drflac_uint8 channels;
  48690. drflac_uint8 bitsPerSample;
  48691. drflac_uint16 maxBlockSizeInPCMFrames;
  48692. drflac_uint64 totalPCMFrameCount;
  48693. drflac_container container;
  48694. drflac_uint32 seekpointCount;
  48695. drflac_frame currentFLACFrame;
  48696. drflac_uint64 currentPCMFrame;
  48697. drflac_uint64 firstFLACFramePosInBytes;
  48698. drflac__memory_stream memoryStream;
  48699. drflac_int32* pDecodedSamples;
  48700. drflac_seekpoint* pSeekpoints;
  48701. void* _oggbs;
  48702. drflac_bool32 _noSeekTableSeek : 1;
  48703. drflac_bool32 _noBinarySearchSeek : 1;
  48704. drflac_bool32 _noBruteForceSeek : 1;
  48705. drflac_bs bs;
  48706. drflac_uint8 pExtraData[1];
  48707. } drflac;
  48708. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48709. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48710. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48711. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48712. DRFLAC_API void drflac_close(drflac* pFlac);
  48713. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut);
  48714. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut);
  48715. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut);
  48716. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex);
  48717. #ifndef DR_FLAC_NO_STDIO
  48718. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  48719. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks);
  48720. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48721. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48722. #endif
  48723. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks);
  48724. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks);
  48725. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48726. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48727. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48728. #ifndef DR_FLAC_NO_STDIO
  48729. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48730. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48731. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48732. #endif
  48733. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48734. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48735. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks);
  48736. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks);
  48737. typedef struct
  48738. {
  48739. drflac_uint32 countRemaining;
  48740. const char* pRunningData;
  48741. } drflac_vorbis_comment_iterator;
  48742. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments);
  48743. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut);
  48744. typedef struct
  48745. {
  48746. drflac_uint32 countRemaining;
  48747. const char* pRunningData;
  48748. } drflac_cuesheet_track_iterator;
  48749. typedef struct
  48750. {
  48751. drflac_uint64 offset;
  48752. drflac_uint8 index;
  48753. drflac_uint8 reserved[3];
  48754. } drflac_cuesheet_track_index;
  48755. typedef struct
  48756. {
  48757. drflac_uint64 offset;
  48758. drflac_uint8 trackNumber;
  48759. char ISRC[12];
  48760. drflac_bool8 isAudio;
  48761. drflac_bool8 preEmphasis;
  48762. drflac_uint8 indexCount;
  48763. const drflac_cuesheet_track_index* pIndexPoints;
  48764. } drflac_cuesheet_track;
  48765. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData);
  48766. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack);
  48767. #ifdef __cplusplus
  48768. }
  48769. #endif
  48770. #endif
  48771. /* dr_flac_h end */
  48772. #endif /* MA_NO_FLAC */
  48773. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  48774. /* dr_mp3_h begin */
  48775. #ifndef dr_mp3_h
  48776. #define dr_mp3_h
  48777. #ifdef __cplusplus
  48778. extern "C" {
  48779. #endif
  48780. #define DRMP3_STRINGIFY(x) #x
  48781. #define DRMP3_XSTRINGIFY(x) DRMP3_STRINGIFY(x)
  48782. #define DRMP3_VERSION_MAJOR 0
  48783. #define DRMP3_VERSION_MINOR 6
  48784. #define DRMP3_VERSION_REVISION 34
  48785. #define DRMP3_VERSION_STRING DRMP3_XSTRINGIFY(DRMP3_VERSION_MAJOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_MINOR) "." DRMP3_XSTRINGIFY(DRMP3_VERSION_REVISION)
  48786. #include <stddef.h>
  48787. typedef signed char drmp3_int8;
  48788. typedef unsigned char drmp3_uint8;
  48789. typedef signed short drmp3_int16;
  48790. typedef unsigned short drmp3_uint16;
  48791. typedef signed int drmp3_int32;
  48792. typedef unsigned int drmp3_uint32;
  48793. #if defined(_MSC_VER) && !defined(__clang__)
  48794. typedef signed __int64 drmp3_int64;
  48795. typedef unsigned __int64 drmp3_uint64;
  48796. #else
  48797. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  48798. #pragma GCC diagnostic push
  48799. #pragma GCC diagnostic ignored "-Wlong-long"
  48800. #if defined(__clang__)
  48801. #pragma GCC diagnostic ignored "-Wc++11-long-long"
  48802. #endif
  48803. #endif
  48804. typedef signed long long drmp3_int64;
  48805. typedef unsigned long long drmp3_uint64;
  48806. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  48807. #pragma GCC diagnostic pop
  48808. #endif
  48809. #endif
  48810. #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__)
  48811. typedef drmp3_uint64 drmp3_uintptr;
  48812. #else
  48813. typedef drmp3_uint32 drmp3_uintptr;
  48814. #endif
  48815. typedef drmp3_uint8 drmp3_bool8;
  48816. typedef drmp3_uint32 drmp3_bool32;
  48817. #define DRMP3_TRUE 1
  48818. #define DRMP3_FALSE 0
  48819. #if !defined(DRMP3_API)
  48820. #if defined(DRMP3_DLL)
  48821. #if defined(_WIN32)
  48822. #define DRMP3_DLL_IMPORT __declspec(dllimport)
  48823. #define DRMP3_DLL_EXPORT __declspec(dllexport)
  48824. #define DRMP3_DLL_PRIVATE static
  48825. #else
  48826. #if defined(__GNUC__) && __GNUC__ >= 4
  48827. #define DRMP3_DLL_IMPORT __attribute__((visibility("default")))
  48828. #define DRMP3_DLL_EXPORT __attribute__((visibility("default")))
  48829. #define DRMP3_DLL_PRIVATE __attribute__((visibility("hidden")))
  48830. #else
  48831. #define DRMP3_DLL_IMPORT
  48832. #define DRMP3_DLL_EXPORT
  48833. #define DRMP3_DLL_PRIVATE static
  48834. #endif
  48835. #endif
  48836. #if defined(DR_MP3_IMPLEMENTATION) || defined(DRMP3_IMPLEMENTATION)
  48837. #define DRMP3_API DRMP3_DLL_EXPORT
  48838. #else
  48839. #define DRMP3_API DRMP3_DLL_IMPORT
  48840. #endif
  48841. #define DRMP3_PRIVATE DRMP3_DLL_PRIVATE
  48842. #else
  48843. #define DRMP3_API extern
  48844. #define DRMP3_PRIVATE static
  48845. #endif
  48846. #endif
  48847. typedef drmp3_int32 drmp3_result;
  48848. #define DRMP3_SUCCESS 0
  48849. #define DRMP3_ERROR -1
  48850. #define DRMP3_INVALID_ARGS -2
  48851. #define DRMP3_INVALID_OPERATION -3
  48852. #define DRMP3_OUT_OF_MEMORY -4
  48853. #define DRMP3_OUT_OF_RANGE -5
  48854. #define DRMP3_ACCESS_DENIED -6
  48855. #define DRMP3_DOES_NOT_EXIST -7
  48856. #define DRMP3_ALREADY_EXISTS -8
  48857. #define DRMP3_TOO_MANY_OPEN_FILES -9
  48858. #define DRMP3_INVALID_FILE -10
  48859. #define DRMP3_TOO_BIG -11
  48860. #define DRMP3_PATH_TOO_LONG -12
  48861. #define DRMP3_NAME_TOO_LONG -13
  48862. #define DRMP3_NOT_DIRECTORY -14
  48863. #define DRMP3_IS_DIRECTORY -15
  48864. #define DRMP3_DIRECTORY_NOT_EMPTY -16
  48865. #define DRMP3_END_OF_FILE -17
  48866. #define DRMP3_NO_SPACE -18
  48867. #define DRMP3_BUSY -19
  48868. #define DRMP3_IO_ERROR -20
  48869. #define DRMP3_INTERRUPT -21
  48870. #define DRMP3_UNAVAILABLE -22
  48871. #define DRMP3_ALREADY_IN_USE -23
  48872. #define DRMP3_BAD_ADDRESS -24
  48873. #define DRMP3_BAD_SEEK -25
  48874. #define DRMP3_BAD_PIPE -26
  48875. #define DRMP3_DEADLOCK -27
  48876. #define DRMP3_TOO_MANY_LINKS -28
  48877. #define DRMP3_NOT_IMPLEMENTED -29
  48878. #define DRMP3_NO_MESSAGE -30
  48879. #define DRMP3_BAD_MESSAGE -31
  48880. #define DRMP3_NO_DATA_AVAILABLE -32
  48881. #define DRMP3_INVALID_DATA -33
  48882. #define DRMP3_TIMEOUT -34
  48883. #define DRMP3_NO_NETWORK -35
  48884. #define DRMP3_NOT_UNIQUE -36
  48885. #define DRMP3_NOT_SOCKET -37
  48886. #define DRMP3_NO_ADDRESS -38
  48887. #define DRMP3_BAD_PROTOCOL -39
  48888. #define DRMP3_PROTOCOL_UNAVAILABLE -40
  48889. #define DRMP3_PROTOCOL_NOT_SUPPORTED -41
  48890. #define DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  48891. #define DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED -43
  48892. #define DRMP3_SOCKET_NOT_SUPPORTED -44
  48893. #define DRMP3_CONNECTION_RESET -45
  48894. #define DRMP3_ALREADY_CONNECTED -46
  48895. #define DRMP3_NOT_CONNECTED -47
  48896. #define DRMP3_CONNECTION_REFUSED -48
  48897. #define DRMP3_NO_HOST -49
  48898. #define DRMP3_IN_PROGRESS -50
  48899. #define DRMP3_CANCELLED -51
  48900. #define DRMP3_MEMORY_ALREADY_MAPPED -52
  48901. #define DRMP3_AT_END -53
  48902. #define DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME 1152
  48903. #define DRMP3_MAX_SAMPLES_PER_FRAME (DRMP3_MAX_PCM_FRAMES_PER_MP3_FRAME*2)
  48904. #ifdef _MSC_VER
  48905. #define DRMP3_INLINE __forceinline
  48906. #elif defined(__GNUC__)
  48907. #if defined(__STRICT_ANSI__)
  48908. #define DRMP3_GNUC_INLINE_HINT __inline__
  48909. #else
  48910. #define DRMP3_GNUC_INLINE_HINT inline
  48911. #endif
  48912. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  48913. #define DRMP3_INLINE DRMP3_GNUC_INLINE_HINT __attribute__((always_inline))
  48914. #else
  48915. #define DRMP3_INLINE DRMP3_GNUC_INLINE_HINT
  48916. #endif
  48917. #elif defined(__WATCOMC__)
  48918. #define DRMP3_INLINE __inline
  48919. #else
  48920. #define DRMP3_INLINE
  48921. #endif
  48922. DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision);
  48923. DRMP3_API const char* drmp3_version_string(void);
  48924. typedef struct
  48925. {
  48926. int frame_bytes, channels, hz, layer, bitrate_kbps;
  48927. } drmp3dec_frame_info;
  48928. typedef struct
  48929. {
  48930. float mdct_overlap[2][9*32], qmf_state[15*2*32];
  48931. int reserv, free_format_bytes;
  48932. drmp3_uint8 header[4], reserv_buf[511];
  48933. } drmp3dec;
  48934. DRMP3_API void drmp3dec_init(drmp3dec *dec);
  48935. DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info);
  48936. DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples);
  48937. typedef enum
  48938. {
  48939. drmp3_seek_origin_start,
  48940. drmp3_seek_origin_current
  48941. } drmp3_seek_origin;
  48942. typedef struct
  48943. {
  48944. drmp3_uint64 seekPosInBytes;
  48945. drmp3_uint64 pcmFrameIndex;
  48946. drmp3_uint16 mp3FramesToDiscard;
  48947. drmp3_uint16 pcmFramesToDiscard;
  48948. } drmp3_seek_point;
  48949. typedef size_t (* drmp3_read_proc)(void* pUserData, void* pBufferOut, size_t bytesToRead);
  48950. typedef drmp3_bool32 (* drmp3_seek_proc)(void* pUserData, int offset, drmp3_seek_origin origin);
  48951. typedef struct
  48952. {
  48953. void* pUserData;
  48954. void* (* onMalloc)(size_t sz, void* pUserData);
  48955. void* (* onRealloc)(void* p, size_t sz, void* pUserData);
  48956. void (* onFree)(void* p, void* pUserData);
  48957. } drmp3_allocation_callbacks;
  48958. typedef struct
  48959. {
  48960. drmp3_uint32 channels;
  48961. drmp3_uint32 sampleRate;
  48962. } drmp3_config;
  48963. typedef struct
  48964. {
  48965. drmp3dec decoder;
  48966. drmp3_uint32 channels;
  48967. drmp3_uint32 sampleRate;
  48968. drmp3_read_proc onRead;
  48969. drmp3_seek_proc onSeek;
  48970. void* pUserData;
  48971. drmp3_allocation_callbacks allocationCallbacks;
  48972. drmp3_uint32 mp3FrameChannels;
  48973. drmp3_uint32 mp3FrameSampleRate;
  48974. drmp3_uint32 pcmFramesConsumedInMP3Frame;
  48975. drmp3_uint32 pcmFramesRemainingInMP3Frame;
  48976. drmp3_uint8 pcmFrames[sizeof(float)*DRMP3_MAX_SAMPLES_PER_FRAME];
  48977. drmp3_uint64 currentPCMFrame;
  48978. drmp3_uint64 streamCursor;
  48979. drmp3_seek_point* pSeekPoints;
  48980. drmp3_uint32 seekPointCount;
  48981. size_t dataSize;
  48982. size_t dataCapacity;
  48983. size_t dataConsumed;
  48984. drmp3_uint8* pData;
  48985. drmp3_bool32 atEnd : 1;
  48986. struct
  48987. {
  48988. const drmp3_uint8* pData;
  48989. size_t dataSize;
  48990. size_t currentReadPos;
  48991. } memory;
  48992. } drmp3;
  48993. DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks);
  48994. DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks);
  48995. #ifndef DR_MP3_NO_STDIO
  48996. DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
  48997. DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks);
  48998. #endif
  48999. DRMP3_API void drmp3_uninit(drmp3* pMP3);
  49000. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut);
  49001. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut);
  49002. DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex);
  49003. DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3);
  49004. DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3);
  49005. DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount);
  49006. DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints);
  49007. DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints);
  49008. DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49009. DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49010. DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49011. DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49012. #ifndef DR_MP3_NO_STDIO
  49013. DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49014. DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49015. #endif
  49016. DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49017. DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks);
  49018. #ifdef __cplusplus
  49019. }
  49020. #endif
  49021. #endif
  49022. /* dr_mp3_h end */
  49023. #endif /* MA_NO_MP3 */
  49024. /**************************************************************************************************************************************************************
  49025. Decoding
  49026. **************************************************************************************************************************************************************/
  49027. #ifndef MA_NO_DECODING
  49028. static ma_result ma_decoder_read_bytes(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  49029. {
  49030. MA_ASSERT(pDecoder != NULL);
  49031. return pDecoder->onRead(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  49032. }
  49033. static ma_result ma_decoder_seek_bytes(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  49034. {
  49035. MA_ASSERT(pDecoder != NULL);
  49036. return pDecoder->onSeek(pDecoder, byteOffset, origin);
  49037. }
  49038. static ma_result ma_decoder_tell_bytes(ma_decoder* pDecoder, ma_int64* pCursor)
  49039. {
  49040. MA_ASSERT(pDecoder != NULL);
  49041. if (pDecoder->onTell == NULL) {
  49042. return MA_NOT_IMPLEMENTED;
  49043. }
  49044. return pDecoder->onTell(pDecoder, pCursor);
  49045. }
  49046. MA_API ma_decoding_backend_config ma_decoding_backend_config_init(ma_format preferredFormat, ma_uint32 seekPointCount)
  49047. {
  49048. ma_decoding_backend_config config;
  49049. MA_ZERO_OBJECT(&config);
  49050. config.preferredFormat = preferredFormat;
  49051. config.seekPointCount = seekPointCount;
  49052. return config;
  49053. }
  49054. MA_API ma_decoder_config ma_decoder_config_init(ma_format outputFormat, ma_uint32 outputChannels, ma_uint32 outputSampleRate)
  49055. {
  49056. ma_decoder_config config;
  49057. MA_ZERO_OBJECT(&config);
  49058. config.format = outputFormat;
  49059. config.channels = outputChannels;
  49060. config.sampleRate = outputSampleRate;
  49061. config.resampling = ma_resampler_config_init(ma_format_unknown, 0, 0, 0, ma_resample_algorithm_linear); /* Format/channels/rate doesn't matter here. */
  49062. config.encodingFormat = ma_encoding_format_unknown;
  49063. /* Note that we are intentionally leaving the channel map empty here which will cause the default channel map to be used. */
  49064. return config;
  49065. }
  49066. MA_API ma_decoder_config ma_decoder_config_init_default()
  49067. {
  49068. return ma_decoder_config_init(ma_format_unknown, 0, 0);
  49069. }
  49070. MA_API ma_decoder_config ma_decoder_config_init_copy(const ma_decoder_config* pConfig)
  49071. {
  49072. ma_decoder_config config;
  49073. if (pConfig != NULL) {
  49074. config = *pConfig;
  49075. } else {
  49076. MA_ZERO_OBJECT(&config);
  49077. }
  49078. return config;
  49079. }
  49080. static ma_result ma_decoder__init_data_converter(ma_decoder* pDecoder, const ma_decoder_config* pConfig)
  49081. {
  49082. ma_result result;
  49083. ma_data_converter_config converterConfig;
  49084. ma_format internalFormat;
  49085. ma_uint32 internalChannels;
  49086. ma_uint32 internalSampleRate;
  49087. ma_channel internalChannelMap[MA_MAX_CHANNELS];
  49088. MA_ASSERT(pDecoder != NULL);
  49089. MA_ASSERT(pConfig != NULL);
  49090. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, &internalSampleRate, internalChannelMap, ma_countof(internalChannelMap));
  49091. if (result != MA_SUCCESS) {
  49092. return result; /* Failed to retrieve the internal data format. */
  49093. }
  49094. /* Make sure we're not asking for too many channels. */
  49095. if (pConfig->channels > MA_MAX_CHANNELS) {
  49096. return MA_INVALID_ARGS;
  49097. }
  49098. /* The internal channels should have already been validated at a higher level, but we'll do it again explicitly here for safety. */
  49099. if (internalChannels > MA_MAX_CHANNELS) {
  49100. return MA_INVALID_ARGS;
  49101. }
  49102. /* Output format. */
  49103. if (pConfig->format == ma_format_unknown) {
  49104. pDecoder->outputFormat = internalFormat;
  49105. } else {
  49106. pDecoder->outputFormat = pConfig->format;
  49107. }
  49108. if (pConfig->channels == 0) {
  49109. pDecoder->outputChannels = internalChannels;
  49110. } else {
  49111. pDecoder->outputChannels = pConfig->channels;
  49112. }
  49113. if (pConfig->sampleRate == 0) {
  49114. pDecoder->outputSampleRate = internalSampleRate;
  49115. } else {
  49116. pDecoder->outputSampleRate = pConfig->sampleRate;
  49117. }
  49118. converterConfig = ma_data_converter_config_init(
  49119. internalFormat, pDecoder->outputFormat,
  49120. internalChannels, pDecoder->outputChannels,
  49121. internalSampleRate, pDecoder->outputSampleRate
  49122. );
  49123. converterConfig.pChannelMapIn = internalChannelMap;
  49124. converterConfig.pChannelMapOut = pConfig->pChannelMap;
  49125. converterConfig.channelMixMode = pConfig->channelMixMode;
  49126. converterConfig.ditherMode = pConfig->ditherMode;
  49127. converterConfig.allowDynamicSampleRate = MA_FALSE; /* Never allow dynamic sample rate conversion. Setting this to true will disable passthrough optimizations. */
  49128. converterConfig.resampling = pConfig->resampling;
  49129. result = ma_data_converter_init(&converterConfig, &pDecoder->allocationCallbacks, &pDecoder->converter);
  49130. if (result != MA_SUCCESS) {
  49131. return result;
  49132. }
  49133. /*
  49134. Now that we have the decoder we need to determine whether or not we need a heap-allocated cache. We'll
  49135. need this if the data converter does not support calculation of the required input frame count. To
  49136. determine support for this we'll just run a test.
  49137. */
  49138. {
  49139. ma_uint64 unused;
  49140. result = ma_data_converter_get_required_input_frame_count(&pDecoder->converter, 1, &unused);
  49141. if (result != MA_SUCCESS) {
  49142. /*
  49143. We were unable to calculate the required input frame count which means we'll need to use
  49144. a heap-allocated cache.
  49145. */
  49146. ma_uint64 inputCacheCapSizeInBytes;
  49147. pDecoder->inputCacheCap = MA_DATA_CONVERTER_STACK_BUFFER_SIZE / ma_get_bytes_per_frame(internalFormat, internalChannels);
  49148. /* Not strictly necessary, but keeping here for safety in case we change the default value of pDecoder->inputCacheCap. */
  49149. inputCacheCapSizeInBytes = pDecoder->inputCacheCap * ma_get_bytes_per_frame(internalFormat, internalChannels);
  49150. if (inputCacheCapSizeInBytes > MA_SIZE_MAX) {
  49151. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  49152. return MA_OUT_OF_MEMORY;
  49153. }
  49154. pDecoder->pInputCache = ma_malloc((size_t)inputCacheCapSizeInBytes, &pDecoder->allocationCallbacks); /* Safe cast to size_t. */
  49155. if (pDecoder->pInputCache == NULL) {
  49156. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  49157. return MA_OUT_OF_MEMORY;
  49158. }
  49159. }
  49160. }
  49161. return MA_SUCCESS;
  49162. }
  49163. static ma_result ma_decoder_internal_on_read__custom(void* pUserData, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  49164. {
  49165. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  49166. MA_ASSERT(pDecoder != NULL);
  49167. return ma_decoder_read_bytes(pDecoder, pBufferOut, bytesToRead, pBytesRead);
  49168. }
  49169. static ma_result ma_decoder_internal_on_seek__custom(void* pUserData, ma_int64 offset, ma_seek_origin origin)
  49170. {
  49171. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  49172. MA_ASSERT(pDecoder != NULL);
  49173. return ma_decoder_seek_bytes(pDecoder, offset, origin);
  49174. }
  49175. static ma_result ma_decoder_internal_on_tell__custom(void* pUserData, ma_int64* pCursor)
  49176. {
  49177. ma_decoder* pDecoder = (ma_decoder*)pUserData;
  49178. MA_ASSERT(pDecoder != NULL);
  49179. return ma_decoder_tell_bytes(pDecoder, pCursor);
  49180. }
  49181. static ma_result ma_decoder_init_from_vtable(const ma_decoding_backend_vtable* pVTable, void* pVTableUserData, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  49182. {
  49183. ma_result result;
  49184. ma_decoding_backend_config backendConfig;
  49185. ma_data_source* pBackend;
  49186. MA_ASSERT(pVTable != NULL);
  49187. MA_ASSERT(pConfig != NULL);
  49188. MA_ASSERT(pDecoder != NULL);
  49189. if (pVTable->onInit == NULL) {
  49190. return MA_NOT_IMPLEMENTED;
  49191. }
  49192. backendConfig = ma_decoding_backend_config_init(pConfig->format, pConfig->seekPointCount);
  49193. 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);
  49194. if (result != MA_SUCCESS) {
  49195. return result; /* Failed to initialize the backend from this vtable. */
  49196. }
  49197. /* Getting here means we were able to initialize the backend so we can now initialize the decoder. */
  49198. pDecoder->pBackend = pBackend;
  49199. pDecoder->pBackendVTable = pVTable;
  49200. pDecoder->pBackendUserData = pConfig->pCustomBackendUserData;
  49201. return MA_SUCCESS;
  49202. }
  49203. static ma_result ma_decoder_init_custom__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  49204. {
  49205. ma_result result = MA_NO_BACKEND;
  49206. size_t ivtable;
  49207. MA_ASSERT(pConfig != NULL);
  49208. MA_ASSERT(pDecoder != NULL);
  49209. if (pConfig->ppCustomBackendVTables == NULL) {
  49210. return MA_NO_BACKEND;
  49211. }
  49212. /* The order each backend is listed is what defines the priority. */
  49213. for (ivtable = 0; ivtable < pConfig->customBackendCount; ivtable += 1) {
  49214. const ma_decoding_backend_vtable* pVTable = pConfig->ppCustomBackendVTables[ivtable];
  49215. if (pVTable != NULL && pVTable->onInit != NULL) {
  49216. result = ma_decoder_init_from_vtable(pVTable, pConfig->pCustomBackendUserData, pConfig, pDecoder);
  49217. if (result == MA_SUCCESS) {
  49218. return MA_SUCCESS;
  49219. } else {
  49220. /* 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. */
  49221. result = ma_decoder_seek_bytes(pDecoder, 0, ma_seek_origin_start);
  49222. if (result != MA_SUCCESS) {
  49223. return result; /* Failed to seek back to the start. */
  49224. }
  49225. }
  49226. } else {
  49227. /* No vtable. */
  49228. }
  49229. }
  49230. /* Getting here means we couldn't find a backend. */
  49231. return MA_NO_BACKEND;
  49232. }
  49233. /* WAV */
  49234. #ifdef dr_wav_h
  49235. #define MA_HAS_WAV
  49236. typedef struct
  49237. {
  49238. ma_data_source_base ds;
  49239. ma_read_proc onRead;
  49240. ma_seek_proc onSeek;
  49241. ma_tell_proc onTell;
  49242. void* pReadSeekTellUserData;
  49243. ma_format format; /* Can be f32, s16 or s32. */
  49244. #if !defined(MA_NO_WAV)
  49245. drwav dr;
  49246. #endif
  49247. } ma_wav;
  49248. 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);
  49249. 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);
  49250. 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);
  49251. 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);
  49252. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks);
  49253. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  49254. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex);
  49255. 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);
  49256. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor);
  49257. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength);
  49258. static ma_result ma_wav_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  49259. {
  49260. return ma_wav_read_pcm_frames((ma_wav*)pDataSource, pFramesOut, frameCount, pFramesRead);
  49261. }
  49262. static ma_result ma_wav_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  49263. {
  49264. return ma_wav_seek_to_pcm_frame((ma_wav*)pDataSource, frameIndex);
  49265. }
  49266. 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)
  49267. {
  49268. return ma_wav_get_data_format((ma_wav*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  49269. }
  49270. static ma_result ma_wav_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  49271. {
  49272. return ma_wav_get_cursor_in_pcm_frames((ma_wav*)pDataSource, pCursor);
  49273. }
  49274. static ma_result ma_wav_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  49275. {
  49276. return ma_wav_get_length_in_pcm_frames((ma_wav*)pDataSource, pLength);
  49277. }
  49278. static ma_data_source_vtable g_ma_wav_ds_vtable =
  49279. {
  49280. ma_wav_ds_read,
  49281. ma_wav_ds_seek,
  49282. ma_wav_ds_get_data_format,
  49283. ma_wav_ds_get_cursor,
  49284. ma_wav_ds_get_length,
  49285. NULL, /* onSetLooping */
  49286. 0
  49287. };
  49288. #if !defined(MA_NO_WAV)
  49289. static drwav_allocation_callbacks drwav_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  49290. {
  49291. drwav_allocation_callbacks callbacks;
  49292. if (pAllocationCallbacks != NULL) {
  49293. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  49294. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  49295. callbacks.onFree = pAllocationCallbacks->onFree;
  49296. callbacks.pUserData = pAllocationCallbacks->pUserData;
  49297. } else {
  49298. callbacks.onMalloc = ma__malloc_default;
  49299. callbacks.onRealloc = ma__realloc_default;
  49300. callbacks.onFree = ma__free_default;
  49301. callbacks.pUserData = NULL;
  49302. }
  49303. return callbacks;
  49304. }
  49305. static size_t ma_wav_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  49306. {
  49307. ma_wav* pWav = (ma_wav*)pUserData;
  49308. ma_result result;
  49309. size_t bytesRead;
  49310. MA_ASSERT(pWav != NULL);
  49311. result = pWav->onRead(pWav->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  49312. (void)result;
  49313. return bytesRead;
  49314. }
  49315. static drwav_bool32 ma_wav_dr_callback__seek(void* pUserData, int offset, drwav_seek_origin origin)
  49316. {
  49317. ma_wav* pWav = (ma_wav*)pUserData;
  49318. ma_result result;
  49319. ma_seek_origin maSeekOrigin;
  49320. MA_ASSERT(pWav != NULL);
  49321. maSeekOrigin = ma_seek_origin_start;
  49322. if (origin == drwav_seek_origin_current) {
  49323. maSeekOrigin = ma_seek_origin_current;
  49324. }
  49325. result = pWav->onSeek(pWav->pReadSeekTellUserData, offset, maSeekOrigin);
  49326. if (result != MA_SUCCESS) {
  49327. return MA_FALSE;
  49328. }
  49329. return MA_TRUE;
  49330. }
  49331. #endif
  49332. static ma_result ma_wav_init_internal(const ma_decoding_backend_config* pConfig, ma_wav* pWav)
  49333. {
  49334. ma_result result;
  49335. ma_data_source_config dataSourceConfig;
  49336. if (pWav == NULL) {
  49337. return MA_INVALID_ARGS;
  49338. }
  49339. MA_ZERO_OBJECT(pWav);
  49340. pWav->format = ma_format_unknown; /* Use closest match to source file by default. */
  49341. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  49342. pWav->format = pConfig->preferredFormat;
  49343. } else {
  49344. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  49345. }
  49346. dataSourceConfig = ma_data_source_config_init();
  49347. dataSourceConfig.vtable = &g_ma_wav_ds_vtable;
  49348. result = ma_data_source_init(&dataSourceConfig, &pWav->ds);
  49349. if (result != MA_SUCCESS) {
  49350. return result; /* Failed to initialize the base data source. */
  49351. }
  49352. return MA_SUCCESS;
  49353. }
  49354. 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)
  49355. {
  49356. ma_result result;
  49357. result = ma_wav_init_internal(pConfig, pWav);
  49358. if (result != MA_SUCCESS) {
  49359. return result;
  49360. }
  49361. if (onRead == NULL || onSeek == NULL) {
  49362. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  49363. }
  49364. pWav->onRead = onRead;
  49365. pWav->onSeek = onSeek;
  49366. pWav->onTell = onTell;
  49367. pWav->pReadSeekTellUserData = pReadSeekTellUserData;
  49368. #if !defined(MA_NO_WAV)
  49369. {
  49370. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49371. drwav_bool32 wavResult;
  49372. wavResult = drwav_init(&pWav->dr, ma_wav_dr_callback__read, ma_wav_dr_callback__seek, pWav, &wavAllocationCallbacks);
  49373. if (wavResult != MA_TRUE) {
  49374. return MA_INVALID_FILE;
  49375. }
  49376. /*
  49377. If an explicit format was not specified, try picking the closest match based on the internal
  49378. format. The format needs to be supported by miniaudio.
  49379. */
  49380. if (pWav->format == ma_format_unknown) {
  49381. switch (pWav->dr.translatedFormatTag)
  49382. {
  49383. case DR_WAVE_FORMAT_PCM:
  49384. {
  49385. if (pWav->dr.bitsPerSample == 8) {
  49386. pWav->format = ma_format_u8;
  49387. } else if (pWav->dr.bitsPerSample == 16) {
  49388. pWav->format = ma_format_s16;
  49389. } else if (pWav->dr.bitsPerSample == 24) {
  49390. pWav->format = ma_format_s24;
  49391. } else if (pWav->dr.bitsPerSample == 32) {
  49392. pWav->format = ma_format_s32;
  49393. }
  49394. } break;
  49395. case DR_WAVE_FORMAT_IEEE_FLOAT:
  49396. {
  49397. if (pWav->dr.bitsPerSample == 32) {
  49398. pWav->format = ma_format_f32;
  49399. }
  49400. } break;
  49401. default: break;
  49402. }
  49403. /* Fall back to f32 if we couldn't find anything. */
  49404. if (pWav->format == ma_format_unknown) {
  49405. pWav->format = ma_format_f32;
  49406. }
  49407. }
  49408. return MA_SUCCESS;
  49409. }
  49410. #else
  49411. {
  49412. /* wav is disabled. */
  49413. (void)pAllocationCallbacks;
  49414. return MA_NOT_IMPLEMENTED;
  49415. }
  49416. #endif
  49417. }
  49418. 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)
  49419. {
  49420. ma_result result;
  49421. result = ma_wav_init_internal(pConfig, pWav);
  49422. if (result != MA_SUCCESS) {
  49423. return result;
  49424. }
  49425. #if !defined(MA_NO_WAV)
  49426. {
  49427. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49428. drwav_bool32 wavResult;
  49429. wavResult = drwav_init_file(&pWav->dr, pFilePath, &wavAllocationCallbacks);
  49430. if (wavResult != MA_TRUE) {
  49431. return MA_INVALID_FILE;
  49432. }
  49433. return MA_SUCCESS;
  49434. }
  49435. #else
  49436. {
  49437. /* wav is disabled. */
  49438. (void)pFilePath;
  49439. (void)pAllocationCallbacks;
  49440. return MA_NOT_IMPLEMENTED;
  49441. }
  49442. #endif
  49443. }
  49444. 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)
  49445. {
  49446. ma_result result;
  49447. result = ma_wav_init_internal(pConfig, pWav);
  49448. if (result != MA_SUCCESS) {
  49449. return result;
  49450. }
  49451. #if !defined(MA_NO_WAV)
  49452. {
  49453. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49454. drwav_bool32 wavResult;
  49455. wavResult = drwav_init_file_w(&pWav->dr, pFilePath, &wavAllocationCallbacks);
  49456. if (wavResult != MA_TRUE) {
  49457. return MA_INVALID_FILE;
  49458. }
  49459. return MA_SUCCESS;
  49460. }
  49461. #else
  49462. {
  49463. /* wav is disabled. */
  49464. (void)pFilePath;
  49465. (void)pAllocationCallbacks;
  49466. return MA_NOT_IMPLEMENTED;
  49467. }
  49468. #endif
  49469. }
  49470. 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)
  49471. {
  49472. ma_result result;
  49473. result = ma_wav_init_internal(pConfig, pWav);
  49474. if (result != MA_SUCCESS) {
  49475. return result;
  49476. }
  49477. #if !defined(MA_NO_WAV)
  49478. {
  49479. drwav_allocation_callbacks wavAllocationCallbacks = drwav_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49480. drwav_bool32 wavResult;
  49481. wavResult = drwav_init_memory(&pWav->dr, pData, dataSize, &wavAllocationCallbacks);
  49482. if (wavResult != MA_TRUE) {
  49483. return MA_INVALID_FILE;
  49484. }
  49485. return MA_SUCCESS;
  49486. }
  49487. #else
  49488. {
  49489. /* wav is disabled. */
  49490. (void)pData;
  49491. (void)dataSize;
  49492. (void)pAllocationCallbacks;
  49493. return MA_NOT_IMPLEMENTED;
  49494. }
  49495. #endif
  49496. }
  49497. MA_API void ma_wav_uninit(ma_wav* pWav, const ma_allocation_callbacks* pAllocationCallbacks)
  49498. {
  49499. if (pWav == NULL) {
  49500. return;
  49501. }
  49502. (void)pAllocationCallbacks;
  49503. #if !defined(MA_NO_WAV)
  49504. {
  49505. drwav_uninit(&pWav->dr);
  49506. }
  49507. #else
  49508. {
  49509. /* wav is disabled. Should never hit this since initialization would have failed. */
  49510. MA_ASSERT(MA_FALSE);
  49511. }
  49512. #endif
  49513. ma_data_source_uninit(&pWav->ds);
  49514. }
  49515. MA_API ma_result ma_wav_read_pcm_frames(ma_wav* pWav, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  49516. {
  49517. if (pFramesRead != NULL) {
  49518. *pFramesRead = 0;
  49519. }
  49520. if (frameCount == 0) {
  49521. return MA_INVALID_ARGS;
  49522. }
  49523. if (pWav == NULL) {
  49524. return MA_INVALID_ARGS;
  49525. }
  49526. #if !defined(MA_NO_WAV)
  49527. {
  49528. /* We always use floating point format. */
  49529. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  49530. ma_uint64 totalFramesRead = 0;
  49531. ma_format format;
  49532. ma_wav_get_data_format(pWav, &format, NULL, NULL, NULL, 0);
  49533. switch (format)
  49534. {
  49535. case ma_format_f32:
  49536. {
  49537. totalFramesRead = drwav_read_pcm_frames_f32(&pWav->dr, frameCount, (float*)pFramesOut);
  49538. } break;
  49539. case ma_format_s16:
  49540. {
  49541. totalFramesRead = drwav_read_pcm_frames_s16(&pWav->dr, frameCount, (drwav_int16*)pFramesOut);
  49542. } break;
  49543. case ma_format_s32:
  49544. {
  49545. totalFramesRead = drwav_read_pcm_frames_s32(&pWav->dr, frameCount, (drwav_int32*)pFramesOut);
  49546. } break;
  49547. /* Fallback to a raw read. */
  49548. case ma_format_unknown: return MA_INVALID_OPERATION; /* <-- this should never be hit because initialization would just fall back to a supported format. */
  49549. default:
  49550. {
  49551. totalFramesRead = drwav_read_pcm_frames(&pWav->dr, frameCount, pFramesOut);
  49552. } break;
  49553. }
  49554. /* In the future we'll update dr_wav to return MA_AT_END for us. */
  49555. if (totalFramesRead == 0) {
  49556. result = MA_AT_END;
  49557. }
  49558. if (pFramesRead != NULL) {
  49559. *pFramesRead = totalFramesRead;
  49560. }
  49561. if (result == MA_SUCCESS && totalFramesRead == 0) {
  49562. result = MA_AT_END;
  49563. }
  49564. return result;
  49565. }
  49566. #else
  49567. {
  49568. /* wav is disabled. Should never hit this since initialization would have failed. */
  49569. MA_ASSERT(MA_FALSE);
  49570. (void)pFramesOut;
  49571. (void)frameCount;
  49572. (void)pFramesRead;
  49573. return MA_NOT_IMPLEMENTED;
  49574. }
  49575. #endif
  49576. }
  49577. MA_API ma_result ma_wav_seek_to_pcm_frame(ma_wav* pWav, ma_uint64 frameIndex)
  49578. {
  49579. if (pWav == NULL) {
  49580. return MA_INVALID_ARGS;
  49581. }
  49582. #if !defined(MA_NO_WAV)
  49583. {
  49584. drwav_bool32 wavResult;
  49585. wavResult = drwav_seek_to_pcm_frame(&pWav->dr, frameIndex);
  49586. if (wavResult != DRWAV_TRUE) {
  49587. return MA_ERROR;
  49588. }
  49589. return MA_SUCCESS;
  49590. }
  49591. #else
  49592. {
  49593. /* wav is disabled. Should never hit this since initialization would have failed. */
  49594. MA_ASSERT(MA_FALSE);
  49595. (void)frameIndex;
  49596. return MA_NOT_IMPLEMENTED;
  49597. }
  49598. #endif
  49599. }
  49600. 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)
  49601. {
  49602. /* Defaults for safety. */
  49603. if (pFormat != NULL) {
  49604. *pFormat = ma_format_unknown;
  49605. }
  49606. if (pChannels != NULL) {
  49607. *pChannels = 0;
  49608. }
  49609. if (pSampleRate != NULL) {
  49610. *pSampleRate = 0;
  49611. }
  49612. if (pChannelMap != NULL) {
  49613. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  49614. }
  49615. if (pWav == NULL) {
  49616. return MA_INVALID_OPERATION;
  49617. }
  49618. if (pFormat != NULL) {
  49619. *pFormat = pWav->format;
  49620. }
  49621. #if !defined(MA_NO_WAV)
  49622. {
  49623. if (pChannels != NULL) {
  49624. *pChannels = pWav->dr.channels;
  49625. }
  49626. if (pSampleRate != NULL) {
  49627. *pSampleRate = pWav->dr.sampleRate;
  49628. }
  49629. if (pChannelMap != NULL) {
  49630. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pWav->dr.channels);
  49631. }
  49632. return MA_SUCCESS;
  49633. }
  49634. #else
  49635. {
  49636. /* wav is disabled. Should never hit this since initialization would have failed. */
  49637. MA_ASSERT(MA_FALSE);
  49638. return MA_NOT_IMPLEMENTED;
  49639. }
  49640. #endif
  49641. }
  49642. MA_API ma_result ma_wav_get_cursor_in_pcm_frames(ma_wav* pWav, ma_uint64* pCursor)
  49643. {
  49644. if (pCursor == NULL) {
  49645. return MA_INVALID_ARGS;
  49646. }
  49647. *pCursor = 0; /* Safety. */
  49648. if (pWav == NULL) {
  49649. return MA_INVALID_ARGS;
  49650. }
  49651. #if !defined(MA_NO_WAV)
  49652. {
  49653. drwav_result wavResult = drwav_get_cursor_in_pcm_frames(&pWav->dr, pCursor);
  49654. if (wavResult != DRWAV_SUCCESS) {
  49655. return (ma_result)wavResult; /* dr_wav result codes map to miniaudio's. */
  49656. }
  49657. return MA_SUCCESS;
  49658. }
  49659. #else
  49660. {
  49661. /* wav is disabled. Should never hit this since initialization would have failed. */
  49662. MA_ASSERT(MA_FALSE);
  49663. return MA_NOT_IMPLEMENTED;
  49664. }
  49665. #endif
  49666. }
  49667. MA_API ma_result ma_wav_get_length_in_pcm_frames(ma_wav* pWav, ma_uint64* pLength)
  49668. {
  49669. if (pLength == NULL) {
  49670. return MA_INVALID_ARGS;
  49671. }
  49672. *pLength = 0; /* Safety. */
  49673. if (pWav == NULL) {
  49674. return MA_INVALID_ARGS;
  49675. }
  49676. #if !defined(MA_NO_WAV)
  49677. {
  49678. drwav_result wavResult = drwav_get_length_in_pcm_frames(&pWav->dr, pLength);
  49679. if (wavResult != DRWAV_SUCCESS) {
  49680. return (ma_result)wavResult; /* dr_wav result codes map to miniaudio's. */
  49681. }
  49682. return MA_SUCCESS;
  49683. }
  49684. #else
  49685. {
  49686. /* wav is disabled. Should never hit this since initialization would have failed. */
  49687. MA_ASSERT(MA_FALSE);
  49688. return MA_NOT_IMPLEMENTED;
  49689. }
  49690. #endif
  49691. }
  49692. 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)
  49693. {
  49694. ma_result result;
  49695. ma_wav* pWav;
  49696. (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. */
  49697. /* For now we're just allocating the decoder backend on the heap. */
  49698. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  49699. if (pWav == NULL) {
  49700. return MA_OUT_OF_MEMORY;
  49701. }
  49702. result = ma_wav_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pWav);
  49703. if (result != MA_SUCCESS) {
  49704. ma_free(pWav, pAllocationCallbacks);
  49705. return result;
  49706. }
  49707. *ppBackend = pWav;
  49708. return MA_SUCCESS;
  49709. }
  49710. 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)
  49711. {
  49712. ma_result result;
  49713. ma_wav* pWav;
  49714. (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. */
  49715. /* For now we're just allocating the decoder backend on the heap. */
  49716. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  49717. if (pWav == NULL) {
  49718. return MA_OUT_OF_MEMORY;
  49719. }
  49720. result = ma_wav_init_file(pFilePath, pConfig, pAllocationCallbacks, pWav);
  49721. if (result != MA_SUCCESS) {
  49722. ma_free(pWav, pAllocationCallbacks);
  49723. return result;
  49724. }
  49725. *ppBackend = pWav;
  49726. return MA_SUCCESS;
  49727. }
  49728. 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)
  49729. {
  49730. ma_result result;
  49731. ma_wav* pWav;
  49732. (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. */
  49733. /* For now we're just allocating the decoder backend on the heap. */
  49734. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  49735. if (pWav == NULL) {
  49736. return MA_OUT_OF_MEMORY;
  49737. }
  49738. result = ma_wav_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pWav);
  49739. if (result != MA_SUCCESS) {
  49740. ma_free(pWav, pAllocationCallbacks);
  49741. return result;
  49742. }
  49743. *ppBackend = pWav;
  49744. return MA_SUCCESS;
  49745. }
  49746. 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)
  49747. {
  49748. ma_result result;
  49749. ma_wav* pWav;
  49750. (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. */
  49751. /* For now we're just allocating the decoder backend on the heap. */
  49752. pWav = (ma_wav*)ma_malloc(sizeof(*pWav), pAllocationCallbacks);
  49753. if (pWav == NULL) {
  49754. return MA_OUT_OF_MEMORY;
  49755. }
  49756. result = ma_wav_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pWav);
  49757. if (result != MA_SUCCESS) {
  49758. ma_free(pWav, pAllocationCallbacks);
  49759. return result;
  49760. }
  49761. *ppBackend = pWav;
  49762. return MA_SUCCESS;
  49763. }
  49764. static void ma_decoding_backend_uninit__wav(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  49765. {
  49766. ma_wav* pWav = (ma_wav*)pBackend;
  49767. (void)pUserData;
  49768. ma_wav_uninit(pWav, pAllocationCallbacks);
  49769. ma_free(pWav, pAllocationCallbacks);
  49770. }
  49771. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_wav =
  49772. {
  49773. ma_decoding_backend_init__wav,
  49774. ma_decoding_backend_init_file__wav,
  49775. ma_decoding_backend_init_file_w__wav,
  49776. ma_decoding_backend_init_memory__wav,
  49777. ma_decoding_backend_uninit__wav
  49778. };
  49779. static ma_result ma_decoder_init_wav__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  49780. {
  49781. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_wav, NULL, pConfig, pDecoder);
  49782. }
  49783. #endif /* dr_wav_h */
  49784. /* FLAC */
  49785. #ifdef dr_flac_h
  49786. #define MA_HAS_FLAC
  49787. typedef struct
  49788. {
  49789. ma_data_source_base ds;
  49790. ma_read_proc onRead;
  49791. ma_seek_proc onSeek;
  49792. ma_tell_proc onTell;
  49793. void* pReadSeekTellUserData;
  49794. ma_format format; /* Can be f32, s16 or s32. */
  49795. #if !defined(MA_NO_FLAC)
  49796. drflac* dr;
  49797. #endif
  49798. } ma_flac;
  49799. 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);
  49800. 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);
  49801. 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);
  49802. 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);
  49803. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks);
  49804. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  49805. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex);
  49806. 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);
  49807. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor);
  49808. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength);
  49809. static ma_result ma_flac_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  49810. {
  49811. return ma_flac_read_pcm_frames((ma_flac*)pDataSource, pFramesOut, frameCount, pFramesRead);
  49812. }
  49813. static ma_result ma_flac_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  49814. {
  49815. return ma_flac_seek_to_pcm_frame((ma_flac*)pDataSource, frameIndex);
  49816. }
  49817. 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)
  49818. {
  49819. return ma_flac_get_data_format((ma_flac*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  49820. }
  49821. static ma_result ma_flac_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  49822. {
  49823. return ma_flac_get_cursor_in_pcm_frames((ma_flac*)pDataSource, pCursor);
  49824. }
  49825. static ma_result ma_flac_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  49826. {
  49827. return ma_flac_get_length_in_pcm_frames((ma_flac*)pDataSource, pLength);
  49828. }
  49829. static ma_data_source_vtable g_ma_flac_ds_vtable =
  49830. {
  49831. ma_flac_ds_read,
  49832. ma_flac_ds_seek,
  49833. ma_flac_ds_get_data_format,
  49834. ma_flac_ds_get_cursor,
  49835. ma_flac_ds_get_length,
  49836. NULL, /* onSetLooping */
  49837. 0
  49838. };
  49839. #if !defined(MA_NO_FLAC)
  49840. static drflac_allocation_callbacks drflac_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  49841. {
  49842. drflac_allocation_callbacks callbacks;
  49843. if (pAllocationCallbacks != NULL) {
  49844. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  49845. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  49846. callbacks.onFree = pAllocationCallbacks->onFree;
  49847. callbacks.pUserData = pAllocationCallbacks->pUserData;
  49848. } else {
  49849. callbacks.onMalloc = ma__malloc_default;
  49850. callbacks.onRealloc = ma__realloc_default;
  49851. callbacks.onFree = ma__free_default;
  49852. callbacks.pUserData = NULL;
  49853. }
  49854. return callbacks;
  49855. }
  49856. static size_t ma_flac_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  49857. {
  49858. ma_flac* pFlac = (ma_flac*)pUserData;
  49859. ma_result result;
  49860. size_t bytesRead;
  49861. MA_ASSERT(pFlac != NULL);
  49862. result = pFlac->onRead(pFlac->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  49863. (void)result;
  49864. return bytesRead;
  49865. }
  49866. static drflac_bool32 ma_flac_dr_callback__seek(void* pUserData, int offset, drflac_seek_origin origin)
  49867. {
  49868. ma_flac* pFlac = (ma_flac*)pUserData;
  49869. ma_result result;
  49870. ma_seek_origin maSeekOrigin;
  49871. MA_ASSERT(pFlac != NULL);
  49872. maSeekOrigin = ma_seek_origin_start;
  49873. if (origin == drflac_seek_origin_current) {
  49874. maSeekOrigin = ma_seek_origin_current;
  49875. }
  49876. result = pFlac->onSeek(pFlac->pReadSeekTellUserData, offset, maSeekOrigin);
  49877. if (result != MA_SUCCESS) {
  49878. return MA_FALSE;
  49879. }
  49880. return MA_TRUE;
  49881. }
  49882. #endif
  49883. static ma_result ma_flac_init_internal(const ma_decoding_backend_config* pConfig, ma_flac* pFlac)
  49884. {
  49885. ma_result result;
  49886. ma_data_source_config dataSourceConfig;
  49887. if (pFlac == NULL) {
  49888. return MA_INVALID_ARGS;
  49889. }
  49890. MA_ZERO_OBJECT(pFlac);
  49891. pFlac->format = ma_format_f32; /* f32 by default. */
  49892. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16 || pConfig->preferredFormat == ma_format_s32)) {
  49893. pFlac->format = pConfig->preferredFormat;
  49894. } else {
  49895. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  49896. }
  49897. dataSourceConfig = ma_data_source_config_init();
  49898. dataSourceConfig.vtable = &g_ma_flac_ds_vtable;
  49899. result = ma_data_source_init(&dataSourceConfig, &pFlac->ds);
  49900. if (result != MA_SUCCESS) {
  49901. return result; /* Failed to initialize the base data source. */
  49902. }
  49903. return MA_SUCCESS;
  49904. }
  49905. 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)
  49906. {
  49907. ma_result result;
  49908. result = ma_flac_init_internal(pConfig, pFlac);
  49909. if (result != MA_SUCCESS) {
  49910. return result;
  49911. }
  49912. if (onRead == NULL || onSeek == NULL) {
  49913. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  49914. }
  49915. pFlac->onRead = onRead;
  49916. pFlac->onSeek = onSeek;
  49917. pFlac->onTell = onTell;
  49918. pFlac->pReadSeekTellUserData = pReadSeekTellUserData;
  49919. #if !defined(MA_NO_FLAC)
  49920. {
  49921. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49922. pFlac->dr = drflac_open(ma_flac_dr_callback__read, ma_flac_dr_callback__seek, pFlac, &flacAllocationCallbacks);
  49923. if (pFlac->dr == NULL) {
  49924. return MA_INVALID_FILE;
  49925. }
  49926. return MA_SUCCESS;
  49927. }
  49928. #else
  49929. {
  49930. /* flac is disabled. */
  49931. (void)pAllocationCallbacks;
  49932. return MA_NOT_IMPLEMENTED;
  49933. }
  49934. #endif
  49935. }
  49936. 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)
  49937. {
  49938. ma_result result;
  49939. result = ma_flac_init_internal(pConfig, pFlac);
  49940. if (result != MA_SUCCESS) {
  49941. return result;
  49942. }
  49943. #if !defined(MA_NO_FLAC)
  49944. {
  49945. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49946. pFlac->dr = drflac_open_file(pFilePath, &flacAllocationCallbacks);
  49947. if (pFlac->dr == NULL) {
  49948. return MA_INVALID_FILE;
  49949. }
  49950. return MA_SUCCESS;
  49951. }
  49952. #else
  49953. {
  49954. /* flac is disabled. */
  49955. (void)pFilePath;
  49956. (void)pAllocationCallbacks;
  49957. return MA_NOT_IMPLEMENTED;
  49958. }
  49959. #endif
  49960. }
  49961. 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)
  49962. {
  49963. ma_result result;
  49964. result = ma_flac_init_internal(pConfig, pFlac);
  49965. if (result != MA_SUCCESS) {
  49966. return result;
  49967. }
  49968. #if !defined(MA_NO_FLAC)
  49969. {
  49970. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49971. pFlac->dr = drflac_open_file_w(pFilePath, &flacAllocationCallbacks);
  49972. if (pFlac->dr == NULL) {
  49973. return MA_INVALID_FILE;
  49974. }
  49975. return MA_SUCCESS;
  49976. }
  49977. #else
  49978. {
  49979. /* flac is disabled. */
  49980. (void)pFilePath;
  49981. (void)pAllocationCallbacks;
  49982. return MA_NOT_IMPLEMENTED;
  49983. }
  49984. #endif
  49985. }
  49986. 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)
  49987. {
  49988. ma_result result;
  49989. result = ma_flac_init_internal(pConfig, pFlac);
  49990. if (result != MA_SUCCESS) {
  49991. return result;
  49992. }
  49993. #if !defined(MA_NO_FLAC)
  49994. {
  49995. drflac_allocation_callbacks flacAllocationCallbacks = drflac_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  49996. pFlac->dr = drflac_open_memory(pData, dataSize, &flacAllocationCallbacks);
  49997. if (pFlac->dr == NULL) {
  49998. return MA_INVALID_FILE;
  49999. }
  50000. return MA_SUCCESS;
  50001. }
  50002. #else
  50003. {
  50004. /* flac is disabled. */
  50005. (void)pData;
  50006. (void)dataSize;
  50007. (void)pAllocationCallbacks;
  50008. return MA_NOT_IMPLEMENTED;
  50009. }
  50010. #endif
  50011. }
  50012. MA_API void ma_flac_uninit(ma_flac* pFlac, const ma_allocation_callbacks* pAllocationCallbacks)
  50013. {
  50014. if (pFlac == NULL) {
  50015. return;
  50016. }
  50017. (void)pAllocationCallbacks;
  50018. #if !defined(MA_NO_FLAC)
  50019. {
  50020. drflac_close(pFlac->dr);
  50021. }
  50022. #else
  50023. {
  50024. /* flac is disabled. Should never hit this since initialization would have failed. */
  50025. MA_ASSERT(MA_FALSE);
  50026. }
  50027. #endif
  50028. ma_data_source_uninit(&pFlac->ds);
  50029. }
  50030. MA_API ma_result ma_flac_read_pcm_frames(ma_flac* pFlac, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50031. {
  50032. if (pFramesRead != NULL) {
  50033. *pFramesRead = 0;
  50034. }
  50035. if (frameCount == 0) {
  50036. return MA_INVALID_ARGS;
  50037. }
  50038. if (pFlac == NULL) {
  50039. return MA_INVALID_ARGS;
  50040. }
  50041. #if !defined(MA_NO_FLAC)
  50042. {
  50043. /* We always use floating point format. */
  50044. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  50045. ma_uint64 totalFramesRead = 0;
  50046. ma_format format;
  50047. ma_flac_get_data_format(pFlac, &format, NULL, NULL, NULL, 0);
  50048. switch (format)
  50049. {
  50050. case ma_format_f32:
  50051. {
  50052. totalFramesRead = drflac_read_pcm_frames_f32(pFlac->dr, frameCount, (float*)pFramesOut);
  50053. } break;
  50054. case ma_format_s16:
  50055. {
  50056. totalFramesRead = drflac_read_pcm_frames_s16(pFlac->dr, frameCount, (drflac_int16*)pFramesOut);
  50057. } break;
  50058. case ma_format_s32:
  50059. {
  50060. totalFramesRead = drflac_read_pcm_frames_s32(pFlac->dr, frameCount, (drflac_int32*)pFramesOut);
  50061. } break;
  50062. case ma_format_u8:
  50063. case ma_format_s24:
  50064. case ma_format_unknown:
  50065. default:
  50066. {
  50067. return MA_INVALID_OPERATION;
  50068. };
  50069. }
  50070. /* In the future we'll update dr_flac to return MA_AT_END for us. */
  50071. if (totalFramesRead == 0) {
  50072. result = MA_AT_END;
  50073. }
  50074. if (pFramesRead != NULL) {
  50075. *pFramesRead = totalFramesRead;
  50076. }
  50077. if (result == MA_SUCCESS && totalFramesRead == 0) {
  50078. result = MA_AT_END;
  50079. }
  50080. return result;
  50081. }
  50082. #else
  50083. {
  50084. /* flac is disabled. Should never hit this since initialization would have failed. */
  50085. MA_ASSERT(MA_FALSE);
  50086. (void)pFramesOut;
  50087. (void)frameCount;
  50088. (void)pFramesRead;
  50089. return MA_NOT_IMPLEMENTED;
  50090. }
  50091. #endif
  50092. }
  50093. MA_API ma_result ma_flac_seek_to_pcm_frame(ma_flac* pFlac, ma_uint64 frameIndex)
  50094. {
  50095. if (pFlac == NULL) {
  50096. return MA_INVALID_ARGS;
  50097. }
  50098. #if !defined(MA_NO_FLAC)
  50099. {
  50100. drflac_bool32 flacResult;
  50101. flacResult = drflac_seek_to_pcm_frame(pFlac->dr, frameIndex);
  50102. if (flacResult != DRFLAC_TRUE) {
  50103. return MA_ERROR;
  50104. }
  50105. return MA_SUCCESS;
  50106. }
  50107. #else
  50108. {
  50109. /* flac is disabled. Should never hit this since initialization would have failed. */
  50110. MA_ASSERT(MA_FALSE);
  50111. (void)frameIndex;
  50112. return MA_NOT_IMPLEMENTED;
  50113. }
  50114. #endif
  50115. }
  50116. 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)
  50117. {
  50118. /* Defaults for safety. */
  50119. if (pFormat != NULL) {
  50120. *pFormat = ma_format_unknown;
  50121. }
  50122. if (pChannels != NULL) {
  50123. *pChannels = 0;
  50124. }
  50125. if (pSampleRate != NULL) {
  50126. *pSampleRate = 0;
  50127. }
  50128. if (pChannelMap != NULL) {
  50129. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  50130. }
  50131. if (pFlac == NULL) {
  50132. return MA_INVALID_OPERATION;
  50133. }
  50134. if (pFormat != NULL) {
  50135. *pFormat = pFlac->format;
  50136. }
  50137. #if !defined(MA_NO_FLAC)
  50138. {
  50139. if (pChannels != NULL) {
  50140. *pChannels = pFlac->dr->channels;
  50141. }
  50142. if (pSampleRate != NULL) {
  50143. *pSampleRate = pFlac->dr->sampleRate;
  50144. }
  50145. if (pChannelMap != NULL) {
  50146. ma_channel_map_init_standard(ma_standard_channel_map_microsoft, pChannelMap, channelMapCap, pFlac->dr->channels);
  50147. }
  50148. return MA_SUCCESS;
  50149. }
  50150. #else
  50151. {
  50152. /* flac is disabled. Should never hit this since initialization would have failed. */
  50153. MA_ASSERT(MA_FALSE);
  50154. return MA_NOT_IMPLEMENTED;
  50155. }
  50156. #endif
  50157. }
  50158. MA_API ma_result ma_flac_get_cursor_in_pcm_frames(ma_flac* pFlac, ma_uint64* pCursor)
  50159. {
  50160. if (pCursor == NULL) {
  50161. return MA_INVALID_ARGS;
  50162. }
  50163. *pCursor = 0; /* Safety. */
  50164. if (pFlac == NULL) {
  50165. return MA_INVALID_ARGS;
  50166. }
  50167. #if !defined(MA_NO_FLAC)
  50168. {
  50169. *pCursor = pFlac->dr->currentPCMFrame;
  50170. return MA_SUCCESS;
  50171. }
  50172. #else
  50173. {
  50174. /* flac is disabled. Should never hit this since initialization would have failed. */
  50175. MA_ASSERT(MA_FALSE);
  50176. return MA_NOT_IMPLEMENTED;
  50177. }
  50178. #endif
  50179. }
  50180. MA_API ma_result ma_flac_get_length_in_pcm_frames(ma_flac* pFlac, ma_uint64* pLength)
  50181. {
  50182. if (pLength == NULL) {
  50183. return MA_INVALID_ARGS;
  50184. }
  50185. *pLength = 0; /* Safety. */
  50186. if (pFlac == NULL) {
  50187. return MA_INVALID_ARGS;
  50188. }
  50189. #if !defined(MA_NO_FLAC)
  50190. {
  50191. *pLength = pFlac->dr->totalPCMFrameCount;
  50192. return MA_SUCCESS;
  50193. }
  50194. #else
  50195. {
  50196. /* flac is disabled. Should never hit this since initialization would have failed. */
  50197. MA_ASSERT(MA_FALSE);
  50198. return MA_NOT_IMPLEMENTED;
  50199. }
  50200. #endif
  50201. }
  50202. 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)
  50203. {
  50204. ma_result result;
  50205. ma_flac* pFlac;
  50206. (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. */
  50207. /* For now we're just allocating the decoder backend on the heap. */
  50208. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  50209. if (pFlac == NULL) {
  50210. return MA_OUT_OF_MEMORY;
  50211. }
  50212. result = ma_flac_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pFlac);
  50213. if (result != MA_SUCCESS) {
  50214. ma_free(pFlac, pAllocationCallbacks);
  50215. return result;
  50216. }
  50217. *ppBackend = pFlac;
  50218. return MA_SUCCESS;
  50219. }
  50220. 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)
  50221. {
  50222. ma_result result;
  50223. ma_flac* pFlac;
  50224. (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. */
  50225. /* For now we're just allocating the decoder backend on the heap. */
  50226. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  50227. if (pFlac == NULL) {
  50228. return MA_OUT_OF_MEMORY;
  50229. }
  50230. result = ma_flac_init_file(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  50231. if (result != MA_SUCCESS) {
  50232. ma_free(pFlac, pAllocationCallbacks);
  50233. return result;
  50234. }
  50235. *ppBackend = pFlac;
  50236. return MA_SUCCESS;
  50237. }
  50238. 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)
  50239. {
  50240. ma_result result;
  50241. ma_flac* pFlac;
  50242. (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. */
  50243. /* For now we're just allocating the decoder backend on the heap. */
  50244. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  50245. if (pFlac == NULL) {
  50246. return MA_OUT_OF_MEMORY;
  50247. }
  50248. result = ma_flac_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pFlac);
  50249. if (result != MA_SUCCESS) {
  50250. ma_free(pFlac, pAllocationCallbacks);
  50251. return result;
  50252. }
  50253. *ppBackend = pFlac;
  50254. return MA_SUCCESS;
  50255. }
  50256. 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)
  50257. {
  50258. ma_result result;
  50259. ma_flac* pFlac;
  50260. (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. */
  50261. /* For now we're just allocating the decoder backend on the heap. */
  50262. pFlac = (ma_flac*)ma_malloc(sizeof(*pFlac), pAllocationCallbacks);
  50263. if (pFlac == NULL) {
  50264. return MA_OUT_OF_MEMORY;
  50265. }
  50266. result = ma_flac_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pFlac);
  50267. if (result != MA_SUCCESS) {
  50268. ma_free(pFlac, pAllocationCallbacks);
  50269. return result;
  50270. }
  50271. *ppBackend = pFlac;
  50272. return MA_SUCCESS;
  50273. }
  50274. static void ma_decoding_backend_uninit__flac(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  50275. {
  50276. ma_flac* pFlac = (ma_flac*)pBackend;
  50277. (void)pUserData;
  50278. ma_flac_uninit(pFlac, pAllocationCallbacks);
  50279. ma_free(pFlac, pAllocationCallbacks);
  50280. }
  50281. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_flac =
  50282. {
  50283. ma_decoding_backend_init__flac,
  50284. ma_decoding_backend_init_file__flac,
  50285. ma_decoding_backend_init_file_w__flac,
  50286. ma_decoding_backend_init_memory__flac,
  50287. ma_decoding_backend_uninit__flac
  50288. };
  50289. static ma_result ma_decoder_init_flac__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50290. {
  50291. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_flac, NULL, pConfig, pDecoder);
  50292. }
  50293. #endif /* dr_flac_h */
  50294. /* MP3 */
  50295. #ifdef dr_mp3_h
  50296. #define MA_HAS_MP3
  50297. typedef struct
  50298. {
  50299. ma_data_source_base ds;
  50300. ma_read_proc onRead;
  50301. ma_seek_proc onSeek;
  50302. ma_tell_proc onTell;
  50303. void* pReadSeekTellUserData;
  50304. ma_format format; /* Can be f32 or s16. */
  50305. #if !defined(MA_NO_MP3)
  50306. drmp3 dr;
  50307. drmp3_uint32 seekPointCount;
  50308. drmp3_seek_point* pSeekPoints; /* Only used if seek table generation is used. */
  50309. #endif
  50310. } ma_mp3;
  50311. 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);
  50312. 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);
  50313. 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);
  50314. 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);
  50315. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks);
  50316. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  50317. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex);
  50318. 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);
  50319. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor);
  50320. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength);
  50321. static ma_result ma_mp3_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50322. {
  50323. return ma_mp3_read_pcm_frames((ma_mp3*)pDataSource, pFramesOut, frameCount, pFramesRead);
  50324. }
  50325. static ma_result ma_mp3_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  50326. {
  50327. return ma_mp3_seek_to_pcm_frame((ma_mp3*)pDataSource, frameIndex);
  50328. }
  50329. 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)
  50330. {
  50331. return ma_mp3_get_data_format((ma_mp3*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  50332. }
  50333. static ma_result ma_mp3_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  50334. {
  50335. return ma_mp3_get_cursor_in_pcm_frames((ma_mp3*)pDataSource, pCursor);
  50336. }
  50337. static ma_result ma_mp3_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  50338. {
  50339. return ma_mp3_get_length_in_pcm_frames((ma_mp3*)pDataSource, pLength);
  50340. }
  50341. static ma_data_source_vtable g_ma_mp3_ds_vtable =
  50342. {
  50343. ma_mp3_ds_read,
  50344. ma_mp3_ds_seek,
  50345. ma_mp3_ds_get_data_format,
  50346. ma_mp3_ds_get_cursor,
  50347. ma_mp3_ds_get_length,
  50348. NULL, /* onSetLooping */
  50349. 0
  50350. };
  50351. #if !defined(MA_NO_MP3)
  50352. static drmp3_allocation_callbacks drmp3_allocation_callbacks_from_miniaudio(const ma_allocation_callbacks* pAllocationCallbacks)
  50353. {
  50354. drmp3_allocation_callbacks callbacks;
  50355. if (pAllocationCallbacks != NULL) {
  50356. callbacks.onMalloc = pAllocationCallbacks->onMalloc;
  50357. callbacks.onRealloc = pAllocationCallbacks->onRealloc;
  50358. callbacks.onFree = pAllocationCallbacks->onFree;
  50359. callbacks.pUserData = pAllocationCallbacks->pUserData;
  50360. } else {
  50361. callbacks.onMalloc = ma__malloc_default;
  50362. callbacks.onRealloc = ma__realloc_default;
  50363. callbacks.onFree = ma__free_default;
  50364. callbacks.pUserData = NULL;
  50365. }
  50366. return callbacks;
  50367. }
  50368. static size_t ma_mp3_dr_callback__read(void* pUserData, void* pBufferOut, size_t bytesToRead)
  50369. {
  50370. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  50371. ma_result result;
  50372. size_t bytesRead;
  50373. MA_ASSERT(pMP3 != NULL);
  50374. result = pMP3->onRead(pMP3->pReadSeekTellUserData, pBufferOut, bytesToRead, &bytesRead);
  50375. (void)result;
  50376. return bytesRead;
  50377. }
  50378. static drmp3_bool32 ma_mp3_dr_callback__seek(void* pUserData, int offset, drmp3_seek_origin origin)
  50379. {
  50380. ma_mp3* pMP3 = (ma_mp3*)pUserData;
  50381. ma_result result;
  50382. ma_seek_origin maSeekOrigin;
  50383. MA_ASSERT(pMP3 != NULL);
  50384. maSeekOrigin = ma_seek_origin_start;
  50385. if (origin == drmp3_seek_origin_current) {
  50386. maSeekOrigin = ma_seek_origin_current;
  50387. }
  50388. result = pMP3->onSeek(pMP3->pReadSeekTellUserData, offset, maSeekOrigin);
  50389. if (result != MA_SUCCESS) {
  50390. return MA_FALSE;
  50391. }
  50392. return MA_TRUE;
  50393. }
  50394. #endif
  50395. static ma_result ma_mp3_init_internal(const ma_decoding_backend_config* pConfig, ma_mp3* pMP3)
  50396. {
  50397. ma_result result;
  50398. ma_data_source_config dataSourceConfig;
  50399. if (pMP3 == NULL) {
  50400. return MA_INVALID_ARGS;
  50401. }
  50402. MA_ZERO_OBJECT(pMP3);
  50403. pMP3->format = ma_format_f32; /* f32 by default. */
  50404. if (pConfig != NULL && (pConfig->preferredFormat == ma_format_f32 || pConfig->preferredFormat == ma_format_s16)) {
  50405. pMP3->format = pConfig->preferredFormat;
  50406. } else {
  50407. /* Getting here means something other than f32 and s16 was specified. Just leave this unset to use the default format. */
  50408. }
  50409. dataSourceConfig = ma_data_source_config_init();
  50410. dataSourceConfig.vtable = &g_ma_mp3_ds_vtable;
  50411. result = ma_data_source_init(&dataSourceConfig, &pMP3->ds);
  50412. if (result != MA_SUCCESS) {
  50413. return result; /* Failed to initialize the base data source. */
  50414. }
  50415. return MA_SUCCESS;
  50416. }
  50417. static ma_result ma_mp3_generate_seek_table(ma_mp3* pMP3, const ma_decoding_backend_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks)
  50418. {
  50419. drmp3_bool32 mp3Result;
  50420. drmp3_uint32 seekPointCount = 0;
  50421. drmp3_seek_point* pSeekPoints = NULL;
  50422. MA_ASSERT(pMP3 != NULL);
  50423. MA_ASSERT(pConfig != NULL);
  50424. seekPointCount = pConfig->seekPointCount;
  50425. if (seekPointCount > 0) {
  50426. pSeekPoints = (drmp3_seek_point*)ma_malloc(sizeof(*pMP3->pSeekPoints) * seekPointCount, pAllocationCallbacks);
  50427. if (pSeekPoints == NULL) {
  50428. return MA_OUT_OF_MEMORY;
  50429. }
  50430. }
  50431. mp3Result = drmp3_calculate_seek_points(&pMP3->dr, &seekPointCount, pSeekPoints);
  50432. if (mp3Result != MA_TRUE) {
  50433. ma_free(pSeekPoints, pAllocationCallbacks);
  50434. return MA_ERROR;
  50435. }
  50436. mp3Result = drmp3_bind_seek_table(&pMP3->dr, seekPointCount, pSeekPoints);
  50437. if (mp3Result != MA_TRUE) {
  50438. ma_free(pSeekPoints, pAllocationCallbacks);
  50439. return MA_ERROR;
  50440. }
  50441. pMP3->seekPointCount = seekPointCount;
  50442. pMP3->pSeekPoints = pSeekPoints;
  50443. return MA_SUCCESS;
  50444. }
  50445. 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)
  50446. {
  50447. ma_result result;
  50448. result = ma_mp3_init_internal(pConfig, pMP3);
  50449. if (result != MA_SUCCESS) {
  50450. return result;
  50451. }
  50452. if (onRead == NULL || onSeek == NULL) {
  50453. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  50454. }
  50455. pMP3->onRead = onRead;
  50456. pMP3->onSeek = onSeek;
  50457. pMP3->onTell = onTell;
  50458. pMP3->pReadSeekTellUserData = pReadSeekTellUserData;
  50459. #if !defined(MA_NO_MP3)
  50460. {
  50461. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50462. drmp3_bool32 mp3Result;
  50463. mp3Result = drmp3_init(&pMP3->dr, ma_mp3_dr_callback__read, ma_mp3_dr_callback__seek, pMP3, &mp3AllocationCallbacks);
  50464. if (mp3Result != MA_TRUE) {
  50465. return MA_INVALID_FILE;
  50466. }
  50467. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  50468. return MA_SUCCESS;
  50469. }
  50470. #else
  50471. {
  50472. /* mp3 is disabled. */
  50473. (void)pAllocationCallbacks;
  50474. return MA_NOT_IMPLEMENTED;
  50475. }
  50476. #endif
  50477. }
  50478. 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)
  50479. {
  50480. ma_result result;
  50481. result = ma_mp3_init_internal(pConfig, pMP3);
  50482. if (result != MA_SUCCESS) {
  50483. return result;
  50484. }
  50485. #if !defined(MA_NO_MP3)
  50486. {
  50487. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50488. drmp3_bool32 mp3Result;
  50489. mp3Result = drmp3_init_file(&pMP3->dr, pFilePath, &mp3AllocationCallbacks);
  50490. if (mp3Result != MA_TRUE) {
  50491. return MA_INVALID_FILE;
  50492. }
  50493. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  50494. return MA_SUCCESS;
  50495. }
  50496. #else
  50497. {
  50498. /* mp3 is disabled. */
  50499. (void)pFilePath;
  50500. (void)pAllocationCallbacks;
  50501. return MA_NOT_IMPLEMENTED;
  50502. }
  50503. #endif
  50504. }
  50505. 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)
  50506. {
  50507. ma_result result;
  50508. result = ma_mp3_init_internal(pConfig, pMP3);
  50509. if (result != MA_SUCCESS) {
  50510. return result;
  50511. }
  50512. #if !defined(MA_NO_MP3)
  50513. {
  50514. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50515. drmp3_bool32 mp3Result;
  50516. mp3Result = drmp3_init_file_w(&pMP3->dr, pFilePath, &mp3AllocationCallbacks);
  50517. if (mp3Result != MA_TRUE) {
  50518. return MA_INVALID_FILE;
  50519. }
  50520. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  50521. return MA_SUCCESS;
  50522. }
  50523. #else
  50524. {
  50525. /* mp3 is disabled. */
  50526. (void)pFilePath;
  50527. (void)pAllocationCallbacks;
  50528. return MA_NOT_IMPLEMENTED;
  50529. }
  50530. #endif
  50531. }
  50532. 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)
  50533. {
  50534. ma_result result;
  50535. result = ma_mp3_init_internal(pConfig, pMP3);
  50536. if (result != MA_SUCCESS) {
  50537. return result;
  50538. }
  50539. #if !defined(MA_NO_MP3)
  50540. {
  50541. drmp3_allocation_callbacks mp3AllocationCallbacks = drmp3_allocation_callbacks_from_miniaudio(pAllocationCallbacks);
  50542. drmp3_bool32 mp3Result;
  50543. mp3Result = drmp3_init_memory(&pMP3->dr, pData, dataSize, &mp3AllocationCallbacks);
  50544. if (mp3Result != MA_TRUE) {
  50545. return MA_INVALID_FILE;
  50546. }
  50547. ma_mp3_generate_seek_table(pMP3, pConfig, pAllocationCallbacks);
  50548. return MA_SUCCESS;
  50549. }
  50550. #else
  50551. {
  50552. /* mp3 is disabled. */
  50553. (void)pData;
  50554. (void)dataSize;
  50555. (void)pAllocationCallbacks;
  50556. return MA_NOT_IMPLEMENTED;
  50557. }
  50558. #endif
  50559. }
  50560. MA_API void ma_mp3_uninit(ma_mp3* pMP3, const ma_allocation_callbacks* pAllocationCallbacks)
  50561. {
  50562. if (pMP3 == NULL) {
  50563. return;
  50564. }
  50565. #if !defined(MA_NO_MP3)
  50566. {
  50567. drmp3_uninit(&pMP3->dr);
  50568. }
  50569. #else
  50570. {
  50571. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50572. MA_ASSERT(MA_FALSE);
  50573. }
  50574. #endif
  50575. /* Seek points need to be freed after the MP3 decoder has been uninitialized to ensure they're no longer being referenced. */
  50576. ma_free(pMP3->pSeekPoints, pAllocationCallbacks);
  50577. ma_data_source_uninit(&pMP3->ds);
  50578. }
  50579. MA_API ma_result ma_mp3_read_pcm_frames(ma_mp3* pMP3, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50580. {
  50581. if (pFramesRead != NULL) {
  50582. *pFramesRead = 0;
  50583. }
  50584. if (frameCount == 0) {
  50585. return MA_INVALID_ARGS;
  50586. }
  50587. if (pMP3 == NULL) {
  50588. return MA_INVALID_ARGS;
  50589. }
  50590. #if !defined(MA_NO_MP3)
  50591. {
  50592. /* We always use floating point format. */
  50593. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  50594. ma_uint64 totalFramesRead = 0;
  50595. ma_format format;
  50596. ma_mp3_get_data_format(pMP3, &format, NULL, NULL, NULL, 0);
  50597. switch (format)
  50598. {
  50599. case ma_format_f32:
  50600. {
  50601. totalFramesRead = drmp3_read_pcm_frames_f32(&pMP3->dr, frameCount, (float*)pFramesOut);
  50602. } break;
  50603. case ma_format_s16:
  50604. {
  50605. totalFramesRead = drmp3_read_pcm_frames_s16(&pMP3->dr, frameCount, (drmp3_int16*)pFramesOut);
  50606. } break;
  50607. case ma_format_u8:
  50608. case ma_format_s24:
  50609. case ma_format_s32:
  50610. case ma_format_unknown:
  50611. default:
  50612. {
  50613. return MA_INVALID_OPERATION;
  50614. };
  50615. }
  50616. /* In the future we'll update dr_mp3 to return MA_AT_END for us. */
  50617. if (totalFramesRead == 0) {
  50618. result = MA_AT_END;
  50619. }
  50620. if (pFramesRead != NULL) {
  50621. *pFramesRead = totalFramesRead;
  50622. }
  50623. return result;
  50624. }
  50625. #else
  50626. {
  50627. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50628. MA_ASSERT(MA_FALSE);
  50629. (void)pFramesOut;
  50630. (void)frameCount;
  50631. (void)pFramesRead;
  50632. return MA_NOT_IMPLEMENTED;
  50633. }
  50634. #endif
  50635. }
  50636. MA_API ma_result ma_mp3_seek_to_pcm_frame(ma_mp3* pMP3, ma_uint64 frameIndex)
  50637. {
  50638. if (pMP3 == NULL) {
  50639. return MA_INVALID_ARGS;
  50640. }
  50641. #if !defined(MA_NO_MP3)
  50642. {
  50643. drmp3_bool32 mp3Result;
  50644. mp3Result = drmp3_seek_to_pcm_frame(&pMP3->dr, frameIndex);
  50645. if (mp3Result != DRMP3_TRUE) {
  50646. return MA_ERROR;
  50647. }
  50648. return MA_SUCCESS;
  50649. }
  50650. #else
  50651. {
  50652. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50653. MA_ASSERT(MA_FALSE);
  50654. (void)frameIndex;
  50655. return MA_NOT_IMPLEMENTED;
  50656. }
  50657. #endif
  50658. }
  50659. 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)
  50660. {
  50661. /* Defaults for safety. */
  50662. if (pFormat != NULL) {
  50663. *pFormat = ma_format_unknown;
  50664. }
  50665. if (pChannels != NULL) {
  50666. *pChannels = 0;
  50667. }
  50668. if (pSampleRate != NULL) {
  50669. *pSampleRate = 0;
  50670. }
  50671. if (pChannelMap != NULL) {
  50672. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  50673. }
  50674. if (pMP3 == NULL) {
  50675. return MA_INVALID_OPERATION;
  50676. }
  50677. if (pFormat != NULL) {
  50678. *pFormat = pMP3->format;
  50679. }
  50680. #if !defined(MA_NO_MP3)
  50681. {
  50682. if (pChannels != NULL) {
  50683. *pChannels = pMP3->dr.channels;
  50684. }
  50685. if (pSampleRate != NULL) {
  50686. *pSampleRate = pMP3->dr.sampleRate;
  50687. }
  50688. if (pChannelMap != NULL) {
  50689. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pMP3->dr.channels);
  50690. }
  50691. return MA_SUCCESS;
  50692. }
  50693. #else
  50694. {
  50695. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50696. MA_ASSERT(MA_FALSE);
  50697. return MA_NOT_IMPLEMENTED;
  50698. }
  50699. #endif
  50700. }
  50701. MA_API ma_result ma_mp3_get_cursor_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pCursor)
  50702. {
  50703. if (pCursor == NULL) {
  50704. return MA_INVALID_ARGS;
  50705. }
  50706. *pCursor = 0; /* Safety. */
  50707. if (pMP3 == NULL) {
  50708. return MA_INVALID_ARGS;
  50709. }
  50710. #if !defined(MA_NO_MP3)
  50711. {
  50712. *pCursor = pMP3->dr.currentPCMFrame;
  50713. return MA_SUCCESS;
  50714. }
  50715. #else
  50716. {
  50717. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50718. MA_ASSERT(MA_FALSE);
  50719. return MA_NOT_IMPLEMENTED;
  50720. }
  50721. #endif
  50722. }
  50723. MA_API ma_result ma_mp3_get_length_in_pcm_frames(ma_mp3* pMP3, ma_uint64* pLength)
  50724. {
  50725. if (pLength == NULL) {
  50726. return MA_INVALID_ARGS;
  50727. }
  50728. *pLength = 0; /* Safety. */
  50729. if (pMP3 == NULL) {
  50730. return MA_INVALID_ARGS;
  50731. }
  50732. #if !defined(MA_NO_MP3)
  50733. {
  50734. *pLength = drmp3_get_pcm_frame_count(&pMP3->dr);
  50735. return MA_SUCCESS;
  50736. }
  50737. #else
  50738. {
  50739. /* mp3 is disabled. Should never hit this since initialization would have failed. */
  50740. MA_ASSERT(MA_FALSE);
  50741. return MA_NOT_IMPLEMENTED;
  50742. }
  50743. #endif
  50744. }
  50745. 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)
  50746. {
  50747. ma_result result;
  50748. ma_mp3* pMP3;
  50749. (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. */
  50750. /* For now we're just allocating the decoder backend on the heap. */
  50751. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  50752. if (pMP3 == NULL) {
  50753. return MA_OUT_OF_MEMORY;
  50754. }
  50755. result = ma_mp3_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pMP3);
  50756. if (result != MA_SUCCESS) {
  50757. ma_free(pMP3, pAllocationCallbacks);
  50758. return result;
  50759. }
  50760. *ppBackend = pMP3;
  50761. return MA_SUCCESS;
  50762. }
  50763. 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)
  50764. {
  50765. ma_result result;
  50766. ma_mp3* pMP3;
  50767. (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. */
  50768. /* For now we're just allocating the decoder backend on the heap. */
  50769. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  50770. if (pMP3 == NULL) {
  50771. return MA_OUT_OF_MEMORY;
  50772. }
  50773. result = ma_mp3_init_file(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  50774. if (result != MA_SUCCESS) {
  50775. ma_free(pMP3, pAllocationCallbacks);
  50776. return result;
  50777. }
  50778. *ppBackend = pMP3;
  50779. return MA_SUCCESS;
  50780. }
  50781. 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)
  50782. {
  50783. ma_result result;
  50784. ma_mp3* pMP3;
  50785. (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. */
  50786. /* For now we're just allocating the decoder backend on the heap. */
  50787. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  50788. if (pMP3 == NULL) {
  50789. return MA_OUT_OF_MEMORY;
  50790. }
  50791. result = ma_mp3_init_file_w(pFilePath, pConfig, pAllocationCallbacks, pMP3);
  50792. if (result != MA_SUCCESS) {
  50793. ma_free(pMP3, pAllocationCallbacks);
  50794. return result;
  50795. }
  50796. *ppBackend = pMP3;
  50797. return MA_SUCCESS;
  50798. }
  50799. 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)
  50800. {
  50801. ma_result result;
  50802. ma_mp3* pMP3;
  50803. (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. */
  50804. /* For now we're just allocating the decoder backend on the heap. */
  50805. pMP3 = (ma_mp3*)ma_malloc(sizeof(*pMP3), pAllocationCallbacks);
  50806. if (pMP3 == NULL) {
  50807. return MA_OUT_OF_MEMORY;
  50808. }
  50809. result = ma_mp3_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pMP3);
  50810. if (result != MA_SUCCESS) {
  50811. ma_free(pMP3, pAllocationCallbacks);
  50812. return result;
  50813. }
  50814. *ppBackend = pMP3;
  50815. return MA_SUCCESS;
  50816. }
  50817. static void ma_decoding_backend_uninit__mp3(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  50818. {
  50819. ma_mp3* pMP3 = (ma_mp3*)pBackend;
  50820. (void)pUserData;
  50821. ma_mp3_uninit(pMP3, pAllocationCallbacks);
  50822. ma_free(pMP3, pAllocationCallbacks);
  50823. }
  50824. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_mp3 =
  50825. {
  50826. ma_decoding_backend_init__mp3,
  50827. ma_decoding_backend_init_file__mp3,
  50828. ma_decoding_backend_init_file_w__mp3,
  50829. ma_decoding_backend_init_memory__mp3,
  50830. ma_decoding_backend_uninit__mp3
  50831. };
  50832. static ma_result ma_decoder_init_mp3__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  50833. {
  50834. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_mp3, NULL, pConfig, pDecoder);
  50835. }
  50836. #endif /* dr_mp3_h */
  50837. /* Vorbis */
  50838. #ifdef STB_VORBIS_INCLUDE_STB_VORBIS_H
  50839. #define MA_HAS_VORBIS
  50840. /* The size in bytes of each chunk of data to read from the Vorbis stream. */
  50841. #define MA_VORBIS_DATA_CHUNK_SIZE 4096
  50842. typedef struct
  50843. {
  50844. ma_data_source_base ds;
  50845. ma_read_proc onRead;
  50846. ma_seek_proc onSeek;
  50847. ma_tell_proc onTell;
  50848. void* pReadSeekTellUserData;
  50849. 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. */
  50850. ma_format format; /* Only f32 is allowed with stb_vorbis. */
  50851. ma_uint32 channels;
  50852. ma_uint32 sampleRate;
  50853. ma_uint64 cursor;
  50854. #if !defined(MA_NO_VORBIS)
  50855. stb_vorbis* stb;
  50856. ma_bool32 usingPushMode;
  50857. struct
  50858. {
  50859. ma_uint8* pData;
  50860. size_t dataSize;
  50861. size_t dataCapacity;
  50862. ma_uint32 framesConsumed; /* The number of frames consumed in ppPacketData. */
  50863. ma_uint32 framesRemaining; /* The number of frames remaining in ppPacketData. */
  50864. float** ppPacketData;
  50865. } push;
  50866. #endif
  50867. } ma_stbvorbis;
  50868. 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);
  50869. 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);
  50870. 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);
  50871. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks);
  50872. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead);
  50873. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex);
  50874. 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);
  50875. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor);
  50876. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength);
  50877. static ma_result ma_stbvorbis_ds_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  50878. {
  50879. return ma_stbvorbis_read_pcm_frames((ma_stbvorbis*)pDataSource, pFramesOut, frameCount, pFramesRead);
  50880. }
  50881. static ma_result ma_stbvorbis_ds_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  50882. {
  50883. return ma_stbvorbis_seek_to_pcm_frame((ma_stbvorbis*)pDataSource, frameIndex);
  50884. }
  50885. 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)
  50886. {
  50887. return ma_stbvorbis_get_data_format((ma_stbvorbis*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  50888. }
  50889. static ma_result ma_stbvorbis_ds_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  50890. {
  50891. return ma_stbvorbis_get_cursor_in_pcm_frames((ma_stbvorbis*)pDataSource, pCursor);
  50892. }
  50893. static ma_result ma_stbvorbis_ds_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  50894. {
  50895. return ma_stbvorbis_get_length_in_pcm_frames((ma_stbvorbis*)pDataSource, pLength);
  50896. }
  50897. static ma_data_source_vtable g_ma_stbvorbis_ds_vtable =
  50898. {
  50899. ma_stbvorbis_ds_read,
  50900. ma_stbvorbis_ds_seek,
  50901. ma_stbvorbis_ds_get_data_format,
  50902. ma_stbvorbis_ds_get_cursor,
  50903. ma_stbvorbis_ds_get_length,
  50904. NULL, /* onSetLooping */
  50905. 0
  50906. };
  50907. static ma_result ma_stbvorbis_init_internal(const ma_decoding_backend_config* pConfig, ma_stbvorbis* pVorbis)
  50908. {
  50909. ma_result result;
  50910. ma_data_source_config dataSourceConfig;
  50911. (void)pConfig;
  50912. if (pVorbis == NULL) {
  50913. return MA_INVALID_ARGS;
  50914. }
  50915. MA_ZERO_OBJECT(pVorbis);
  50916. pVorbis->format = ma_format_f32; /* Only supporting f32. */
  50917. dataSourceConfig = ma_data_source_config_init();
  50918. dataSourceConfig.vtable = &g_ma_stbvorbis_ds_vtable;
  50919. result = ma_data_source_init(&dataSourceConfig, &pVorbis->ds);
  50920. if (result != MA_SUCCESS) {
  50921. return result; /* Failed to initialize the base data source. */
  50922. }
  50923. return MA_SUCCESS;
  50924. }
  50925. #if !defined(MA_NO_VORBIS)
  50926. static ma_result ma_stbvorbis_post_init(ma_stbvorbis* pVorbis)
  50927. {
  50928. stb_vorbis_info info;
  50929. MA_ASSERT(pVorbis != NULL);
  50930. info = stb_vorbis_get_info(pVorbis->stb);
  50931. pVorbis->channels = info.channels;
  50932. pVorbis->sampleRate = info.sample_rate;
  50933. return MA_SUCCESS;
  50934. }
  50935. #endif
  50936. 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)
  50937. {
  50938. ma_result result;
  50939. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  50940. if (result != MA_SUCCESS) {
  50941. return result;
  50942. }
  50943. if (onRead == NULL || onSeek == NULL) {
  50944. return MA_INVALID_ARGS; /* onRead and onSeek are mandatory. */
  50945. }
  50946. pVorbis->onRead = onRead;
  50947. pVorbis->onSeek = onSeek;
  50948. pVorbis->onTell = onTell;
  50949. pVorbis->pReadSeekTellUserData = pReadSeekTellUserData;
  50950. ma_allocation_callbacks_init_copy(&pVorbis->allocationCallbacks, pAllocationCallbacks);
  50951. #if !defined(MA_NO_VORBIS)
  50952. {
  50953. /*
  50954. stb_vorbis lacks a callback based API for it's pulling API which means we're stuck with the
  50955. pushing API. In order for us to be able to successfully initialize the decoder we need to
  50956. supply it with enough data. We need to keep loading data until we have enough.
  50957. */
  50958. stb_vorbis* stb;
  50959. size_t dataSize = 0;
  50960. size_t dataCapacity = 0;
  50961. ma_uint8* pData = NULL; /* <-- Must be initialized to NULL. */
  50962. for (;;) {
  50963. int vorbisError;
  50964. int consumedDataSize; /* <-- Fill by stb_vorbis_open_pushdata(). */
  50965. size_t bytesRead;
  50966. ma_uint8* pNewData;
  50967. /* Allocate memory for the new chunk. */
  50968. dataCapacity += MA_VORBIS_DATA_CHUNK_SIZE;
  50969. pNewData = (ma_uint8*)ma_realloc(pData, dataCapacity, pAllocationCallbacks);
  50970. if (pNewData == NULL) {
  50971. ma_free(pData, pAllocationCallbacks);
  50972. return MA_OUT_OF_MEMORY;
  50973. }
  50974. pData = pNewData;
  50975. /* Read in the next chunk. */
  50976. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pData, dataSize), (dataCapacity - dataSize), &bytesRead);
  50977. dataSize += bytesRead;
  50978. if (result != MA_SUCCESS) {
  50979. ma_free(pData, pAllocationCallbacks);
  50980. return result;
  50981. }
  50982. /* We have a maximum of 31 bits with stb_vorbis. */
  50983. if (dataSize > INT_MAX) {
  50984. ma_free(pData, pAllocationCallbacks);
  50985. return MA_TOO_BIG;
  50986. }
  50987. stb = stb_vorbis_open_pushdata(pData, (int)dataSize, &consumedDataSize, &vorbisError, NULL);
  50988. if (stb != NULL) {
  50989. /*
  50990. Successfully opened the Vorbis decoder. We might have some leftover unprocessed
  50991. data so we'll need to move that down to the front.
  50992. */
  50993. dataSize -= (size_t)consumedDataSize; /* Consume the data. */
  50994. MA_MOVE_MEMORY(pData, ma_offset_ptr(pData, consumedDataSize), dataSize);
  50995. break;
  50996. } else {
  50997. /* Failed to open the decoder. */
  50998. if (vorbisError == VORBIS_need_more_data) {
  50999. continue;
  51000. } else {
  51001. ma_free(pData, pAllocationCallbacks);
  51002. return MA_ERROR; /* Failed to open the stb_vorbis decoder. */
  51003. }
  51004. }
  51005. }
  51006. MA_ASSERT(stb != NULL);
  51007. pVorbis->stb = stb;
  51008. pVorbis->push.pData = pData;
  51009. pVorbis->push.dataSize = dataSize;
  51010. pVorbis->push.dataCapacity = dataCapacity;
  51011. pVorbis->usingPushMode = MA_TRUE;
  51012. result = ma_stbvorbis_post_init(pVorbis);
  51013. if (result != MA_SUCCESS) {
  51014. stb_vorbis_close(pVorbis->stb);
  51015. ma_free(pData, pAllocationCallbacks);
  51016. return result;
  51017. }
  51018. return MA_SUCCESS;
  51019. }
  51020. #else
  51021. {
  51022. /* vorbis is disabled. */
  51023. (void)pAllocationCallbacks;
  51024. return MA_NOT_IMPLEMENTED;
  51025. }
  51026. #endif
  51027. }
  51028. 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)
  51029. {
  51030. ma_result result;
  51031. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  51032. if (result != MA_SUCCESS) {
  51033. return result;
  51034. }
  51035. #if !defined(MA_NO_VORBIS)
  51036. {
  51037. (void)pAllocationCallbacks; /* Don't know how to make use of this with stb_vorbis. */
  51038. /* We can use stb_vorbis' pull mode for file based streams. */
  51039. pVorbis->stb = stb_vorbis_open_filename(pFilePath, NULL, NULL);
  51040. if (pVorbis->stb == NULL) {
  51041. return MA_INVALID_FILE;
  51042. }
  51043. pVorbis->usingPushMode = MA_FALSE;
  51044. result = ma_stbvorbis_post_init(pVorbis);
  51045. if (result != MA_SUCCESS) {
  51046. stb_vorbis_close(pVorbis->stb);
  51047. return result;
  51048. }
  51049. return MA_SUCCESS;
  51050. }
  51051. #else
  51052. {
  51053. /* vorbis is disabled. */
  51054. (void)pFilePath;
  51055. (void)pAllocationCallbacks;
  51056. return MA_NOT_IMPLEMENTED;
  51057. }
  51058. #endif
  51059. }
  51060. 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)
  51061. {
  51062. ma_result result;
  51063. result = ma_stbvorbis_init_internal(pConfig, pVorbis);
  51064. if (result != MA_SUCCESS) {
  51065. return result;
  51066. }
  51067. #if !defined(MA_NO_VORBIS)
  51068. {
  51069. (void)pAllocationCallbacks;
  51070. /* stb_vorbis uses an int as it's size specifier, restricting it to 32-bit even on 64-bit systems. *sigh*. */
  51071. if (dataSize > INT_MAX) {
  51072. return MA_TOO_BIG;
  51073. }
  51074. pVorbis->stb = stb_vorbis_open_memory((const unsigned char*)pData, (int)dataSize, NULL, NULL);
  51075. if (pVorbis->stb == NULL) {
  51076. return MA_INVALID_FILE;
  51077. }
  51078. pVorbis->usingPushMode = MA_FALSE;
  51079. result = ma_stbvorbis_post_init(pVorbis);
  51080. if (result != MA_SUCCESS) {
  51081. stb_vorbis_close(pVorbis->stb);
  51082. return result;
  51083. }
  51084. return MA_SUCCESS;
  51085. }
  51086. #else
  51087. {
  51088. /* vorbis is disabled. */
  51089. (void)pData;
  51090. (void)dataSize;
  51091. (void)pAllocationCallbacks;
  51092. return MA_NOT_IMPLEMENTED;
  51093. }
  51094. #endif
  51095. }
  51096. MA_API void ma_stbvorbis_uninit(ma_stbvorbis* pVorbis, const ma_allocation_callbacks* pAllocationCallbacks)
  51097. {
  51098. if (pVorbis == NULL) {
  51099. return;
  51100. }
  51101. #if !defined(MA_NO_VORBIS)
  51102. {
  51103. stb_vorbis_close(pVorbis->stb);
  51104. /* We'll have to clear some memory if we're using push mode. */
  51105. if (pVorbis->usingPushMode) {
  51106. ma_free(pVorbis->push.pData, pAllocationCallbacks);
  51107. }
  51108. }
  51109. #else
  51110. {
  51111. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51112. MA_ASSERT(MA_FALSE);
  51113. }
  51114. #endif
  51115. ma_data_source_uninit(&pVorbis->ds);
  51116. }
  51117. MA_API ma_result ma_stbvorbis_read_pcm_frames(ma_stbvorbis* pVorbis, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51118. {
  51119. if (pFramesRead != NULL) {
  51120. *pFramesRead = 0;
  51121. }
  51122. if (frameCount == 0) {
  51123. return MA_INVALID_ARGS;
  51124. }
  51125. if (pVorbis == NULL) {
  51126. return MA_INVALID_ARGS;
  51127. }
  51128. #if !defined(MA_NO_VORBIS)
  51129. {
  51130. /* We always use floating point format. */
  51131. ma_result result = MA_SUCCESS; /* Must be initialized to MA_SUCCESS. */
  51132. ma_uint64 totalFramesRead = 0;
  51133. ma_format format;
  51134. ma_uint32 channels;
  51135. ma_stbvorbis_get_data_format(pVorbis, &format, &channels, NULL, NULL, 0);
  51136. if (format == ma_format_f32) {
  51137. /* We read differently depending on whether or not we're using push mode. */
  51138. if (pVorbis->usingPushMode) {
  51139. /* Push mode. This is the complex case. */
  51140. float* pFramesOutF32 = (float*)pFramesOut;
  51141. while (totalFramesRead < frameCount) {
  51142. /* The first thing to do is read from any already-cached frames. */
  51143. ma_uint32 framesToReadFromCache = (ma_uint32)ma_min(pVorbis->push.framesRemaining, (frameCount - totalFramesRead)); /* Safe cast because pVorbis->framesRemaining is 32-bit. */
  51144. /* The output pointer can be null in which case we just treate it as a seek. */
  51145. if (pFramesOut != NULL) {
  51146. ma_uint64 iFrame;
  51147. for (iFrame = 0; iFrame < framesToReadFromCache; iFrame += 1) {
  51148. ma_uint32 iChannel;
  51149. for (iChannel = 0; iChannel < pVorbis->channels; iChannel += 1) {
  51150. pFramesOutF32[iChannel] = pVorbis->push.ppPacketData[iChannel][pVorbis->push.framesConsumed + iFrame];
  51151. }
  51152. pFramesOutF32 += pVorbis->channels;
  51153. }
  51154. }
  51155. /* Update pointers and counters. */
  51156. pVorbis->push.framesConsumed += framesToReadFromCache;
  51157. pVorbis->push.framesRemaining -= framesToReadFromCache;
  51158. totalFramesRead += framesToReadFromCache;
  51159. /* Don't bother reading any more frames right now if we've just finished loading. */
  51160. if (totalFramesRead == frameCount) {
  51161. break;
  51162. }
  51163. MA_ASSERT(pVorbis->push.framesRemaining == 0);
  51164. /* Getting here means we've run out of cached frames. We'll need to load some more. */
  51165. for (;;) {
  51166. int samplesRead = 0;
  51167. int consumedDataSize;
  51168. /* We need to case dataSize to an int, so make sure we can do it safely. */
  51169. if (pVorbis->push.dataSize > INT_MAX) {
  51170. break; /* Too big. */
  51171. }
  51172. consumedDataSize = stb_vorbis_decode_frame_pushdata(pVorbis->stb, pVorbis->push.pData, (int)pVorbis->push.dataSize, NULL, &pVorbis->push.ppPacketData, &samplesRead);
  51173. if (consumedDataSize != 0) {
  51174. /* Successfully decoded a Vorbis frame. Consume the data. */
  51175. pVorbis->push.dataSize -= (size_t)consumedDataSize;
  51176. MA_MOVE_MEMORY(pVorbis->push.pData, ma_offset_ptr(pVorbis->push.pData, consumedDataSize), pVorbis->push.dataSize);
  51177. pVorbis->push.framesConsumed = 0;
  51178. pVorbis->push.framesRemaining = samplesRead;
  51179. break;
  51180. } else {
  51181. /* Not enough data. Read more. */
  51182. size_t bytesRead;
  51183. /* Expand the data buffer if necessary. */
  51184. if (pVorbis->push.dataCapacity == pVorbis->push.dataSize) {
  51185. size_t newCap = pVorbis->push.dataCapacity + MA_VORBIS_DATA_CHUNK_SIZE;
  51186. ma_uint8* pNewData;
  51187. pNewData = (ma_uint8*)ma_realloc(pVorbis->push.pData, newCap, &pVorbis->allocationCallbacks);
  51188. if (pNewData == NULL) {
  51189. result = MA_OUT_OF_MEMORY;
  51190. break;
  51191. }
  51192. pVorbis->push.pData = pNewData;
  51193. pVorbis->push.dataCapacity = newCap;
  51194. }
  51195. /* We should have enough room to load some data. */
  51196. result = pVorbis->onRead(pVorbis->pReadSeekTellUserData, ma_offset_ptr(pVorbis->push.pData, pVorbis->push.dataSize), (pVorbis->push.dataCapacity - pVorbis->push.dataSize), &bytesRead);
  51197. pVorbis->push.dataSize += bytesRead;
  51198. if (result != MA_SUCCESS) {
  51199. break; /* Failed to read any data. Get out. */
  51200. }
  51201. }
  51202. }
  51203. /* 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). */
  51204. if (result != MA_SUCCESS) {
  51205. break;
  51206. }
  51207. }
  51208. } else {
  51209. /* 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. */
  51210. while (totalFramesRead < frameCount) {
  51211. ma_uint64 framesRemaining = (frameCount - totalFramesRead);
  51212. int framesRead;
  51213. if (framesRemaining > INT_MAX) {
  51214. framesRemaining = INT_MAX;
  51215. }
  51216. 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. */
  51217. totalFramesRead += framesRead;
  51218. if (framesRead < (int)framesRemaining) {
  51219. break; /* Nothing left to read. Get out. */
  51220. }
  51221. }
  51222. }
  51223. } else {
  51224. result = MA_INVALID_ARGS;
  51225. }
  51226. pVorbis->cursor += totalFramesRead;
  51227. if (totalFramesRead == 0) {
  51228. result = MA_AT_END;
  51229. }
  51230. if (pFramesRead != NULL) {
  51231. *pFramesRead = totalFramesRead;
  51232. }
  51233. if (result == MA_SUCCESS && totalFramesRead == 0) {
  51234. result = MA_AT_END;
  51235. }
  51236. return result;
  51237. }
  51238. #else
  51239. {
  51240. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51241. MA_ASSERT(MA_FALSE);
  51242. (void)pFramesOut;
  51243. (void)frameCount;
  51244. (void)pFramesRead;
  51245. return MA_NOT_IMPLEMENTED;
  51246. }
  51247. #endif
  51248. }
  51249. MA_API ma_result ma_stbvorbis_seek_to_pcm_frame(ma_stbvorbis* pVorbis, ma_uint64 frameIndex)
  51250. {
  51251. if (pVorbis == NULL) {
  51252. return MA_INVALID_ARGS;
  51253. }
  51254. #if !defined(MA_NO_VORBIS)
  51255. {
  51256. /* Different seeking methods depending on whether or not we're using push mode. */
  51257. if (pVorbis->usingPushMode) {
  51258. /* Push mode. This is the complex case. */
  51259. ma_result result;
  51260. float buffer[4096];
  51261. /*
  51262. This is terribly inefficient because stb_vorbis does not have a good seeking solution with it's push API. Currently this just performs
  51263. a full decode right from the start of the stream. Later on I'll need to write a layer that goes through all of the Ogg pages until we
  51264. find the one containing the sample we need. Then we know exactly where to seek for stb_vorbis.
  51265. TODO: Use seeking logic documented for stb_vorbis_flush_pushdata().
  51266. */
  51267. /* Seek to the start of the file to begin with. */
  51268. result = pVorbis->onSeek(pVorbis->pReadSeekTellUserData, 0, ma_seek_origin_start);
  51269. if (result != MA_SUCCESS) {
  51270. return result;
  51271. }
  51272. stb_vorbis_flush_pushdata(pVorbis->stb);
  51273. pVorbis->push.framesRemaining = 0;
  51274. pVorbis->push.dataSize = 0;
  51275. /* Move the cursor back to the start. We'll increment this in the loop below. */
  51276. pVorbis->cursor = 0;
  51277. while (pVorbis->cursor < frameIndex) {
  51278. ma_uint64 framesRead;
  51279. ma_uint64 framesToRead = ma_countof(buffer)/pVorbis->channels;
  51280. if (framesToRead > (frameIndex - pVorbis->cursor)) {
  51281. framesToRead = (frameIndex - pVorbis->cursor);
  51282. }
  51283. result = ma_stbvorbis_read_pcm_frames(pVorbis, buffer, framesToRead, &framesRead);
  51284. pVorbis->cursor += framesRead;
  51285. if (result != MA_SUCCESS) {
  51286. return result;
  51287. }
  51288. }
  51289. } else {
  51290. /* Pull mode. This is the simple case. */
  51291. int vorbisResult;
  51292. if (frameIndex > UINT_MAX) {
  51293. return MA_INVALID_ARGS; /* Trying to seek beyond the 32-bit maximum of stb_vorbis. */
  51294. }
  51295. vorbisResult = stb_vorbis_seek(pVorbis->stb, (unsigned int)frameIndex); /* Safe cast. */
  51296. if (vorbisResult == 0) {
  51297. return MA_ERROR; /* See failed. */
  51298. }
  51299. pVorbis->cursor = frameIndex;
  51300. }
  51301. return MA_SUCCESS;
  51302. }
  51303. #else
  51304. {
  51305. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51306. MA_ASSERT(MA_FALSE);
  51307. (void)frameIndex;
  51308. return MA_NOT_IMPLEMENTED;
  51309. }
  51310. #endif
  51311. }
  51312. 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)
  51313. {
  51314. /* Defaults for safety. */
  51315. if (pFormat != NULL) {
  51316. *pFormat = ma_format_unknown;
  51317. }
  51318. if (pChannels != NULL) {
  51319. *pChannels = 0;
  51320. }
  51321. if (pSampleRate != NULL) {
  51322. *pSampleRate = 0;
  51323. }
  51324. if (pChannelMap != NULL) {
  51325. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  51326. }
  51327. if (pVorbis == NULL) {
  51328. return MA_INVALID_OPERATION;
  51329. }
  51330. if (pFormat != NULL) {
  51331. *pFormat = pVorbis->format;
  51332. }
  51333. #if !defined(MA_NO_VORBIS)
  51334. {
  51335. if (pChannels != NULL) {
  51336. *pChannels = pVorbis->channels;
  51337. }
  51338. if (pSampleRate != NULL) {
  51339. *pSampleRate = pVorbis->sampleRate;
  51340. }
  51341. if (pChannelMap != NULL) {
  51342. ma_channel_map_init_standard(ma_standard_channel_map_vorbis, pChannelMap, channelMapCap, pVorbis->channels);
  51343. }
  51344. return MA_SUCCESS;
  51345. }
  51346. #else
  51347. {
  51348. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51349. MA_ASSERT(MA_FALSE);
  51350. return MA_NOT_IMPLEMENTED;
  51351. }
  51352. #endif
  51353. }
  51354. MA_API ma_result ma_stbvorbis_get_cursor_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pCursor)
  51355. {
  51356. if (pCursor == NULL) {
  51357. return MA_INVALID_ARGS;
  51358. }
  51359. *pCursor = 0; /* Safety. */
  51360. if (pVorbis == NULL) {
  51361. return MA_INVALID_ARGS;
  51362. }
  51363. #if !defined(MA_NO_VORBIS)
  51364. {
  51365. *pCursor = pVorbis->cursor;
  51366. return MA_SUCCESS;
  51367. }
  51368. #else
  51369. {
  51370. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51371. MA_ASSERT(MA_FALSE);
  51372. return MA_NOT_IMPLEMENTED;
  51373. }
  51374. #endif
  51375. }
  51376. MA_API ma_result ma_stbvorbis_get_length_in_pcm_frames(ma_stbvorbis* pVorbis, ma_uint64* pLength)
  51377. {
  51378. if (pLength == NULL) {
  51379. return MA_INVALID_ARGS;
  51380. }
  51381. *pLength = 0; /* Safety. */
  51382. if (pVorbis == NULL) {
  51383. return MA_INVALID_ARGS;
  51384. }
  51385. #if !defined(MA_NO_VORBIS)
  51386. {
  51387. if (pVorbis->usingPushMode) {
  51388. *pLength = 0; /* I don't know of a good way to determine this reliably with stb_vorbis and push mode. */
  51389. } else {
  51390. *pLength = stb_vorbis_stream_length_in_samples(pVorbis->stb);
  51391. }
  51392. return MA_SUCCESS;
  51393. }
  51394. #else
  51395. {
  51396. /* vorbis is disabled. Should never hit this since initialization would have failed. */
  51397. MA_ASSERT(MA_FALSE);
  51398. return MA_NOT_IMPLEMENTED;
  51399. }
  51400. #endif
  51401. }
  51402. 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)
  51403. {
  51404. ma_result result;
  51405. ma_stbvorbis* pVorbis;
  51406. (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. */
  51407. /* For now we're just allocating the decoder backend on the heap. */
  51408. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  51409. if (pVorbis == NULL) {
  51410. return MA_OUT_OF_MEMORY;
  51411. }
  51412. result = ma_stbvorbis_init(onRead, onSeek, onTell, pReadSeekTellUserData, pConfig, pAllocationCallbacks, pVorbis);
  51413. if (result != MA_SUCCESS) {
  51414. ma_free(pVorbis, pAllocationCallbacks);
  51415. return result;
  51416. }
  51417. *ppBackend = pVorbis;
  51418. return MA_SUCCESS;
  51419. }
  51420. 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)
  51421. {
  51422. ma_result result;
  51423. ma_stbvorbis* pVorbis;
  51424. (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. */
  51425. /* For now we're just allocating the decoder backend on the heap. */
  51426. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  51427. if (pVorbis == NULL) {
  51428. return MA_OUT_OF_MEMORY;
  51429. }
  51430. result = ma_stbvorbis_init_file(pFilePath, pConfig, pAllocationCallbacks, pVorbis);
  51431. if (result != MA_SUCCESS) {
  51432. ma_free(pVorbis, pAllocationCallbacks);
  51433. return result;
  51434. }
  51435. *ppBackend = pVorbis;
  51436. return MA_SUCCESS;
  51437. }
  51438. 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)
  51439. {
  51440. ma_result result;
  51441. ma_stbvorbis* pVorbis;
  51442. (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. */
  51443. /* For now we're just allocating the decoder backend on the heap. */
  51444. pVorbis = (ma_stbvorbis*)ma_malloc(sizeof(*pVorbis), pAllocationCallbacks);
  51445. if (pVorbis == NULL) {
  51446. return MA_OUT_OF_MEMORY;
  51447. }
  51448. result = ma_stbvorbis_init_memory(pData, dataSize, pConfig, pAllocationCallbacks, pVorbis);
  51449. if (result != MA_SUCCESS) {
  51450. ma_free(pVorbis, pAllocationCallbacks);
  51451. return result;
  51452. }
  51453. *ppBackend = pVorbis;
  51454. return MA_SUCCESS;
  51455. }
  51456. static void ma_decoding_backend_uninit__stbvorbis(void* pUserData, ma_data_source* pBackend, const ma_allocation_callbacks* pAllocationCallbacks)
  51457. {
  51458. ma_stbvorbis* pVorbis = (ma_stbvorbis*)pBackend;
  51459. (void)pUserData;
  51460. ma_stbvorbis_uninit(pVorbis, pAllocationCallbacks);
  51461. ma_free(pVorbis, pAllocationCallbacks);
  51462. }
  51463. static ma_decoding_backend_vtable g_ma_decoding_backend_vtable_stbvorbis =
  51464. {
  51465. ma_decoding_backend_init__stbvorbis,
  51466. ma_decoding_backend_init_file__stbvorbis,
  51467. NULL, /* onInitFileW() */
  51468. ma_decoding_backend_init_memory__stbvorbis,
  51469. ma_decoding_backend_uninit__stbvorbis
  51470. };
  51471. static ma_result ma_decoder_init_vorbis__internal(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51472. {
  51473. return ma_decoder_init_from_vtable(&g_ma_decoding_backend_vtable_stbvorbis, NULL, pConfig, pDecoder);
  51474. }
  51475. #endif /* STB_VORBIS_INCLUDE_STB_VORBIS_H */
  51476. static ma_result ma_decoder__init_allocation_callbacks(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51477. {
  51478. MA_ASSERT(pDecoder != NULL);
  51479. if (pConfig != NULL) {
  51480. return ma_allocation_callbacks_init_copy(&pDecoder->allocationCallbacks, &pConfig->allocationCallbacks);
  51481. } else {
  51482. pDecoder->allocationCallbacks = ma_allocation_callbacks_init_default();
  51483. return MA_SUCCESS;
  51484. }
  51485. }
  51486. static ma_result ma_decoder__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  51487. {
  51488. return ma_decoder_read_pcm_frames((ma_decoder*)pDataSource, pFramesOut, frameCount, pFramesRead);
  51489. }
  51490. static ma_result ma_decoder__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  51491. {
  51492. return ma_decoder_seek_to_pcm_frame((ma_decoder*)pDataSource, frameIndex);
  51493. }
  51494. 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)
  51495. {
  51496. return ma_decoder_get_data_format((ma_decoder*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  51497. }
  51498. static ma_result ma_decoder__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  51499. {
  51500. return ma_decoder_get_cursor_in_pcm_frames((ma_decoder*)pDataSource, pCursor);
  51501. }
  51502. static ma_result ma_decoder__data_source_on_get_length(ma_data_source* pDataSource, ma_uint64* pLength)
  51503. {
  51504. return ma_decoder_get_length_in_pcm_frames((ma_decoder*)pDataSource, pLength);
  51505. }
  51506. static ma_data_source_vtable g_ma_decoder_data_source_vtable =
  51507. {
  51508. ma_decoder__data_source_on_read,
  51509. ma_decoder__data_source_on_seek,
  51510. ma_decoder__data_source_on_get_data_format,
  51511. ma_decoder__data_source_on_get_cursor,
  51512. ma_decoder__data_source_on_get_length,
  51513. NULL, /* onSetLooping */
  51514. 0
  51515. };
  51516. 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)
  51517. {
  51518. ma_result result;
  51519. ma_data_source_config dataSourceConfig;
  51520. MA_ASSERT(pConfig != NULL);
  51521. if (pDecoder == NULL) {
  51522. return MA_INVALID_ARGS;
  51523. }
  51524. MA_ZERO_OBJECT(pDecoder);
  51525. if (onRead == NULL || onSeek == NULL) {
  51526. return MA_INVALID_ARGS;
  51527. }
  51528. dataSourceConfig = ma_data_source_config_init();
  51529. dataSourceConfig.vtable = &g_ma_decoder_data_source_vtable;
  51530. result = ma_data_source_init(&dataSourceConfig, &pDecoder->ds);
  51531. if (result != MA_SUCCESS) {
  51532. return result;
  51533. }
  51534. pDecoder->onRead = onRead;
  51535. pDecoder->onSeek = onSeek;
  51536. pDecoder->onTell = onTell;
  51537. pDecoder->pUserData = pUserData;
  51538. result = ma_decoder__init_allocation_callbacks(pConfig, pDecoder);
  51539. if (result != MA_SUCCESS) {
  51540. ma_data_source_uninit(&pDecoder->ds);
  51541. return result;
  51542. }
  51543. return MA_SUCCESS;
  51544. }
  51545. static ma_result ma_decoder__postinit(const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51546. {
  51547. ma_result result;
  51548. result = ma_decoder__init_data_converter(pDecoder, pConfig);
  51549. /* If we failed post initialization we need to uninitialize the decoder before returning to prevent a memory leak. */
  51550. if (result != MA_SUCCESS) {
  51551. ma_decoder_uninit(pDecoder);
  51552. return result;
  51553. }
  51554. return result;
  51555. }
  51556. 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)
  51557. {
  51558. ma_result result = MA_NO_BACKEND;
  51559. MA_ASSERT(pConfig != NULL);
  51560. MA_ASSERT(pDecoder != NULL);
  51561. /* Silence some warnings in the case that we don't have any decoder backends enabled. */
  51562. (void)onRead;
  51563. (void)onSeek;
  51564. (void)pUserData;
  51565. /* If we've specified a specific encoding type, try that first. */
  51566. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  51567. #ifdef MA_HAS_WAV
  51568. if (pConfig->encodingFormat == ma_encoding_format_wav) {
  51569. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  51570. }
  51571. #endif
  51572. #ifdef MA_HAS_FLAC
  51573. if (pConfig->encodingFormat == ma_encoding_format_flac) {
  51574. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  51575. }
  51576. #endif
  51577. #ifdef MA_HAS_MP3
  51578. if (pConfig->encodingFormat == ma_encoding_format_mp3) {
  51579. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  51580. }
  51581. #endif
  51582. #ifdef MA_HAS_VORBIS
  51583. if (pConfig->encodingFormat == ma_encoding_format_vorbis) {
  51584. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  51585. }
  51586. #endif
  51587. /* If we weren't able to initialize the decoder, seek back to the start to give the next attempts a clean start. */
  51588. if (result != MA_SUCCESS) {
  51589. onSeek(pDecoder, 0, ma_seek_origin_start);
  51590. }
  51591. }
  51592. if (result != MA_SUCCESS) {
  51593. /* Getting here means we couldn't load a specific decoding backend based on the encoding format. */
  51594. /*
  51595. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  51596. implement the same encoding format they take priority over the built-in decoders.
  51597. */
  51598. if (result != MA_SUCCESS) {
  51599. result = ma_decoder_init_custom__internal(pConfig, pDecoder);
  51600. if (result != MA_SUCCESS) {
  51601. onSeek(pDecoder, 0, ma_seek_origin_start);
  51602. }
  51603. }
  51604. /*
  51605. If we get to this point and we still haven't found a decoder, and the caller has requested a
  51606. specific encoding format, there's no hope for it. Abort.
  51607. */
  51608. if (pConfig->encodingFormat != ma_encoding_format_unknown) {
  51609. return MA_NO_BACKEND;
  51610. }
  51611. #ifdef MA_HAS_WAV
  51612. if (result != MA_SUCCESS) {
  51613. result = ma_decoder_init_wav__internal(pConfig, pDecoder);
  51614. if (result != MA_SUCCESS) {
  51615. onSeek(pDecoder, 0, ma_seek_origin_start);
  51616. }
  51617. }
  51618. #endif
  51619. #ifdef MA_HAS_FLAC
  51620. if (result != MA_SUCCESS) {
  51621. result = ma_decoder_init_flac__internal(pConfig, pDecoder);
  51622. if (result != MA_SUCCESS) {
  51623. onSeek(pDecoder, 0, ma_seek_origin_start);
  51624. }
  51625. }
  51626. #endif
  51627. #ifdef MA_HAS_MP3
  51628. if (result != MA_SUCCESS) {
  51629. result = ma_decoder_init_mp3__internal(pConfig, pDecoder);
  51630. if (result != MA_SUCCESS) {
  51631. onSeek(pDecoder, 0, ma_seek_origin_start);
  51632. }
  51633. }
  51634. #endif
  51635. #ifdef MA_HAS_VORBIS
  51636. if (result != MA_SUCCESS) {
  51637. result = ma_decoder_init_vorbis__internal(pConfig, pDecoder);
  51638. if (result != MA_SUCCESS) {
  51639. onSeek(pDecoder, 0, ma_seek_origin_start);
  51640. }
  51641. }
  51642. #endif
  51643. }
  51644. if (result != MA_SUCCESS) {
  51645. return result;
  51646. }
  51647. return ma_decoder__postinit(pConfig, pDecoder);
  51648. }
  51649. 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)
  51650. {
  51651. ma_decoder_config config;
  51652. ma_result result;
  51653. config = ma_decoder_config_init_copy(pConfig);
  51654. result = ma_decoder__preinit(onRead, onSeek, NULL, pUserData, &config, pDecoder);
  51655. if (result != MA_SUCCESS) {
  51656. return result;
  51657. }
  51658. return ma_decoder_init__internal(onRead, onSeek, pUserData, &config, pDecoder);
  51659. }
  51660. static ma_result ma_decoder__on_read_memory(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  51661. {
  51662. size_t bytesRemaining;
  51663. MA_ASSERT(pDecoder->data.memory.dataSize >= pDecoder->data.memory.currentReadPos);
  51664. if (pBytesRead != NULL) {
  51665. *pBytesRead = 0;
  51666. }
  51667. bytesRemaining = pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos;
  51668. if (bytesToRead > bytesRemaining) {
  51669. bytesToRead = bytesRemaining;
  51670. }
  51671. if (bytesRemaining == 0) {
  51672. return MA_AT_END;
  51673. }
  51674. if (bytesToRead > 0) {
  51675. MA_COPY_MEMORY(pBufferOut, pDecoder->data.memory.pData + pDecoder->data.memory.currentReadPos, bytesToRead);
  51676. pDecoder->data.memory.currentReadPos += bytesToRead;
  51677. }
  51678. if (pBytesRead != NULL) {
  51679. *pBytesRead = bytesToRead;
  51680. }
  51681. return MA_SUCCESS;
  51682. }
  51683. static ma_result ma_decoder__on_seek_memory(ma_decoder* pDecoder, ma_int64 byteOffset, ma_seek_origin origin)
  51684. {
  51685. if (byteOffset > 0 && (ma_uint64)byteOffset > MA_SIZE_MAX) {
  51686. return MA_BAD_SEEK;
  51687. }
  51688. if (origin == ma_seek_origin_current) {
  51689. if (byteOffset > 0) {
  51690. if (pDecoder->data.memory.currentReadPos + byteOffset > pDecoder->data.memory.dataSize) {
  51691. byteOffset = (ma_int64)(pDecoder->data.memory.dataSize - pDecoder->data.memory.currentReadPos); /* Trying to seek too far forward. */
  51692. }
  51693. pDecoder->data.memory.currentReadPos += (size_t)byteOffset;
  51694. } else {
  51695. if (pDecoder->data.memory.currentReadPos < (size_t)-byteOffset) {
  51696. byteOffset = -(ma_int64)pDecoder->data.memory.currentReadPos; /* Trying to seek too far backwards. */
  51697. }
  51698. pDecoder->data.memory.currentReadPos -= (size_t)-byteOffset;
  51699. }
  51700. } else {
  51701. if (origin == ma_seek_origin_end) {
  51702. if (byteOffset < 0) {
  51703. byteOffset = -byteOffset;
  51704. }
  51705. if (byteOffset > (ma_int64)pDecoder->data.memory.dataSize) {
  51706. pDecoder->data.memory.currentReadPos = 0; /* Trying to seek too far back. */
  51707. } else {
  51708. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize - (size_t)byteOffset;
  51709. }
  51710. } else {
  51711. if ((size_t)byteOffset <= pDecoder->data.memory.dataSize) {
  51712. pDecoder->data.memory.currentReadPos = (size_t)byteOffset;
  51713. } else {
  51714. pDecoder->data.memory.currentReadPos = pDecoder->data.memory.dataSize; /* Trying to seek too far forward. */
  51715. }
  51716. }
  51717. }
  51718. return MA_SUCCESS;
  51719. }
  51720. static ma_result ma_decoder__on_tell_memory(ma_decoder* pDecoder, ma_int64* pCursor)
  51721. {
  51722. MA_ASSERT(pDecoder != NULL);
  51723. MA_ASSERT(pCursor != NULL);
  51724. *pCursor = (ma_int64)pDecoder->data.memory.currentReadPos;
  51725. return MA_SUCCESS;
  51726. }
  51727. static ma_result ma_decoder__preinit_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51728. {
  51729. ma_result result = ma_decoder__preinit(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, ma_decoder__on_tell_memory, NULL, pConfig, pDecoder);
  51730. if (result != MA_SUCCESS) {
  51731. return result;
  51732. }
  51733. if (pData == NULL || dataSize == 0) {
  51734. return MA_INVALID_ARGS;
  51735. }
  51736. pDecoder->data.memory.pData = (const ma_uint8*)pData;
  51737. pDecoder->data.memory.dataSize = dataSize;
  51738. pDecoder->data.memory.currentReadPos = 0;
  51739. (void)pConfig;
  51740. return MA_SUCCESS;
  51741. }
  51742. MA_API ma_result ma_decoder_init_memory(const void* pData, size_t dataSize, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51743. {
  51744. ma_decoder_config config;
  51745. ma_result result;
  51746. config = ma_decoder_config_init_copy(pConfig); /* Make sure the config is not NULL. */
  51747. result = ma_decoder__preinit_memory(pData, dataSize, &config, pDecoder);
  51748. if (result != MA_SUCCESS) {
  51749. return result;
  51750. }
  51751. return ma_decoder_init__internal(ma_decoder__on_read_memory, ma_decoder__on_seek_memory, NULL, &config, pDecoder);
  51752. }
  51753. #if defined(MA_HAS_WAV) || \
  51754. defined(MA_HAS_MP3) || \
  51755. defined(MA_HAS_FLAC) || \
  51756. defined(MA_HAS_VORBIS) || \
  51757. defined(MA_HAS_OPUS)
  51758. #define MA_HAS_PATH_API
  51759. #endif
  51760. #if defined(MA_HAS_PATH_API)
  51761. static const char* ma_path_file_name(const char* path)
  51762. {
  51763. const char* fileName;
  51764. if (path == NULL) {
  51765. return NULL;
  51766. }
  51767. fileName = path;
  51768. /* We just loop through the path until we find the last slash. */
  51769. while (path[0] != '\0') {
  51770. if (path[0] == '/' || path[0] == '\\') {
  51771. fileName = path;
  51772. }
  51773. path += 1;
  51774. }
  51775. /* At this point the file name is sitting on a slash, so just move forward. */
  51776. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  51777. fileName += 1;
  51778. }
  51779. return fileName;
  51780. }
  51781. static const wchar_t* ma_path_file_name_w(const wchar_t* path)
  51782. {
  51783. const wchar_t* fileName;
  51784. if (path == NULL) {
  51785. return NULL;
  51786. }
  51787. fileName = path;
  51788. /* We just loop through the path until we find the last slash. */
  51789. while (path[0] != '\0') {
  51790. if (path[0] == '/' || path[0] == '\\') {
  51791. fileName = path;
  51792. }
  51793. path += 1;
  51794. }
  51795. /* At this point the file name is sitting on a slash, so just move forward. */
  51796. while (fileName[0] != '\0' && (fileName[0] == '/' || fileName[0] == '\\')) {
  51797. fileName += 1;
  51798. }
  51799. return fileName;
  51800. }
  51801. static const char* ma_path_extension(const char* path)
  51802. {
  51803. const char* extension;
  51804. const char* lastOccurance;
  51805. if (path == NULL) {
  51806. path = "";
  51807. }
  51808. extension = ma_path_file_name(path);
  51809. lastOccurance = NULL;
  51810. /* Just find the last '.' and return. */
  51811. while (extension[0] != '\0') {
  51812. if (extension[0] == '.') {
  51813. extension += 1;
  51814. lastOccurance = extension;
  51815. }
  51816. extension += 1;
  51817. }
  51818. return (lastOccurance != NULL) ? lastOccurance : extension;
  51819. }
  51820. static const wchar_t* ma_path_extension_w(const wchar_t* path)
  51821. {
  51822. const wchar_t* extension;
  51823. const wchar_t* lastOccurance;
  51824. if (path == NULL) {
  51825. path = L"";
  51826. }
  51827. extension = ma_path_file_name_w(path);
  51828. lastOccurance = NULL;
  51829. /* Just find the last '.' and return. */
  51830. while (extension[0] != '\0') {
  51831. if (extension[0] == '.') {
  51832. extension += 1;
  51833. lastOccurance = extension;
  51834. }
  51835. extension += 1;
  51836. }
  51837. return (lastOccurance != NULL) ? lastOccurance : extension;
  51838. }
  51839. static ma_bool32 ma_path_extension_equal(const char* path, const char* extension)
  51840. {
  51841. const char* ext1;
  51842. const char* ext2;
  51843. if (path == NULL || extension == NULL) {
  51844. return MA_FALSE;
  51845. }
  51846. ext1 = extension;
  51847. ext2 = ma_path_extension(path);
  51848. #if defined(_MSC_VER) || defined(__DMC__)
  51849. return _stricmp(ext1, ext2) == 0;
  51850. #else
  51851. return strcasecmp(ext1, ext2) == 0;
  51852. #endif
  51853. }
  51854. static ma_bool32 ma_path_extension_equal_w(const wchar_t* path, const wchar_t* extension)
  51855. {
  51856. const wchar_t* ext1;
  51857. const wchar_t* ext2;
  51858. if (path == NULL || extension == NULL) {
  51859. return MA_FALSE;
  51860. }
  51861. ext1 = extension;
  51862. ext2 = ma_path_extension_w(path);
  51863. #if defined(_MSC_VER) || defined(__WATCOMC__) || defined(__DMC__)
  51864. return _wcsicmp(ext1, ext2) == 0;
  51865. #else
  51866. /*
  51867. I'm not aware of a wide character version of strcasecmp(). I'm therefore converting the extensions to multibyte strings and comparing those. This
  51868. isn't the most efficient way to do it, but it should work OK.
  51869. */
  51870. {
  51871. char ext1MB[4096];
  51872. char ext2MB[4096];
  51873. const wchar_t* pext1 = ext1;
  51874. const wchar_t* pext2 = ext2;
  51875. mbstate_t mbs1;
  51876. mbstate_t mbs2;
  51877. MA_ZERO_OBJECT(&mbs1);
  51878. MA_ZERO_OBJECT(&mbs2);
  51879. if (wcsrtombs(ext1MB, &pext1, sizeof(ext1MB), &mbs1) == (size_t)-1) {
  51880. return MA_FALSE;
  51881. }
  51882. if (wcsrtombs(ext2MB, &pext2, sizeof(ext2MB), &mbs2) == (size_t)-1) {
  51883. return MA_FALSE;
  51884. }
  51885. return strcasecmp(ext1MB, ext2MB) == 0;
  51886. }
  51887. #endif
  51888. }
  51889. #endif /* MA_HAS_PATH_API */
  51890. static ma_result ma_decoder__on_read_vfs(ma_decoder* pDecoder, void* pBufferOut, size_t bytesToRead, size_t* pBytesRead)
  51891. {
  51892. MA_ASSERT(pDecoder != NULL);
  51893. MA_ASSERT(pBufferOut != NULL);
  51894. return ma_vfs_or_default_read(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pBufferOut, bytesToRead, pBytesRead);
  51895. }
  51896. static ma_result ma_decoder__on_seek_vfs(ma_decoder* pDecoder, ma_int64 offset, ma_seek_origin origin)
  51897. {
  51898. MA_ASSERT(pDecoder != NULL);
  51899. return ma_vfs_or_default_seek(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, offset, origin);
  51900. }
  51901. static ma_result ma_decoder__on_tell_vfs(ma_decoder* pDecoder, ma_int64* pCursor)
  51902. {
  51903. MA_ASSERT(pDecoder != NULL);
  51904. return ma_vfs_or_default_tell(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file, pCursor);
  51905. }
  51906. static ma_result ma_decoder__preinit_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51907. {
  51908. ma_result result;
  51909. ma_vfs_file file;
  51910. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  51911. if (result != MA_SUCCESS) {
  51912. return result;
  51913. }
  51914. if (pFilePath == NULL || pFilePath[0] == '\0') {
  51915. return MA_INVALID_ARGS;
  51916. }
  51917. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  51918. if (result != MA_SUCCESS) {
  51919. return result;
  51920. }
  51921. pDecoder->data.vfs.pVFS = pVFS;
  51922. pDecoder->data.vfs.file = file;
  51923. return MA_SUCCESS;
  51924. }
  51925. MA_API ma_result ma_decoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  51926. {
  51927. ma_result result;
  51928. ma_decoder_config config;
  51929. config = ma_decoder_config_init_copy(pConfig);
  51930. result = ma_decoder__preinit_vfs(pVFS, pFilePath, &config, pDecoder);
  51931. if (result != MA_SUCCESS) {
  51932. return result;
  51933. }
  51934. result = MA_NO_BACKEND;
  51935. if (config.encodingFormat != ma_encoding_format_unknown) {
  51936. #ifdef MA_HAS_WAV
  51937. if (config.encodingFormat == ma_encoding_format_wav) {
  51938. result = ma_decoder_init_wav__internal(&config, pDecoder);
  51939. }
  51940. #endif
  51941. #ifdef MA_HAS_FLAC
  51942. if (config.encodingFormat == ma_encoding_format_flac) {
  51943. result = ma_decoder_init_flac__internal(&config, pDecoder);
  51944. }
  51945. #endif
  51946. #ifdef MA_HAS_MP3
  51947. if (config.encodingFormat == ma_encoding_format_mp3) {
  51948. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  51949. }
  51950. #endif
  51951. #ifdef MA_HAS_VORBIS
  51952. if (config.encodingFormat == ma_encoding_format_vorbis) {
  51953. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  51954. }
  51955. #endif
  51956. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  51957. if (result != MA_SUCCESS) {
  51958. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  51959. }
  51960. }
  51961. if (result != MA_SUCCESS) {
  51962. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  51963. /*
  51964. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  51965. implement the same encoding format they take priority over the built-in decoders.
  51966. */
  51967. if (result != MA_SUCCESS) {
  51968. result = ma_decoder_init_custom__internal(&config, pDecoder);
  51969. if (result != MA_SUCCESS) {
  51970. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  51971. }
  51972. }
  51973. /*
  51974. If we get to this point and we still haven't found a decoder, and the caller has requested a
  51975. specific encoding format, there's no hope for it. Abort.
  51976. */
  51977. if (config.encodingFormat != ma_encoding_format_unknown) {
  51978. return MA_NO_BACKEND;
  51979. }
  51980. #ifdef MA_HAS_WAV
  51981. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "wav")) {
  51982. result = ma_decoder_init_wav__internal(&config, pDecoder);
  51983. if (result != MA_SUCCESS) {
  51984. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  51985. }
  51986. }
  51987. #endif
  51988. #ifdef MA_HAS_FLAC
  51989. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "flac")) {
  51990. result = ma_decoder_init_flac__internal(&config, pDecoder);
  51991. if (result != MA_SUCCESS) {
  51992. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  51993. }
  51994. }
  51995. #endif
  51996. #ifdef MA_HAS_MP3
  51997. if (result != MA_SUCCESS && ma_path_extension_equal(pFilePath, "mp3")) {
  51998. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  51999. if (result != MA_SUCCESS) {
  52000. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52001. }
  52002. }
  52003. #endif
  52004. }
  52005. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  52006. if (result != MA_SUCCESS) {
  52007. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  52008. } else {
  52009. result = ma_decoder__postinit(&config, pDecoder);
  52010. }
  52011. if (result != MA_SUCCESS) {
  52012. 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. */
  52013. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  52014. }
  52015. return result;
  52016. }
  52017. return MA_SUCCESS;
  52018. }
  52019. static ma_result ma_decoder__preinit_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52020. {
  52021. ma_result result;
  52022. ma_vfs_file file;
  52023. result = ma_decoder__preinit(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, ma_decoder__on_tell_vfs, NULL, pConfig, pDecoder);
  52024. if (result != MA_SUCCESS) {
  52025. return result;
  52026. }
  52027. if (pFilePath == NULL || pFilePath[0] == '\0') {
  52028. return MA_INVALID_ARGS;
  52029. }
  52030. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_READ, &file);
  52031. if (result != MA_SUCCESS) {
  52032. return result;
  52033. }
  52034. pDecoder->data.vfs.pVFS = pVFS;
  52035. pDecoder->data.vfs.file = file;
  52036. return MA_SUCCESS;
  52037. }
  52038. MA_API ma_result ma_decoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52039. {
  52040. ma_result result;
  52041. ma_decoder_config config;
  52042. config = ma_decoder_config_init_copy(pConfig);
  52043. result = ma_decoder__preinit_vfs_w(pVFS, pFilePath, &config, pDecoder);
  52044. if (result != MA_SUCCESS) {
  52045. return result;
  52046. }
  52047. result = MA_NO_BACKEND;
  52048. if (config.encodingFormat != ma_encoding_format_unknown) {
  52049. #ifdef MA_HAS_WAV
  52050. if (config.encodingFormat == ma_encoding_format_wav) {
  52051. result = ma_decoder_init_wav__internal(&config, pDecoder);
  52052. }
  52053. #endif
  52054. #ifdef MA_HAS_FLAC
  52055. if (config.encodingFormat == ma_encoding_format_flac) {
  52056. result = ma_decoder_init_flac__internal(&config, pDecoder);
  52057. }
  52058. #endif
  52059. #ifdef MA_HAS_MP3
  52060. if (config.encodingFormat == ma_encoding_format_mp3) {
  52061. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  52062. }
  52063. #endif
  52064. #ifdef MA_HAS_VORBIS
  52065. if (config.encodingFormat == ma_encoding_format_vorbis) {
  52066. result = ma_decoder_init_vorbis__internal(&config, pDecoder);
  52067. }
  52068. #endif
  52069. /* Make sure we seek back to the start if we didn't initialize a decoder successfully so the next attempts have a fresh start. */
  52070. if (result != MA_SUCCESS) {
  52071. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52072. }
  52073. }
  52074. if (result != MA_SUCCESS) {
  52075. /* Getting here means we weren't able to initialize a decoder of a specific encoding format. */
  52076. /*
  52077. We use trial and error to open a decoder. We prioritize custom decoders so that if they
  52078. implement the same encoding format they take priority over the built-in decoders.
  52079. */
  52080. if (result != MA_SUCCESS) {
  52081. result = ma_decoder_init_custom__internal(&config, pDecoder);
  52082. if (result != MA_SUCCESS) {
  52083. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52084. }
  52085. }
  52086. /*
  52087. If we get to this point and we still haven't found a decoder, and the caller has requested a
  52088. specific encoding format, there's no hope for it. Abort.
  52089. */
  52090. if (config.encodingFormat != ma_encoding_format_unknown) {
  52091. return MA_NO_BACKEND;
  52092. }
  52093. #ifdef MA_HAS_WAV
  52094. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"wav")) {
  52095. result = ma_decoder_init_wav__internal(&config, pDecoder);
  52096. if (result != MA_SUCCESS) {
  52097. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52098. }
  52099. }
  52100. #endif
  52101. #ifdef MA_HAS_FLAC
  52102. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"flac")) {
  52103. result = ma_decoder_init_flac__internal(&config, pDecoder);
  52104. if (result != MA_SUCCESS) {
  52105. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52106. }
  52107. }
  52108. #endif
  52109. #ifdef MA_HAS_MP3
  52110. if (result != MA_SUCCESS && ma_path_extension_equal_w(pFilePath, L"mp3")) {
  52111. result = ma_decoder_init_mp3__internal(&config, pDecoder);
  52112. if (result != MA_SUCCESS) {
  52113. ma_decoder__on_seek_vfs(pDecoder, 0, ma_seek_origin_start);
  52114. }
  52115. }
  52116. #endif
  52117. }
  52118. /* If we still haven't got a result just use trial and error. Otherwise we can finish up. */
  52119. if (result != MA_SUCCESS) {
  52120. result = ma_decoder_init__internal(ma_decoder__on_read_vfs, ma_decoder__on_seek_vfs, NULL, &config, pDecoder);
  52121. } else {
  52122. result = ma_decoder__postinit(&config, pDecoder);
  52123. }
  52124. if (result != MA_SUCCESS) {
  52125. ma_vfs_or_default_close(pVFS, pDecoder->data.vfs.file);
  52126. return result;
  52127. }
  52128. return MA_SUCCESS;
  52129. }
  52130. MA_API ma_result ma_decoder_init_file(const char* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52131. {
  52132. return ma_decoder_init_vfs(NULL, pFilePath, pConfig, pDecoder);
  52133. }
  52134. MA_API ma_result ma_decoder_init_file_w(const wchar_t* pFilePath, const ma_decoder_config* pConfig, ma_decoder* pDecoder)
  52135. {
  52136. return ma_decoder_init_vfs_w(NULL, pFilePath, pConfig, pDecoder);
  52137. }
  52138. MA_API ma_result ma_decoder_uninit(ma_decoder* pDecoder)
  52139. {
  52140. if (pDecoder == NULL) {
  52141. return MA_INVALID_ARGS;
  52142. }
  52143. if (pDecoder->pBackend != NULL) {
  52144. if (pDecoder->pBackendVTable != NULL && pDecoder->pBackendVTable->onUninit != NULL) {
  52145. pDecoder->pBackendVTable->onUninit(pDecoder->pBackendUserData, pDecoder->pBackend, &pDecoder->allocationCallbacks);
  52146. }
  52147. }
  52148. if (pDecoder->onRead == ma_decoder__on_read_vfs) {
  52149. ma_vfs_or_default_close(pDecoder->data.vfs.pVFS, pDecoder->data.vfs.file);
  52150. pDecoder->data.vfs.file = NULL;
  52151. }
  52152. ma_data_converter_uninit(&pDecoder->converter, &pDecoder->allocationCallbacks);
  52153. ma_data_source_uninit(&pDecoder->ds);
  52154. if (pDecoder->pInputCache != NULL) {
  52155. ma_free(pDecoder->pInputCache, &pDecoder->allocationCallbacks);
  52156. }
  52157. return MA_SUCCESS;
  52158. }
  52159. MA_API ma_result ma_decoder_read_pcm_frames(ma_decoder* pDecoder, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52160. {
  52161. ma_result result = MA_SUCCESS;
  52162. ma_uint64 totalFramesReadOut;
  52163. void* pRunningFramesOut;
  52164. if (pFramesRead != NULL) {
  52165. *pFramesRead = 0; /* Safety. */
  52166. }
  52167. if (frameCount == 0) {
  52168. return MA_INVALID_ARGS;
  52169. }
  52170. if (pDecoder == NULL) {
  52171. return MA_INVALID_ARGS;
  52172. }
  52173. if (pDecoder->pBackend == NULL) {
  52174. return MA_INVALID_OPERATION;
  52175. }
  52176. /* Fast path. */
  52177. if (pDecoder->converter.isPassthrough) {
  52178. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pFramesOut, frameCount, &totalFramesReadOut);
  52179. } else {
  52180. /*
  52181. 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
  52182. need to run through each sample because we need to ensure it's internal cache is updated.
  52183. */
  52184. if (pFramesOut == NULL && pDecoder->converter.hasResampler == MA_FALSE) {
  52185. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, NULL, frameCount, &totalFramesReadOut);
  52186. } else {
  52187. /* Slow path. Need to run everything through the data converter. */
  52188. ma_format internalFormat;
  52189. ma_uint32 internalChannels;
  52190. totalFramesReadOut = 0;
  52191. pRunningFramesOut = pFramesOut;
  52192. result = ma_data_source_get_data_format(pDecoder->pBackend, &internalFormat, &internalChannels, NULL, NULL, 0);
  52193. if (result != MA_SUCCESS) {
  52194. return result; /* Failed to retrieve the internal format and channel count. */
  52195. }
  52196. /*
  52197. We run a different path depending on whether or not we are using a heap-allocated
  52198. intermediary buffer or not. If the data converter does not support the calculation of
  52199. the required number of input frames, we'll use the heap-allocated path. Otherwise we'll
  52200. use the stack-allocated path.
  52201. */
  52202. if (pDecoder->pInputCache != NULL) {
  52203. /* We don't have a way of determining the required number of input frames, so need to persistently store input data in a cache. */
  52204. while (totalFramesReadOut < frameCount) {
  52205. ma_uint64 framesToReadThisIterationIn;
  52206. ma_uint64 framesToReadThisIterationOut;
  52207. /* If there's any data available in the cache, that needs to get processed first. */
  52208. if (pDecoder->inputCacheRemaining > 0) {
  52209. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  52210. framesToReadThisIterationIn = framesToReadThisIterationOut;
  52211. if (framesToReadThisIterationIn > pDecoder->inputCacheRemaining) {
  52212. framesToReadThisIterationIn = pDecoder->inputCacheRemaining;
  52213. }
  52214. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, ma_offset_pcm_frames_ptr(pDecoder->pInputCache, pDecoder->inputCacheConsumed, internalFormat, internalChannels), &framesToReadThisIterationIn, pRunningFramesOut, &framesToReadThisIterationOut);
  52215. if (result != MA_SUCCESS) {
  52216. break;
  52217. }
  52218. pDecoder->inputCacheConsumed += framesToReadThisIterationIn;
  52219. pDecoder->inputCacheRemaining -= framesToReadThisIterationIn;
  52220. totalFramesReadOut += framesToReadThisIterationOut;
  52221. if (pRunningFramesOut != NULL) {
  52222. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesToReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  52223. }
  52224. if (framesToReadThisIterationIn == 0 && framesToReadThisIterationOut == 0) {
  52225. break; /* We're done. */
  52226. }
  52227. }
  52228. /* Getting here means there's no data in the cache and we need to fill it up from the data source. */
  52229. if (pDecoder->inputCacheRemaining == 0) {
  52230. pDecoder->inputCacheConsumed = 0;
  52231. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pDecoder->pInputCache, pDecoder->inputCacheCap, &pDecoder->inputCacheRemaining);
  52232. if (result != MA_SUCCESS) {
  52233. break;
  52234. }
  52235. }
  52236. }
  52237. } else {
  52238. /* We have a way of determining the required number of input frames so just use the stack. */
  52239. while (totalFramesReadOut < frameCount) {
  52240. ma_uint8 pIntermediaryBuffer[MA_DATA_CONVERTER_STACK_BUFFER_SIZE]; /* In internal format. */
  52241. ma_uint64 intermediaryBufferCap = sizeof(pIntermediaryBuffer) / ma_get_bytes_per_frame(internalFormat, internalChannels);
  52242. ma_uint64 framesToReadThisIterationIn;
  52243. ma_uint64 framesReadThisIterationIn;
  52244. ma_uint64 framesToReadThisIterationOut;
  52245. ma_uint64 framesReadThisIterationOut;
  52246. ma_uint64 requiredInputFrameCount;
  52247. framesToReadThisIterationOut = (frameCount - totalFramesReadOut);
  52248. framesToReadThisIterationIn = framesToReadThisIterationOut;
  52249. if (framesToReadThisIterationIn > intermediaryBufferCap) {
  52250. framesToReadThisIterationIn = intermediaryBufferCap;
  52251. }
  52252. ma_data_converter_get_required_input_frame_count(&pDecoder->converter, framesToReadThisIterationOut, &requiredInputFrameCount);
  52253. if (framesToReadThisIterationIn > requiredInputFrameCount) {
  52254. framesToReadThisIterationIn = requiredInputFrameCount;
  52255. }
  52256. if (requiredInputFrameCount > 0) {
  52257. result = ma_data_source_read_pcm_frames(pDecoder->pBackend, pIntermediaryBuffer, framesToReadThisIterationIn, &framesReadThisIterationIn);
  52258. } else {
  52259. framesReadThisIterationIn = 0;
  52260. }
  52261. /*
  52262. 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
  52263. input frames, we still want to try processing frames because there may some output frames generated from cached input data.
  52264. */
  52265. framesReadThisIterationOut = framesToReadThisIterationOut;
  52266. result = ma_data_converter_process_pcm_frames(&pDecoder->converter, pIntermediaryBuffer, &framesReadThisIterationIn, pRunningFramesOut, &framesReadThisIterationOut);
  52267. if (result != MA_SUCCESS) {
  52268. break;
  52269. }
  52270. totalFramesReadOut += framesReadThisIterationOut;
  52271. if (pRunningFramesOut != NULL) {
  52272. pRunningFramesOut = ma_offset_ptr(pRunningFramesOut, framesReadThisIterationOut * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels));
  52273. }
  52274. if (framesReadThisIterationIn == 0 && framesReadThisIterationOut == 0) {
  52275. break; /* We're done. */
  52276. }
  52277. }
  52278. }
  52279. }
  52280. }
  52281. pDecoder->readPointerInPCMFrames += totalFramesReadOut;
  52282. if (pFramesRead != NULL) {
  52283. *pFramesRead = totalFramesReadOut;
  52284. }
  52285. if (result == MA_SUCCESS && totalFramesReadOut == 0) {
  52286. result = MA_AT_END;
  52287. }
  52288. return result;
  52289. }
  52290. MA_API ma_result ma_decoder_seek_to_pcm_frame(ma_decoder* pDecoder, ma_uint64 frameIndex)
  52291. {
  52292. if (pDecoder == NULL) {
  52293. return MA_INVALID_ARGS;
  52294. }
  52295. if (pDecoder->pBackend != NULL) {
  52296. ma_result result;
  52297. ma_uint64 internalFrameIndex;
  52298. ma_uint32 internalSampleRate;
  52299. ma_uint64 currentFrameIndex;
  52300. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  52301. if (result != MA_SUCCESS) {
  52302. return result; /* Failed to retrieve the internal sample rate. */
  52303. }
  52304. if (internalSampleRate == pDecoder->outputSampleRate) {
  52305. internalFrameIndex = frameIndex;
  52306. } else {
  52307. internalFrameIndex = ma_calculate_frame_count_after_resampling(internalSampleRate, pDecoder->outputSampleRate, frameIndex);
  52308. }
  52309. /* Only seek if we're requesting a different frame to what we're currently sitting on. */
  52310. ma_data_source_get_cursor_in_pcm_frames(pDecoder->pBackend, &currentFrameIndex);
  52311. if (currentFrameIndex != internalFrameIndex) {
  52312. result = ma_data_source_seek_to_pcm_frame(pDecoder->pBackend, internalFrameIndex);
  52313. if (result == MA_SUCCESS) {
  52314. pDecoder->readPointerInPCMFrames = frameIndex;
  52315. }
  52316. /* Reset the data converter so that any cached data in the resampler is cleared. */
  52317. ma_data_converter_reset(&pDecoder->converter);
  52318. }
  52319. return result;
  52320. }
  52321. /* Should never get here, but if we do it means onSeekToPCMFrame was not set by the backend. */
  52322. return MA_INVALID_ARGS;
  52323. }
  52324. 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)
  52325. {
  52326. if (pDecoder == NULL) {
  52327. return MA_INVALID_ARGS;
  52328. }
  52329. if (pFormat != NULL) {
  52330. *pFormat = pDecoder->outputFormat;
  52331. }
  52332. if (pChannels != NULL) {
  52333. *pChannels = pDecoder->outputChannels;
  52334. }
  52335. if (pSampleRate != NULL) {
  52336. *pSampleRate = pDecoder->outputSampleRate;
  52337. }
  52338. if (pChannelMap != NULL) {
  52339. ma_data_converter_get_output_channel_map(&pDecoder->converter, pChannelMap, channelMapCap);
  52340. }
  52341. return MA_SUCCESS;
  52342. }
  52343. MA_API ma_result ma_decoder_get_cursor_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pCursor)
  52344. {
  52345. if (pCursor == NULL) {
  52346. return MA_INVALID_ARGS;
  52347. }
  52348. *pCursor = 0;
  52349. if (pDecoder == NULL) {
  52350. return MA_INVALID_ARGS;
  52351. }
  52352. *pCursor = pDecoder->readPointerInPCMFrames;
  52353. return MA_SUCCESS;
  52354. }
  52355. MA_API ma_result ma_decoder_get_length_in_pcm_frames(ma_decoder* pDecoder, ma_uint64* pLength)
  52356. {
  52357. if (pLength == NULL) {
  52358. return MA_INVALID_ARGS;
  52359. }
  52360. *pLength = 0;
  52361. if (pDecoder == NULL) {
  52362. return MA_INVALID_ARGS;
  52363. }
  52364. if (pDecoder->pBackend != NULL) {
  52365. ma_result result;
  52366. ma_uint64 internalLengthInPCMFrames;
  52367. ma_uint32 internalSampleRate;
  52368. result = ma_data_source_get_length_in_pcm_frames(pDecoder->pBackend, &internalLengthInPCMFrames);
  52369. if (result != MA_SUCCESS) {
  52370. return result; /* Failed to retrieve the internal length. */
  52371. }
  52372. result = ma_data_source_get_data_format(pDecoder->pBackend, NULL, NULL, &internalSampleRate, NULL, 0);
  52373. if (result != MA_SUCCESS) {
  52374. return result; /* Failed to retrieve the internal sample rate. */
  52375. }
  52376. if (internalSampleRate == pDecoder->outputSampleRate) {
  52377. *pLength = internalLengthInPCMFrames;
  52378. } else {
  52379. *pLength = ma_calculate_frame_count_after_resampling(pDecoder->outputSampleRate, internalSampleRate, internalLengthInPCMFrames);
  52380. }
  52381. return MA_SUCCESS;
  52382. } else {
  52383. return MA_NO_BACKEND;
  52384. }
  52385. }
  52386. MA_API ma_result ma_decoder_get_available_frames(ma_decoder* pDecoder, ma_uint64* pAvailableFrames)
  52387. {
  52388. ma_result result;
  52389. ma_uint64 totalFrameCount;
  52390. if (pAvailableFrames == NULL) {
  52391. return MA_INVALID_ARGS;
  52392. }
  52393. *pAvailableFrames = 0;
  52394. if (pDecoder == NULL) {
  52395. return MA_INVALID_ARGS;
  52396. }
  52397. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  52398. if (result != MA_SUCCESS) {
  52399. return result;
  52400. }
  52401. if (totalFrameCount <= pDecoder->readPointerInPCMFrames) {
  52402. *pAvailableFrames = 0;
  52403. } else {
  52404. *pAvailableFrames = totalFrameCount - pDecoder->readPointerInPCMFrames;
  52405. }
  52406. return MA_SUCCESS;
  52407. }
  52408. static ma_result ma_decoder__full_decode_and_uninit(ma_decoder* pDecoder, ma_decoder_config* pConfigOut, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  52409. {
  52410. ma_result result;
  52411. ma_uint64 totalFrameCount;
  52412. ma_uint64 bpf;
  52413. ma_uint64 dataCapInFrames;
  52414. void* pPCMFramesOut;
  52415. MA_ASSERT(pDecoder != NULL);
  52416. totalFrameCount = 0;
  52417. bpf = ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  52418. /* The frame count is unknown until we try reading. Thus, we just run in a loop. */
  52419. dataCapInFrames = 0;
  52420. pPCMFramesOut = NULL;
  52421. for (;;) {
  52422. ma_uint64 frameCountToTryReading;
  52423. ma_uint64 framesJustRead;
  52424. /* Make room if there's not enough. */
  52425. if (totalFrameCount == dataCapInFrames) {
  52426. void* pNewPCMFramesOut;
  52427. ma_uint64 newDataCapInFrames = dataCapInFrames*2;
  52428. if (newDataCapInFrames == 0) {
  52429. newDataCapInFrames = 4096;
  52430. }
  52431. if ((newDataCapInFrames * bpf) > MA_SIZE_MAX) {
  52432. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  52433. return MA_TOO_BIG;
  52434. }
  52435. pNewPCMFramesOut = (void*)ma_realloc(pPCMFramesOut, (size_t)(newDataCapInFrames * bpf), &pDecoder->allocationCallbacks);
  52436. if (pNewPCMFramesOut == NULL) {
  52437. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  52438. return MA_OUT_OF_MEMORY;
  52439. }
  52440. dataCapInFrames = newDataCapInFrames;
  52441. pPCMFramesOut = pNewPCMFramesOut;
  52442. }
  52443. frameCountToTryReading = dataCapInFrames - totalFrameCount;
  52444. MA_ASSERT(frameCountToTryReading > 0);
  52445. result = ma_decoder_read_pcm_frames(pDecoder, (ma_uint8*)pPCMFramesOut + (totalFrameCount * bpf), frameCountToTryReading, &framesJustRead);
  52446. totalFrameCount += framesJustRead;
  52447. if (result != MA_SUCCESS) {
  52448. break;
  52449. }
  52450. if (framesJustRead < frameCountToTryReading) {
  52451. break;
  52452. }
  52453. }
  52454. if (pConfigOut != NULL) {
  52455. pConfigOut->format = pDecoder->outputFormat;
  52456. pConfigOut->channels = pDecoder->outputChannels;
  52457. pConfigOut->sampleRate = pDecoder->outputSampleRate;
  52458. }
  52459. if (ppPCMFramesOut != NULL) {
  52460. *ppPCMFramesOut = pPCMFramesOut;
  52461. } else {
  52462. ma_free(pPCMFramesOut, &pDecoder->allocationCallbacks);
  52463. }
  52464. if (pFrameCountOut != NULL) {
  52465. *pFrameCountOut = totalFrameCount;
  52466. }
  52467. ma_decoder_uninit(pDecoder);
  52468. return MA_SUCCESS;
  52469. }
  52470. MA_API ma_result ma_decode_from_vfs(ma_vfs* pVFS, const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  52471. {
  52472. ma_result result;
  52473. ma_decoder_config config;
  52474. ma_decoder decoder;
  52475. if (pFrameCountOut != NULL) {
  52476. *pFrameCountOut = 0;
  52477. }
  52478. if (ppPCMFramesOut != NULL) {
  52479. *ppPCMFramesOut = NULL;
  52480. }
  52481. config = ma_decoder_config_init_copy(pConfig);
  52482. result = ma_decoder_init_vfs(pVFS, pFilePath, &config, &decoder);
  52483. if (result != MA_SUCCESS) {
  52484. return result;
  52485. }
  52486. result = ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  52487. return result;
  52488. }
  52489. MA_API ma_result ma_decode_file(const char* pFilePath, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  52490. {
  52491. return ma_decode_from_vfs(NULL, pFilePath, pConfig, pFrameCountOut, ppPCMFramesOut);
  52492. }
  52493. MA_API ma_result ma_decode_memory(const void* pData, size_t dataSize, ma_decoder_config* pConfig, ma_uint64* pFrameCountOut, void** ppPCMFramesOut)
  52494. {
  52495. ma_decoder_config config;
  52496. ma_decoder decoder;
  52497. ma_result result;
  52498. if (pFrameCountOut != NULL) {
  52499. *pFrameCountOut = 0;
  52500. }
  52501. if (ppPCMFramesOut != NULL) {
  52502. *ppPCMFramesOut = NULL;
  52503. }
  52504. if (pData == NULL || dataSize == 0) {
  52505. return MA_INVALID_ARGS;
  52506. }
  52507. config = ma_decoder_config_init_copy(pConfig);
  52508. result = ma_decoder_init_memory(pData, dataSize, &config, &decoder);
  52509. if (result != MA_SUCCESS) {
  52510. return result;
  52511. }
  52512. return ma_decoder__full_decode_and_uninit(&decoder, pConfig, pFrameCountOut, ppPCMFramesOut);
  52513. }
  52514. #endif /* MA_NO_DECODING */
  52515. #ifndef MA_NO_ENCODING
  52516. #if defined(MA_HAS_WAV)
  52517. static size_t ma_encoder__internal_on_write_wav(void* pUserData, const void* pData, size_t bytesToWrite)
  52518. {
  52519. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  52520. size_t bytesWritten = 0;
  52521. MA_ASSERT(pEncoder != NULL);
  52522. pEncoder->onWrite(pEncoder, pData, bytesToWrite, &bytesWritten);
  52523. return bytesWritten;
  52524. }
  52525. static drwav_bool32 ma_encoder__internal_on_seek_wav(void* pUserData, int offset, drwav_seek_origin origin)
  52526. {
  52527. ma_encoder* pEncoder = (ma_encoder*)pUserData;
  52528. ma_result result;
  52529. MA_ASSERT(pEncoder != NULL);
  52530. result = pEncoder->onSeek(pEncoder, offset, (origin == drwav_seek_origin_start) ? ma_seek_origin_start : ma_seek_origin_current);
  52531. if (result != MA_SUCCESS) {
  52532. return DRWAV_FALSE;
  52533. } else {
  52534. return DRWAV_TRUE;
  52535. }
  52536. }
  52537. static ma_result ma_encoder__on_init_wav(ma_encoder* pEncoder)
  52538. {
  52539. drwav_data_format wavFormat;
  52540. drwav_allocation_callbacks allocationCallbacks;
  52541. drwav* pWav;
  52542. MA_ASSERT(pEncoder != NULL);
  52543. pWav = (drwav*)ma_malloc(sizeof(*pWav), &pEncoder->config.allocationCallbacks);
  52544. if (pWav == NULL) {
  52545. return MA_OUT_OF_MEMORY;
  52546. }
  52547. wavFormat.container = drwav_container_riff;
  52548. wavFormat.channels = pEncoder->config.channels;
  52549. wavFormat.sampleRate = pEncoder->config.sampleRate;
  52550. wavFormat.bitsPerSample = ma_get_bytes_per_sample(pEncoder->config.format) * 8;
  52551. if (pEncoder->config.format == ma_format_f32) {
  52552. wavFormat.format = DR_WAVE_FORMAT_IEEE_FLOAT;
  52553. } else {
  52554. wavFormat.format = DR_WAVE_FORMAT_PCM;
  52555. }
  52556. allocationCallbacks.pUserData = pEncoder->config.allocationCallbacks.pUserData;
  52557. allocationCallbacks.onMalloc = pEncoder->config.allocationCallbacks.onMalloc;
  52558. allocationCallbacks.onRealloc = pEncoder->config.allocationCallbacks.onRealloc;
  52559. allocationCallbacks.onFree = pEncoder->config.allocationCallbacks.onFree;
  52560. if (!drwav_init_write(pWav, &wavFormat, ma_encoder__internal_on_write_wav, ma_encoder__internal_on_seek_wav, pEncoder, &allocationCallbacks)) {
  52561. return MA_ERROR;
  52562. }
  52563. pEncoder->pInternalEncoder = pWav;
  52564. return MA_SUCCESS;
  52565. }
  52566. static void ma_encoder__on_uninit_wav(ma_encoder* pEncoder)
  52567. {
  52568. drwav* pWav;
  52569. MA_ASSERT(pEncoder != NULL);
  52570. pWav = (drwav*)pEncoder->pInternalEncoder;
  52571. MA_ASSERT(pWav != NULL);
  52572. drwav_uninit(pWav);
  52573. ma_free(pWav, &pEncoder->config.allocationCallbacks);
  52574. }
  52575. static ma_result ma_encoder__on_write_pcm_frames_wav(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  52576. {
  52577. drwav* pWav;
  52578. ma_uint64 framesWritten;
  52579. MA_ASSERT(pEncoder != NULL);
  52580. pWav = (drwav*)pEncoder->pInternalEncoder;
  52581. MA_ASSERT(pWav != NULL);
  52582. framesWritten = drwav_write_pcm_frames(pWav, frameCount, pFramesIn);
  52583. if (pFramesWritten != NULL) {
  52584. *pFramesWritten = framesWritten;
  52585. }
  52586. return MA_SUCCESS;
  52587. }
  52588. #endif
  52589. MA_API ma_encoder_config ma_encoder_config_init(ma_encoding_format encodingFormat, ma_format format, ma_uint32 channels, ma_uint32 sampleRate)
  52590. {
  52591. ma_encoder_config config;
  52592. MA_ZERO_OBJECT(&config);
  52593. config.encodingFormat = encodingFormat;
  52594. config.format = format;
  52595. config.channels = channels;
  52596. config.sampleRate = sampleRate;
  52597. return config;
  52598. }
  52599. MA_API ma_result ma_encoder_preinit(const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  52600. {
  52601. ma_result result;
  52602. if (pEncoder == NULL) {
  52603. return MA_INVALID_ARGS;
  52604. }
  52605. MA_ZERO_OBJECT(pEncoder);
  52606. if (pConfig == NULL) {
  52607. return MA_INVALID_ARGS;
  52608. }
  52609. if (pConfig->format == ma_format_unknown || pConfig->channels == 0 || pConfig->sampleRate == 0) {
  52610. return MA_INVALID_ARGS;
  52611. }
  52612. pEncoder->config = *pConfig;
  52613. result = ma_allocation_callbacks_init_copy(&pEncoder->config.allocationCallbacks, &pConfig->allocationCallbacks);
  52614. if (result != MA_SUCCESS) {
  52615. return result;
  52616. }
  52617. return MA_SUCCESS;
  52618. }
  52619. MA_API ma_result ma_encoder_init__internal(ma_encoder_write_proc onWrite, ma_encoder_seek_proc onSeek, void* pUserData, ma_encoder* pEncoder)
  52620. {
  52621. ma_result result = MA_SUCCESS;
  52622. /* This assumes ma_encoder_preinit() has been called prior. */
  52623. MA_ASSERT(pEncoder != NULL);
  52624. if (onWrite == NULL || onSeek == NULL) {
  52625. return MA_INVALID_ARGS;
  52626. }
  52627. pEncoder->onWrite = onWrite;
  52628. pEncoder->onSeek = onSeek;
  52629. pEncoder->pUserData = pUserData;
  52630. switch (pEncoder->config.encodingFormat)
  52631. {
  52632. case ma_encoding_format_wav:
  52633. {
  52634. #if defined(MA_HAS_WAV)
  52635. pEncoder->onInit = ma_encoder__on_init_wav;
  52636. pEncoder->onUninit = ma_encoder__on_uninit_wav;
  52637. pEncoder->onWritePCMFrames = ma_encoder__on_write_pcm_frames_wav;
  52638. #else
  52639. result = MA_NO_BACKEND;
  52640. #endif
  52641. } break;
  52642. default:
  52643. {
  52644. result = MA_INVALID_ARGS;
  52645. } break;
  52646. }
  52647. /* Getting here means we should have our backend callbacks set up. */
  52648. if (result == MA_SUCCESS) {
  52649. result = pEncoder->onInit(pEncoder);
  52650. }
  52651. return result;
  52652. }
  52653. static ma_result ma_encoder__on_write_vfs(ma_encoder* pEncoder, const void* pBufferIn, size_t bytesToWrite, size_t* pBytesWritten)
  52654. {
  52655. return ma_vfs_or_default_write(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, pBufferIn, bytesToWrite, pBytesWritten);
  52656. }
  52657. static ma_result ma_encoder__on_seek_vfs(ma_encoder* pEncoder, ma_int64 offset, ma_seek_origin origin)
  52658. {
  52659. return ma_vfs_or_default_seek(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file, offset, origin);
  52660. }
  52661. MA_API ma_result ma_encoder_init_vfs(ma_vfs* pVFS, const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  52662. {
  52663. ma_result result;
  52664. ma_vfs_file file;
  52665. result = ma_encoder_preinit(pConfig, pEncoder);
  52666. if (result != MA_SUCCESS) {
  52667. return result;
  52668. }
  52669. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  52670. result = ma_vfs_or_default_open(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  52671. if (result != MA_SUCCESS) {
  52672. return result;
  52673. }
  52674. pEncoder->data.vfs.pVFS = pVFS;
  52675. pEncoder->data.vfs.file = file;
  52676. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  52677. if (result != MA_SUCCESS) {
  52678. ma_vfs_or_default_close(pVFS, file);
  52679. return result;
  52680. }
  52681. return MA_SUCCESS;
  52682. }
  52683. MA_API ma_result ma_encoder_init_vfs_w(ma_vfs* pVFS, const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  52684. {
  52685. ma_result result;
  52686. ma_vfs_file file;
  52687. result = ma_encoder_preinit(pConfig, pEncoder);
  52688. if (result != MA_SUCCESS) {
  52689. return result;
  52690. }
  52691. /* Now open the file. If this fails we don't need to uninitialize the encoder. */
  52692. result = ma_vfs_or_default_open_w(pVFS, pFilePath, MA_OPEN_MODE_WRITE, &file);
  52693. if (result != MA_SUCCESS) {
  52694. return result;
  52695. }
  52696. pEncoder->data.vfs.pVFS = pVFS;
  52697. pEncoder->data.vfs.file = file;
  52698. result = ma_encoder_init__internal(ma_encoder__on_write_vfs, ma_encoder__on_seek_vfs, NULL, pEncoder);
  52699. if (result != MA_SUCCESS) {
  52700. ma_vfs_or_default_close(pVFS, file);
  52701. return result;
  52702. }
  52703. return MA_SUCCESS;
  52704. }
  52705. MA_API ma_result ma_encoder_init_file(const char* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  52706. {
  52707. return ma_encoder_init_vfs(NULL, pFilePath, pConfig, pEncoder);
  52708. }
  52709. MA_API ma_result ma_encoder_init_file_w(const wchar_t* pFilePath, const ma_encoder_config* pConfig, ma_encoder* pEncoder)
  52710. {
  52711. return ma_encoder_init_vfs_w(NULL, pFilePath, pConfig, pEncoder);
  52712. }
  52713. 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)
  52714. {
  52715. ma_result result;
  52716. result = ma_encoder_preinit(pConfig, pEncoder);
  52717. if (result != MA_SUCCESS) {
  52718. return result;
  52719. }
  52720. return ma_encoder_init__internal(onWrite, onSeek, pUserData, pEncoder);
  52721. }
  52722. MA_API void ma_encoder_uninit(ma_encoder* pEncoder)
  52723. {
  52724. if (pEncoder == NULL) {
  52725. return;
  52726. }
  52727. if (pEncoder->onUninit) {
  52728. pEncoder->onUninit(pEncoder);
  52729. }
  52730. /* If we have a file handle, close it. */
  52731. if (pEncoder->onWrite == ma_encoder__on_write_vfs) {
  52732. ma_vfs_or_default_close(pEncoder->data.vfs.pVFS, pEncoder->data.vfs.file);
  52733. pEncoder->data.vfs.file = NULL;
  52734. }
  52735. }
  52736. MA_API ma_result ma_encoder_write_pcm_frames(ma_encoder* pEncoder, const void* pFramesIn, ma_uint64 frameCount, ma_uint64* pFramesWritten)
  52737. {
  52738. if (pFramesWritten != NULL) {
  52739. *pFramesWritten = 0;
  52740. }
  52741. if (pEncoder == NULL || pFramesIn == NULL) {
  52742. return MA_INVALID_ARGS;
  52743. }
  52744. return pEncoder->onWritePCMFrames(pEncoder, pFramesIn, frameCount, pFramesWritten);
  52745. }
  52746. #endif /* MA_NO_ENCODING */
  52747. /**************************************************************************************************************************************************************
  52748. Generation
  52749. **************************************************************************************************************************************************************/
  52750. #ifndef MA_NO_GENERATION
  52751. 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)
  52752. {
  52753. ma_waveform_config config;
  52754. MA_ZERO_OBJECT(&config);
  52755. config.format = format;
  52756. config.channels = channels;
  52757. config.sampleRate = sampleRate;
  52758. config.type = type;
  52759. config.amplitude = amplitude;
  52760. config.frequency = frequency;
  52761. return config;
  52762. }
  52763. static ma_result ma_waveform__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  52764. {
  52765. return ma_waveform_read_pcm_frames((ma_waveform*)pDataSource, pFramesOut, frameCount, pFramesRead);
  52766. }
  52767. static ma_result ma_waveform__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  52768. {
  52769. return ma_waveform_seek_to_pcm_frame((ma_waveform*)pDataSource, frameIndex);
  52770. }
  52771. 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)
  52772. {
  52773. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  52774. *pFormat = pWaveform->config.format;
  52775. *pChannels = pWaveform->config.channels;
  52776. *pSampleRate = pWaveform->config.sampleRate;
  52777. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pWaveform->config.channels);
  52778. return MA_SUCCESS;
  52779. }
  52780. static ma_result ma_waveform__data_source_on_get_cursor(ma_data_source* pDataSource, ma_uint64* pCursor)
  52781. {
  52782. ma_waveform* pWaveform = (ma_waveform*)pDataSource;
  52783. *pCursor = (ma_uint64)(pWaveform->time / pWaveform->advance);
  52784. return MA_SUCCESS;
  52785. }
  52786. static double ma_waveform__calculate_advance(ma_uint32 sampleRate, double frequency)
  52787. {
  52788. return (1.0 / (sampleRate / frequency));
  52789. }
  52790. static void ma_waveform__update_advance(ma_waveform* pWaveform)
  52791. {
  52792. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  52793. }
  52794. static ma_data_source_vtable g_ma_waveform_data_source_vtable =
  52795. {
  52796. ma_waveform__data_source_on_read,
  52797. ma_waveform__data_source_on_seek,
  52798. ma_waveform__data_source_on_get_data_format,
  52799. ma_waveform__data_source_on_get_cursor,
  52800. NULL, /* onGetLength. There's no notion of a length in waveforms. */
  52801. NULL, /* onSetLooping */
  52802. 0
  52803. };
  52804. MA_API ma_result ma_waveform_init(const ma_waveform_config* pConfig, ma_waveform* pWaveform)
  52805. {
  52806. ma_result result;
  52807. ma_data_source_config dataSourceConfig;
  52808. if (pWaveform == NULL) {
  52809. return MA_INVALID_ARGS;
  52810. }
  52811. MA_ZERO_OBJECT(pWaveform);
  52812. dataSourceConfig = ma_data_source_config_init();
  52813. dataSourceConfig.vtable = &g_ma_waveform_data_source_vtable;
  52814. result = ma_data_source_init(&dataSourceConfig, &pWaveform->ds);
  52815. if (result != MA_SUCCESS) {
  52816. return result;
  52817. }
  52818. pWaveform->config = *pConfig;
  52819. pWaveform->advance = ma_waveform__calculate_advance(pWaveform->config.sampleRate, pWaveform->config.frequency);
  52820. pWaveform->time = 0;
  52821. return MA_SUCCESS;
  52822. }
  52823. MA_API void ma_waveform_uninit(ma_waveform* pWaveform)
  52824. {
  52825. if (pWaveform == NULL) {
  52826. return;
  52827. }
  52828. ma_data_source_uninit(&pWaveform->ds);
  52829. }
  52830. MA_API ma_result ma_waveform_set_amplitude(ma_waveform* pWaveform, double amplitude)
  52831. {
  52832. if (pWaveform == NULL) {
  52833. return MA_INVALID_ARGS;
  52834. }
  52835. pWaveform->config.amplitude = amplitude;
  52836. return MA_SUCCESS;
  52837. }
  52838. MA_API ma_result ma_waveform_set_frequency(ma_waveform* pWaveform, double frequency)
  52839. {
  52840. if (pWaveform == NULL) {
  52841. return MA_INVALID_ARGS;
  52842. }
  52843. pWaveform->config.frequency = frequency;
  52844. ma_waveform__update_advance(pWaveform);
  52845. return MA_SUCCESS;
  52846. }
  52847. MA_API ma_result ma_waveform_set_type(ma_waveform* pWaveform, ma_waveform_type type)
  52848. {
  52849. if (pWaveform == NULL) {
  52850. return MA_INVALID_ARGS;
  52851. }
  52852. pWaveform->config.type = type;
  52853. return MA_SUCCESS;
  52854. }
  52855. MA_API ma_result ma_waveform_set_sample_rate(ma_waveform* pWaveform, ma_uint32 sampleRate)
  52856. {
  52857. if (pWaveform == NULL) {
  52858. return MA_INVALID_ARGS;
  52859. }
  52860. pWaveform->config.sampleRate = sampleRate;
  52861. ma_waveform__update_advance(pWaveform);
  52862. return MA_SUCCESS;
  52863. }
  52864. static float ma_waveform_sine_f32(double time, double amplitude)
  52865. {
  52866. return (float)(ma_sind(MA_TAU_D * time) * amplitude);
  52867. }
  52868. static ma_int16 ma_waveform_sine_s16(double time, double amplitude)
  52869. {
  52870. return ma_pcm_sample_f32_to_s16(ma_waveform_sine_f32(time, amplitude));
  52871. }
  52872. static float ma_waveform_square_f32(double time, double amplitude)
  52873. {
  52874. double f = time - (ma_int64)time;
  52875. double r;
  52876. if (f < 0.5) {
  52877. r = amplitude;
  52878. } else {
  52879. r = -amplitude;
  52880. }
  52881. return (float)r;
  52882. }
  52883. static ma_int16 ma_waveform_square_s16(double time, double amplitude)
  52884. {
  52885. return ma_pcm_sample_f32_to_s16(ma_waveform_square_f32(time, amplitude));
  52886. }
  52887. static float ma_waveform_triangle_f32(double time, double amplitude)
  52888. {
  52889. double f = time - (ma_int64)time;
  52890. double r;
  52891. r = 2 * ma_abs(2 * (f - 0.5)) - 1;
  52892. return (float)(r * amplitude);
  52893. }
  52894. static ma_int16 ma_waveform_triangle_s16(double time, double amplitude)
  52895. {
  52896. return ma_pcm_sample_f32_to_s16(ma_waveform_triangle_f32(time, amplitude));
  52897. }
  52898. static float ma_waveform_sawtooth_f32(double time, double amplitude)
  52899. {
  52900. double f = time - (ma_int64)time;
  52901. double r;
  52902. r = 2 * (f - 0.5);
  52903. return (float)(r * amplitude);
  52904. }
  52905. static ma_int16 ma_waveform_sawtooth_s16(double time, double amplitude)
  52906. {
  52907. return ma_pcm_sample_f32_to_s16(ma_waveform_sawtooth_f32(time, amplitude));
  52908. }
  52909. static void ma_waveform_read_pcm_frames__sine(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  52910. {
  52911. ma_uint64 iFrame;
  52912. ma_uint64 iChannel;
  52913. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  52914. ma_uint32 bpf = bps * pWaveform->config.channels;
  52915. MA_ASSERT(pWaveform != NULL);
  52916. MA_ASSERT(pFramesOut != NULL);
  52917. if (pWaveform->config.format == ma_format_f32) {
  52918. float* pFramesOutF32 = (float*)pFramesOut;
  52919. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52920. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  52921. pWaveform->time += pWaveform->advance;
  52922. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52923. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  52924. }
  52925. }
  52926. } else if (pWaveform->config.format == ma_format_s16) {
  52927. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  52928. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52929. ma_int16 s = ma_waveform_sine_s16(pWaveform->time, pWaveform->config.amplitude);
  52930. pWaveform->time += pWaveform->advance;
  52931. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52932. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  52933. }
  52934. }
  52935. } else {
  52936. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52937. float s = ma_waveform_sine_f32(pWaveform->time, pWaveform->config.amplitude);
  52938. pWaveform->time += pWaveform->advance;
  52939. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52940. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  52941. }
  52942. }
  52943. }
  52944. }
  52945. static void ma_waveform_read_pcm_frames__square(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  52946. {
  52947. ma_uint64 iFrame;
  52948. ma_uint64 iChannel;
  52949. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  52950. ma_uint32 bpf = bps * pWaveform->config.channels;
  52951. MA_ASSERT(pWaveform != NULL);
  52952. MA_ASSERT(pFramesOut != NULL);
  52953. if (pWaveform->config.format == ma_format_f32) {
  52954. float* pFramesOutF32 = (float*)pFramesOut;
  52955. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52956. float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.amplitude);
  52957. pWaveform->time += pWaveform->advance;
  52958. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52959. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  52960. }
  52961. }
  52962. } else if (pWaveform->config.format == ma_format_s16) {
  52963. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  52964. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52965. ma_int16 s = ma_waveform_square_s16(pWaveform->time, pWaveform->config.amplitude);
  52966. pWaveform->time += pWaveform->advance;
  52967. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52968. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  52969. }
  52970. }
  52971. } else {
  52972. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52973. float s = ma_waveform_square_f32(pWaveform->time, pWaveform->config.amplitude);
  52974. pWaveform->time += pWaveform->advance;
  52975. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52976. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  52977. }
  52978. }
  52979. }
  52980. }
  52981. static void ma_waveform_read_pcm_frames__triangle(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  52982. {
  52983. ma_uint64 iFrame;
  52984. ma_uint64 iChannel;
  52985. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  52986. ma_uint32 bpf = bps * pWaveform->config.channels;
  52987. MA_ASSERT(pWaveform != NULL);
  52988. MA_ASSERT(pFramesOut != NULL);
  52989. if (pWaveform->config.format == ma_format_f32) {
  52990. float* pFramesOutF32 = (float*)pFramesOut;
  52991. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  52992. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  52993. pWaveform->time += pWaveform->advance;
  52994. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  52995. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  52996. }
  52997. }
  52998. } else if (pWaveform->config.format == ma_format_s16) {
  52999. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  53000. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53001. ma_int16 s = ma_waveform_triangle_s16(pWaveform->time, pWaveform->config.amplitude);
  53002. pWaveform->time += pWaveform->advance;
  53003. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  53004. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  53005. }
  53006. }
  53007. } else {
  53008. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53009. float s = ma_waveform_triangle_f32(pWaveform->time, pWaveform->config.amplitude);
  53010. pWaveform->time += pWaveform->advance;
  53011. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  53012. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53013. }
  53014. }
  53015. }
  53016. }
  53017. static void ma_waveform_read_pcm_frames__sawtooth(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount)
  53018. {
  53019. ma_uint64 iFrame;
  53020. ma_uint64 iChannel;
  53021. ma_uint32 bps = ma_get_bytes_per_sample(pWaveform->config.format);
  53022. ma_uint32 bpf = bps * pWaveform->config.channels;
  53023. MA_ASSERT(pWaveform != NULL);
  53024. MA_ASSERT(pFramesOut != NULL);
  53025. if (pWaveform->config.format == ma_format_f32) {
  53026. float* pFramesOutF32 = (float*)pFramesOut;
  53027. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53028. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  53029. pWaveform->time += pWaveform->advance;
  53030. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  53031. pFramesOutF32[iFrame*pWaveform->config.channels + iChannel] = s;
  53032. }
  53033. }
  53034. } else if (pWaveform->config.format == ma_format_s16) {
  53035. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  53036. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53037. ma_int16 s = ma_waveform_sawtooth_s16(pWaveform->time, pWaveform->config.amplitude);
  53038. pWaveform->time += pWaveform->advance;
  53039. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  53040. pFramesOutS16[iFrame*pWaveform->config.channels + iChannel] = s;
  53041. }
  53042. }
  53043. } else {
  53044. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53045. float s = ma_waveform_sawtooth_f32(pWaveform->time, pWaveform->config.amplitude);
  53046. pWaveform->time += pWaveform->advance;
  53047. for (iChannel = 0; iChannel < pWaveform->config.channels; iChannel += 1) {
  53048. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pWaveform->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53049. }
  53050. }
  53051. }
  53052. }
  53053. MA_API ma_result ma_waveform_read_pcm_frames(ma_waveform* pWaveform, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53054. {
  53055. if (pFramesRead != NULL) {
  53056. *pFramesRead = 0;
  53057. }
  53058. if (frameCount == 0) {
  53059. return MA_INVALID_ARGS;
  53060. }
  53061. if (pWaveform == NULL) {
  53062. return MA_INVALID_ARGS;
  53063. }
  53064. if (pFramesOut != NULL) {
  53065. switch (pWaveform->config.type)
  53066. {
  53067. case ma_waveform_type_sine:
  53068. {
  53069. ma_waveform_read_pcm_frames__sine(pWaveform, pFramesOut, frameCount);
  53070. } break;
  53071. case ma_waveform_type_square:
  53072. {
  53073. ma_waveform_read_pcm_frames__square(pWaveform, pFramesOut, frameCount);
  53074. } break;
  53075. case ma_waveform_type_triangle:
  53076. {
  53077. ma_waveform_read_pcm_frames__triangle(pWaveform, pFramesOut, frameCount);
  53078. } break;
  53079. case ma_waveform_type_sawtooth:
  53080. {
  53081. ma_waveform_read_pcm_frames__sawtooth(pWaveform, pFramesOut, frameCount);
  53082. } break;
  53083. default: return MA_INVALID_OPERATION; /* Unknown waveform type. */
  53084. }
  53085. } else {
  53086. pWaveform->time += pWaveform->advance * (ma_int64)frameCount; /* Cast to int64 required for VC6. Won't affect anything in practice. */
  53087. }
  53088. if (pFramesRead != NULL) {
  53089. *pFramesRead = frameCount;
  53090. }
  53091. return MA_SUCCESS;
  53092. }
  53093. MA_API ma_result ma_waveform_seek_to_pcm_frame(ma_waveform* pWaveform, ma_uint64 frameIndex)
  53094. {
  53095. if (pWaveform == NULL) {
  53096. return MA_INVALID_ARGS;
  53097. }
  53098. pWaveform->time = pWaveform->advance * (ma_int64)frameIndex; /* Casting for VC6. Won't be an issue in practice. */
  53099. return MA_SUCCESS;
  53100. }
  53101. MA_API ma_noise_config ma_noise_config_init(ma_format format, ma_uint32 channels, ma_noise_type type, ma_int32 seed, double amplitude)
  53102. {
  53103. ma_noise_config config;
  53104. MA_ZERO_OBJECT(&config);
  53105. config.format = format;
  53106. config.channels = channels;
  53107. config.type = type;
  53108. config.seed = seed;
  53109. config.amplitude = amplitude;
  53110. if (config.seed == 0) {
  53111. config.seed = MA_DEFAULT_LCG_SEED;
  53112. }
  53113. return config;
  53114. }
  53115. static ma_result ma_noise__data_source_on_read(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53116. {
  53117. return ma_noise_read_pcm_frames((ma_noise*)pDataSource, pFramesOut, frameCount, pFramesRead);
  53118. }
  53119. static ma_result ma_noise__data_source_on_seek(ma_data_source* pDataSource, ma_uint64 frameIndex)
  53120. {
  53121. /* No-op. Just pretend to be successful. */
  53122. (void)pDataSource;
  53123. (void)frameIndex;
  53124. return MA_SUCCESS;
  53125. }
  53126. 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)
  53127. {
  53128. ma_noise* pNoise = (ma_noise*)pDataSource;
  53129. *pFormat = pNoise->config.format;
  53130. *pChannels = pNoise->config.channels;
  53131. *pSampleRate = 0; /* There is no notion of sample rate with noise generation. */
  53132. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pNoise->config.channels);
  53133. return MA_SUCCESS;
  53134. }
  53135. static ma_data_source_vtable g_ma_noise_data_source_vtable =
  53136. {
  53137. ma_noise__data_source_on_read,
  53138. ma_noise__data_source_on_seek, /* No-op for noise. */
  53139. ma_noise__data_source_on_get_data_format,
  53140. NULL, /* onGetCursor. No notion of a cursor for noise. */
  53141. NULL, /* onGetLength. No notion of a length for noise. */
  53142. NULL, /* onSetLooping */
  53143. 0
  53144. };
  53145. #ifndef MA_PINK_NOISE_BIN_SIZE
  53146. #define MA_PINK_NOISE_BIN_SIZE 16
  53147. #endif
  53148. typedef struct
  53149. {
  53150. size_t sizeInBytes;
  53151. struct
  53152. {
  53153. size_t binOffset;
  53154. size_t accumulationOffset;
  53155. size_t counterOffset;
  53156. } pink;
  53157. struct
  53158. {
  53159. size_t accumulationOffset;
  53160. } brownian;
  53161. } ma_noise_heap_layout;
  53162. static ma_result ma_noise_get_heap_layout(const ma_noise_config* pConfig, ma_noise_heap_layout* pHeapLayout)
  53163. {
  53164. MA_ASSERT(pHeapLayout != NULL);
  53165. MA_ZERO_OBJECT(pHeapLayout);
  53166. if (pConfig == NULL) {
  53167. return MA_INVALID_ARGS;
  53168. }
  53169. if (pConfig->channels == 0) {
  53170. return MA_INVALID_ARGS;
  53171. }
  53172. pHeapLayout->sizeInBytes = 0;
  53173. /* Pink. */
  53174. if (pConfig->type == ma_noise_type_pink) {
  53175. /* bin */
  53176. pHeapLayout->pink.binOffset = pHeapLayout->sizeInBytes;
  53177. pHeapLayout->sizeInBytes += sizeof(double*) * pConfig->channels;
  53178. pHeapLayout->sizeInBytes += sizeof(double ) * pConfig->channels * MA_PINK_NOISE_BIN_SIZE;
  53179. /* accumulation */
  53180. pHeapLayout->pink.accumulationOffset = pHeapLayout->sizeInBytes;
  53181. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  53182. /* counter */
  53183. pHeapLayout->pink.counterOffset = pHeapLayout->sizeInBytes;
  53184. pHeapLayout->sizeInBytes += sizeof(ma_uint32) * pConfig->channels;
  53185. }
  53186. /* Brownian. */
  53187. if (pConfig->type == ma_noise_type_brownian) {
  53188. /* accumulation */
  53189. pHeapLayout->brownian.accumulationOffset = pHeapLayout->sizeInBytes;
  53190. pHeapLayout->sizeInBytes += sizeof(double) * pConfig->channels;
  53191. }
  53192. /* Make sure allocation size is aligned. */
  53193. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  53194. return MA_SUCCESS;
  53195. }
  53196. MA_API ma_result ma_noise_get_heap_size(const ma_noise_config* pConfig, size_t* pHeapSizeInBytes)
  53197. {
  53198. ma_result result;
  53199. ma_noise_heap_layout heapLayout;
  53200. if (pHeapSizeInBytes == NULL) {
  53201. return MA_INVALID_ARGS;
  53202. }
  53203. *pHeapSizeInBytes = 0;
  53204. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  53205. if (result != MA_SUCCESS) {
  53206. return result;
  53207. }
  53208. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  53209. return MA_SUCCESS;
  53210. }
  53211. MA_API ma_result ma_noise_init_preallocated(const ma_noise_config* pConfig, void* pHeap, ma_noise* pNoise)
  53212. {
  53213. ma_result result;
  53214. ma_noise_heap_layout heapLayout;
  53215. ma_data_source_config dataSourceConfig;
  53216. ma_uint32 iChannel;
  53217. if (pNoise == NULL) {
  53218. return MA_INVALID_ARGS;
  53219. }
  53220. MA_ZERO_OBJECT(pNoise);
  53221. result = ma_noise_get_heap_layout(pConfig, &heapLayout);
  53222. if (result != MA_SUCCESS) {
  53223. return result;
  53224. }
  53225. pNoise->_pHeap = pHeap;
  53226. MA_ZERO_MEMORY(pNoise->_pHeap, heapLayout.sizeInBytes);
  53227. dataSourceConfig = ma_data_source_config_init();
  53228. dataSourceConfig.vtable = &g_ma_noise_data_source_vtable;
  53229. result = ma_data_source_init(&dataSourceConfig, &pNoise->ds);
  53230. if (result != MA_SUCCESS) {
  53231. return result;
  53232. }
  53233. pNoise->config = *pConfig;
  53234. ma_lcg_seed(&pNoise->lcg, pConfig->seed);
  53235. if (pNoise->config.type == ma_noise_type_pink) {
  53236. pNoise->state.pink.bin = (double** )ma_offset_ptr(pHeap, heapLayout.pink.binOffset);
  53237. pNoise->state.pink.accumulation = (double* )ma_offset_ptr(pHeap, heapLayout.pink.accumulationOffset);
  53238. pNoise->state.pink.counter = (ma_uint32*)ma_offset_ptr(pHeap, heapLayout.pink.counterOffset);
  53239. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  53240. 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));
  53241. pNoise->state.pink.accumulation[iChannel] = 0;
  53242. pNoise->state.pink.counter[iChannel] = 1;
  53243. }
  53244. }
  53245. if (pNoise->config.type == ma_noise_type_brownian) {
  53246. pNoise->state.brownian.accumulation = (double*)ma_offset_ptr(pHeap, heapLayout.brownian.accumulationOffset);
  53247. for (iChannel = 0; iChannel < pConfig->channels; iChannel += 1) {
  53248. pNoise->state.brownian.accumulation[iChannel] = 0;
  53249. }
  53250. }
  53251. return MA_SUCCESS;
  53252. }
  53253. MA_API ma_result ma_noise_init(const ma_noise_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_noise* pNoise)
  53254. {
  53255. ma_result result;
  53256. size_t heapSizeInBytes;
  53257. void* pHeap;
  53258. result = ma_noise_get_heap_size(pConfig, &heapSizeInBytes);
  53259. if (result != MA_SUCCESS) {
  53260. return result;
  53261. }
  53262. if (heapSizeInBytes > 0) {
  53263. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  53264. if (pHeap == NULL) {
  53265. return MA_OUT_OF_MEMORY;
  53266. }
  53267. } else {
  53268. pHeap = NULL;
  53269. }
  53270. result = ma_noise_init_preallocated(pConfig, pHeap, pNoise);
  53271. if (result != MA_SUCCESS) {
  53272. ma_free(pHeap, pAllocationCallbacks);
  53273. return result;
  53274. }
  53275. pNoise->_ownsHeap = MA_TRUE;
  53276. return MA_SUCCESS;
  53277. }
  53278. MA_API void ma_noise_uninit(ma_noise* pNoise, const ma_allocation_callbacks* pAllocationCallbacks)
  53279. {
  53280. if (pNoise == NULL) {
  53281. return;
  53282. }
  53283. ma_data_source_uninit(&pNoise->ds);
  53284. if (pNoise->_ownsHeap) {
  53285. ma_free(pNoise->_pHeap, pAllocationCallbacks);
  53286. }
  53287. }
  53288. MA_API ma_result ma_noise_set_amplitude(ma_noise* pNoise, double amplitude)
  53289. {
  53290. if (pNoise == NULL) {
  53291. return MA_INVALID_ARGS;
  53292. }
  53293. pNoise->config.amplitude = amplitude;
  53294. return MA_SUCCESS;
  53295. }
  53296. MA_API ma_result ma_noise_set_seed(ma_noise* pNoise, ma_int32 seed)
  53297. {
  53298. if (pNoise == NULL) {
  53299. return MA_INVALID_ARGS;
  53300. }
  53301. pNoise->lcg.state = seed;
  53302. return MA_SUCCESS;
  53303. }
  53304. MA_API ma_result ma_noise_set_type(ma_noise* pNoise, ma_noise_type type)
  53305. {
  53306. if (pNoise == NULL) {
  53307. return MA_INVALID_ARGS;
  53308. }
  53309. pNoise->config.type = type;
  53310. return MA_SUCCESS;
  53311. }
  53312. static MA_INLINE float ma_noise_f32_white(ma_noise* pNoise)
  53313. {
  53314. return (float)(ma_lcg_rand_f64(&pNoise->lcg) * pNoise->config.amplitude);
  53315. }
  53316. static MA_INLINE ma_int16 ma_noise_s16_white(ma_noise* pNoise)
  53317. {
  53318. return ma_pcm_sample_f32_to_s16(ma_noise_f32_white(pNoise));
  53319. }
  53320. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__white(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  53321. {
  53322. ma_uint64 iFrame;
  53323. ma_uint32 iChannel;
  53324. const ma_uint32 channels = pNoise->config.channels;
  53325. MA_ASSUME(channels > 0);
  53326. if (pNoise->config.format == ma_format_f32) {
  53327. float* pFramesOutF32 = (float*)pFramesOut;
  53328. if (pNoise->config.duplicateChannels) {
  53329. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53330. float s = ma_noise_f32_white(pNoise);
  53331. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53332. pFramesOutF32[iFrame*channels + iChannel] = s;
  53333. }
  53334. }
  53335. } else {
  53336. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53337. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53338. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_white(pNoise);
  53339. }
  53340. }
  53341. }
  53342. } else if (pNoise->config.format == ma_format_s16) {
  53343. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  53344. if (pNoise->config.duplicateChannels) {
  53345. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53346. ma_int16 s = ma_noise_s16_white(pNoise);
  53347. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53348. pFramesOutS16[iFrame*channels + iChannel] = s;
  53349. }
  53350. }
  53351. } else {
  53352. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53353. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53354. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_white(pNoise);
  53355. }
  53356. }
  53357. }
  53358. } else {
  53359. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  53360. const ma_uint32 bpf = bps * channels;
  53361. if (pNoise->config.duplicateChannels) {
  53362. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53363. float s = ma_noise_f32_white(pNoise);
  53364. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53365. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53366. }
  53367. }
  53368. } else {
  53369. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53370. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53371. float s = ma_noise_f32_white(pNoise);
  53372. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53373. }
  53374. }
  53375. }
  53376. }
  53377. return frameCount;
  53378. }
  53379. static MA_INLINE unsigned int ma_tzcnt32(unsigned int x)
  53380. {
  53381. unsigned int n;
  53382. /* Special case for odd numbers since they should happen about half the time. */
  53383. if (x & 0x1) {
  53384. return 0;
  53385. }
  53386. if (x == 0) {
  53387. return sizeof(x) << 3;
  53388. }
  53389. n = 1;
  53390. if ((x & 0x0000FFFF) == 0) { x >>= 16; n += 16; }
  53391. if ((x & 0x000000FF) == 0) { x >>= 8; n += 8; }
  53392. if ((x & 0x0000000F) == 0) { x >>= 4; n += 4; }
  53393. if ((x & 0x00000003) == 0) { x >>= 2; n += 2; }
  53394. n -= x & 0x00000001;
  53395. return n;
  53396. }
  53397. /*
  53398. Pink noise generation based on Tonic (public domain) with modifications. https://github.com/TonicAudio/Tonic/blob/master/src/Tonic/Noise.h
  53399. This is basically _the_ reference for pink noise from what I've found: http://www.firstpr.com.au/dsp/pink-noise/
  53400. */
  53401. static MA_INLINE float ma_noise_f32_pink(ma_noise* pNoise, ma_uint32 iChannel)
  53402. {
  53403. double result;
  53404. double binPrev;
  53405. double binNext;
  53406. unsigned int ibin;
  53407. ibin = ma_tzcnt32(pNoise->state.pink.counter[iChannel]) & (MA_PINK_NOISE_BIN_SIZE - 1);
  53408. binPrev = pNoise->state.pink.bin[iChannel][ibin];
  53409. binNext = ma_lcg_rand_f64(&pNoise->lcg);
  53410. pNoise->state.pink.bin[iChannel][ibin] = binNext;
  53411. pNoise->state.pink.accumulation[iChannel] += (binNext - binPrev);
  53412. pNoise->state.pink.counter[iChannel] += 1;
  53413. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.pink.accumulation[iChannel]);
  53414. result /= 10;
  53415. return (float)(result * pNoise->config.amplitude);
  53416. }
  53417. static MA_INLINE ma_int16 ma_noise_s16_pink(ma_noise* pNoise, ma_uint32 iChannel)
  53418. {
  53419. return ma_pcm_sample_f32_to_s16(ma_noise_f32_pink(pNoise, iChannel));
  53420. }
  53421. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__pink(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  53422. {
  53423. ma_uint64 iFrame;
  53424. ma_uint32 iChannel;
  53425. const ma_uint32 channels = pNoise->config.channels;
  53426. MA_ASSUME(channels > 0);
  53427. if (pNoise->config.format == ma_format_f32) {
  53428. float* pFramesOutF32 = (float*)pFramesOut;
  53429. if (pNoise->config.duplicateChannels) {
  53430. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53431. float s = ma_noise_f32_pink(pNoise, 0);
  53432. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53433. pFramesOutF32[iFrame*channels + iChannel] = s;
  53434. }
  53435. }
  53436. } else {
  53437. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53438. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53439. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_pink(pNoise, iChannel);
  53440. }
  53441. }
  53442. }
  53443. } else if (pNoise->config.format == ma_format_s16) {
  53444. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  53445. if (pNoise->config.duplicateChannels) {
  53446. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53447. ma_int16 s = ma_noise_s16_pink(pNoise, 0);
  53448. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53449. pFramesOutS16[iFrame*channels + iChannel] = s;
  53450. }
  53451. }
  53452. } else {
  53453. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53454. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53455. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_pink(pNoise, iChannel);
  53456. }
  53457. }
  53458. }
  53459. } else {
  53460. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  53461. const ma_uint32 bpf = bps * channels;
  53462. if (pNoise->config.duplicateChannels) {
  53463. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53464. float s = ma_noise_f32_pink(pNoise, 0);
  53465. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53466. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53467. }
  53468. }
  53469. } else {
  53470. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53471. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53472. float s = ma_noise_f32_pink(pNoise, iChannel);
  53473. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53474. }
  53475. }
  53476. }
  53477. }
  53478. return frameCount;
  53479. }
  53480. static MA_INLINE float ma_noise_f32_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  53481. {
  53482. double result;
  53483. result = (ma_lcg_rand_f64(&pNoise->lcg) + pNoise->state.brownian.accumulation[iChannel]);
  53484. result /= 1.005; /* Don't escape the -1..1 range on average. */
  53485. pNoise->state.brownian.accumulation[iChannel] = result;
  53486. result /= 20;
  53487. return (float)(result * pNoise->config.amplitude);
  53488. }
  53489. static MA_INLINE ma_int16 ma_noise_s16_brownian(ma_noise* pNoise, ma_uint32 iChannel)
  53490. {
  53491. return ma_pcm_sample_f32_to_s16(ma_noise_f32_brownian(pNoise, iChannel));
  53492. }
  53493. static MA_INLINE ma_uint64 ma_noise_read_pcm_frames__brownian(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount)
  53494. {
  53495. ma_uint64 iFrame;
  53496. ma_uint32 iChannel;
  53497. const ma_uint32 channels = pNoise->config.channels;
  53498. MA_ASSUME(channels > 0);
  53499. if (pNoise->config.format == ma_format_f32) {
  53500. float* pFramesOutF32 = (float*)pFramesOut;
  53501. if (pNoise->config.duplicateChannels) {
  53502. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53503. float s = ma_noise_f32_brownian(pNoise, 0);
  53504. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53505. pFramesOutF32[iFrame*channels + iChannel] = s;
  53506. }
  53507. }
  53508. } else {
  53509. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53510. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53511. pFramesOutF32[iFrame*channels + iChannel] = ma_noise_f32_brownian(pNoise, iChannel);
  53512. }
  53513. }
  53514. }
  53515. } else if (pNoise->config.format == ma_format_s16) {
  53516. ma_int16* pFramesOutS16 = (ma_int16*)pFramesOut;
  53517. if (pNoise->config.duplicateChannels) {
  53518. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53519. ma_int16 s = ma_noise_s16_brownian(pNoise, 0);
  53520. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53521. pFramesOutS16[iFrame*channels + iChannel] = s;
  53522. }
  53523. }
  53524. } else {
  53525. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53526. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53527. pFramesOutS16[iFrame*channels + iChannel] = ma_noise_s16_brownian(pNoise, iChannel);
  53528. }
  53529. }
  53530. }
  53531. } else {
  53532. const ma_uint32 bps = ma_get_bytes_per_sample(pNoise->config.format);
  53533. const ma_uint32 bpf = bps * channels;
  53534. if (pNoise->config.duplicateChannels) {
  53535. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53536. float s = ma_noise_f32_brownian(pNoise, 0);
  53537. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53538. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53539. }
  53540. }
  53541. } else {
  53542. for (iFrame = 0; iFrame < frameCount; iFrame += 1) {
  53543. for (iChannel = 0; iChannel < channels; iChannel += 1) {
  53544. float s = ma_noise_f32_brownian(pNoise, iChannel);
  53545. ma_pcm_convert(ma_offset_ptr(pFramesOut, iFrame*bpf + iChannel*bps), pNoise->config.format, &s, ma_format_f32, 1, ma_dither_mode_none);
  53546. }
  53547. }
  53548. }
  53549. }
  53550. return frameCount;
  53551. }
  53552. MA_API ma_result ma_noise_read_pcm_frames(ma_noise* pNoise, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  53553. {
  53554. ma_uint64 framesRead = 0;
  53555. if (pFramesRead != NULL) {
  53556. *pFramesRead = 0;
  53557. }
  53558. if (frameCount == 0) {
  53559. return MA_INVALID_ARGS;
  53560. }
  53561. if (pNoise == NULL) {
  53562. return MA_INVALID_ARGS;
  53563. }
  53564. /* 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. */
  53565. if (pFramesOut == NULL) {
  53566. framesRead = frameCount;
  53567. } else {
  53568. switch (pNoise->config.type) {
  53569. case ma_noise_type_white: framesRead = ma_noise_read_pcm_frames__white (pNoise, pFramesOut, frameCount); break;
  53570. case ma_noise_type_pink: framesRead = ma_noise_read_pcm_frames__pink (pNoise, pFramesOut, frameCount); break;
  53571. case ma_noise_type_brownian: framesRead = ma_noise_read_pcm_frames__brownian(pNoise, pFramesOut, frameCount); break;
  53572. default: return MA_INVALID_OPERATION; /* Unknown noise type. */
  53573. }
  53574. }
  53575. if (pFramesRead != NULL) {
  53576. *pFramesRead = framesRead;
  53577. }
  53578. return MA_SUCCESS;
  53579. }
  53580. #endif /* MA_NO_GENERATION */
  53581. #ifndef MA_NO_RESOURCE_MANAGER
  53582. #ifndef MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS
  53583. #define MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS 1000
  53584. #endif
  53585. #ifndef MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY
  53586. #define MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY 1024
  53587. #endif
  53588. MA_API ma_resource_manager_pipeline_notifications ma_resource_manager_pipeline_notifications_init(void)
  53589. {
  53590. ma_resource_manager_pipeline_notifications notifications;
  53591. MA_ZERO_OBJECT(&notifications);
  53592. return notifications;
  53593. }
  53594. static void ma_resource_manager_pipeline_notifications_signal_all_notifications(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  53595. {
  53596. if (pPipelineNotifications == NULL) {
  53597. return;
  53598. }
  53599. if (pPipelineNotifications->init.pNotification) { ma_async_notification_signal(pPipelineNotifications->init.pNotification); }
  53600. if (pPipelineNotifications->done.pNotification) { ma_async_notification_signal(pPipelineNotifications->done.pNotification); }
  53601. }
  53602. static void ma_resource_manager_pipeline_notifications_acquire_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  53603. {
  53604. if (pPipelineNotifications == NULL) {
  53605. return;
  53606. }
  53607. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->init.pFence); }
  53608. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_acquire(pPipelineNotifications->done.pFence); }
  53609. }
  53610. static void ma_resource_manager_pipeline_notifications_release_all_fences(const ma_resource_manager_pipeline_notifications* pPipelineNotifications)
  53611. {
  53612. if (pPipelineNotifications == NULL) {
  53613. return;
  53614. }
  53615. if (pPipelineNotifications->init.pFence != NULL) { ma_fence_release(pPipelineNotifications->init.pFence); }
  53616. if (pPipelineNotifications->done.pFence != NULL) { ma_fence_release(pPipelineNotifications->done.pFence); }
  53617. }
  53618. #ifndef MA_DEFAULT_HASH_SEED
  53619. #define MA_DEFAULT_HASH_SEED 42
  53620. #endif
  53621. /* MurmurHash3. Based on code from https://github.com/PeterScott/murmur3/blob/master/murmur3.c (public domain). */
  53622. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  53623. #pragma GCC diagnostic push
  53624. #if __GNUC__ >= 7
  53625. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  53626. #endif
  53627. #endif
  53628. static MA_INLINE ma_uint32 ma_rotl32(ma_uint32 x, ma_int8 r)
  53629. {
  53630. return (x << r) | (x >> (32 - r));
  53631. }
  53632. static MA_INLINE ma_uint32 ma_hash_getblock(const ma_uint32* blocks, int i)
  53633. {
  53634. ma_uint32 block;
  53635. /* Try silencing a sanitization warning about unaligned access by doing a memcpy() instead of assignment. */
  53636. MA_COPY_MEMORY(&block, ma_offset_ptr(blocks, i * sizeof(block)), sizeof(block));
  53637. if (ma_is_little_endian()) {
  53638. return block;
  53639. } else {
  53640. return ma_swap_endian_uint32(block);
  53641. }
  53642. }
  53643. static MA_INLINE ma_uint32 ma_hash_fmix32(ma_uint32 h)
  53644. {
  53645. h ^= h >> 16;
  53646. h *= 0x85ebca6b;
  53647. h ^= h >> 13;
  53648. h *= 0xc2b2ae35;
  53649. h ^= h >> 16;
  53650. return h;
  53651. }
  53652. static ma_uint32 ma_hash_32(const void* key, int len, ma_uint32 seed)
  53653. {
  53654. const ma_uint8* data = (const ma_uint8*)key;
  53655. const ma_uint32* blocks;
  53656. const ma_uint8* tail;
  53657. const int nblocks = len / 4;
  53658. ma_uint32 h1 = seed;
  53659. ma_uint32 c1 = 0xcc9e2d51;
  53660. ma_uint32 c2 = 0x1b873593;
  53661. ma_uint32 k1;
  53662. int i;
  53663. blocks = (const ma_uint32 *)(data + nblocks*4);
  53664. for(i = -nblocks; i; i++) {
  53665. k1 = ma_hash_getblock(blocks,i);
  53666. k1 *= c1;
  53667. k1 = ma_rotl32(k1, 15);
  53668. k1 *= c2;
  53669. h1 ^= k1;
  53670. h1 = ma_rotl32(h1, 13);
  53671. h1 = h1*5 + 0xe6546b64;
  53672. }
  53673. tail = (const ma_uint8*)(data + nblocks*4);
  53674. k1 = 0;
  53675. switch(len & 3) {
  53676. case 3: k1 ^= tail[2] << 16;
  53677. case 2: k1 ^= tail[1] << 8;
  53678. case 1: k1 ^= tail[0];
  53679. k1 *= c1; k1 = ma_rotl32(k1, 15); k1 *= c2; h1 ^= k1;
  53680. };
  53681. h1 ^= len;
  53682. h1 = ma_hash_fmix32(h1);
  53683. return h1;
  53684. }
  53685. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  53686. #pragma GCC diagnostic push
  53687. #endif
  53688. /* End MurmurHash3 */
  53689. static ma_uint32 ma_hash_string_32(const char* str)
  53690. {
  53691. return ma_hash_32(str, (int)strlen(str), MA_DEFAULT_HASH_SEED);
  53692. }
  53693. static ma_uint32 ma_hash_string_w_32(const wchar_t* str)
  53694. {
  53695. return ma_hash_32(str, (int)wcslen(str) * sizeof(*str), MA_DEFAULT_HASH_SEED);
  53696. }
  53697. /*
  53698. Basic BST Functions
  53699. */
  53700. static ma_result ma_resource_manager_data_buffer_node_search(ma_resource_manager* pResourceManager, ma_uint32 hashedName32, ma_resource_manager_data_buffer_node** ppDataBufferNode)
  53701. {
  53702. ma_resource_manager_data_buffer_node* pCurrentNode;
  53703. MA_ASSERT(pResourceManager != NULL);
  53704. MA_ASSERT(ppDataBufferNode != NULL);
  53705. pCurrentNode = pResourceManager->pRootDataBufferNode;
  53706. while (pCurrentNode != NULL) {
  53707. if (hashedName32 == pCurrentNode->hashedName32) {
  53708. break; /* Found. */
  53709. } else if (hashedName32 < pCurrentNode->hashedName32) {
  53710. pCurrentNode = pCurrentNode->pChildLo;
  53711. } else {
  53712. pCurrentNode = pCurrentNode->pChildHi;
  53713. }
  53714. }
  53715. *ppDataBufferNode = pCurrentNode;
  53716. if (pCurrentNode == NULL) {
  53717. return MA_DOES_NOT_EXIST;
  53718. } else {
  53719. return MA_SUCCESS;
  53720. }
  53721. }
  53722. 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)
  53723. {
  53724. ma_result result = MA_SUCCESS;
  53725. ma_resource_manager_data_buffer_node* pCurrentNode;
  53726. MA_ASSERT(pResourceManager != NULL);
  53727. MA_ASSERT(ppInsertPoint != NULL);
  53728. *ppInsertPoint = NULL;
  53729. if (pResourceManager->pRootDataBufferNode == NULL) {
  53730. return MA_SUCCESS; /* No items. */
  53731. }
  53732. /* 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. */
  53733. pCurrentNode = pResourceManager->pRootDataBufferNode;
  53734. while (pCurrentNode != NULL) {
  53735. if (hashedName32 == pCurrentNode->hashedName32) {
  53736. result = MA_ALREADY_EXISTS;
  53737. break;
  53738. } else {
  53739. if (hashedName32 < pCurrentNode->hashedName32) {
  53740. if (pCurrentNode->pChildLo == NULL) {
  53741. result = MA_SUCCESS;
  53742. break;
  53743. } else {
  53744. pCurrentNode = pCurrentNode->pChildLo;
  53745. }
  53746. } else {
  53747. if (pCurrentNode->pChildHi == NULL) {
  53748. result = MA_SUCCESS;
  53749. break;
  53750. } else {
  53751. pCurrentNode = pCurrentNode->pChildHi;
  53752. }
  53753. }
  53754. }
  53755. }
  53756. *ppInsertPoint = pCurrentNode;
  53757. return result;
  53758. }
  53759. 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)
  53760. {
  53761. MA_ASSERT(pResourceManager != NULL);
  53762. MA_ASSERT(pDataBufferNode != NULL);
  53763. /* The key must have been set before calling this function. */
  53764. MA_ASSERT(pDataBufferNode->hashedName32 != 0);
  53765. if (pInsertPoint == NULL) {
  53766. /* It's the first node. */
  53767. pResourceManager->pRootDataBufferNode = pDataBufferNode;
  53768. } else {
  53769. /* It's not the first node. It needs to be inserted. */
  53770. if (pDataBufferNode->hashedName32 < pInsertPoint->hashedName32) {
  53771. MA_ASSERT(pInsertPoint->pChildLo == NULL);
  53772. pInsertPoint->pChildLo = pDataBufferNode;
  53773. } else {
  53774. MA_ASSERT(pInsertPoint->pChildHi == NULL);
  53775. pInsertPoint->pChildHi = pDataBufferNode;
  53776. }
  53777. }
  53778. pDataBufferNode->pParent = pInsertPoint;
  53779. return MA_SUCCESS;
  53780. }
  53781. #if 0 /* Unused for now. */
  53782. static ma_result ma_resource_manager_data_buffer_node_insert(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  53783. {
  53784. ma_result result;
  53785. ma_resource_manager_data_buffer_node* pInsertPoint;
  53786. MA_ASSERT(pResourceManager != NULL);
  53787. MA_ASSERT(pDataBufferNode != NULL);
  53788. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, pDataBufferNode->hashedName32, &pInsertPoint);
  53789. if (result != MA_SUCCESS) {
  53790. return MA_INVALID_ARGS;
  53791. }
  53792. return ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  53793. }
  53794. #endif
  53795. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_min(ma_resource_manager_data_buffer_node* pDataBufferNode)
  53796. {
  53797. ma_resource_manager_data_buffer_node* pCurrentNode;
  53798. MA_ASSERT(pDataBufferNode != NULL);
  53799. pCurrentNode = pDataBufferNode;
  53800. while (pCurrentNode->pChildLo != NULL) {
  53801. pCurrentNode = pCurrentNode->pChildLo;
  53802. }
  53803. return pCurrentNode;
  53804. }
  53805. static MA_INLINE ma_resource_manager_data_buffer_node* ma_resource_manager_data_buffer_node_find_max(ma_resource_manager_data_buffer_node* pDataBufferNode)
  53806. {
  53807. ma_resource_manager_data_buffer_node* pCurrentNode;
  53808. MA_ASSERT(pDataBufferNode != NULL);
  53809. pCurrentNode = pDataBufferNode;
  53810. while (pCurrentNode->pChildHi != NULL) {
  53811. pCurrentNode = pCurrentNode->pChildHi;
  53812. }
  53813. return pCurrentNode;
  53814. }
  53815. 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)
  53816. {
  53817. MA_ASSERT(pDataBufferNode != NULL);
  53818. MA_ASSERT(pDataBufferNode->pChildHi != NULL);
  53819. return ma_resource_manager_data_buffer_node_find_min(pDataBufferNode->pChildHi);
  53820. }
  53821. 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)
  53822. {
  53823. MA_ASSERT(pDataBufferNode != NULL);
  53824. MA_ASSERT(pDataBufferNode->pChildLo != NULL);
  53825. return ma_resource_manager_data_buffer_node_find_max(pDataBufferNode->pChildLo);
  53826. }
  53827. static ma_result ma_resource_manager_data_buffer_node_remove(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  53828. {
  53829. MA_ASSERT(pResourceManager != NULL);
  53830. MA_ASSERT(pDataBufferNode != NULL);
  53831. if (pDataBufferNode->pChildLo == NULL) {
  53832. if (pDataBufferNode->pChildHi == NULL) {
  53833. /* Simple case - deleting a buffer with no children. */
  53834. if (pDataBufferNode->pParent == NULL) {
  53835. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode); /* There is only a single buffer in the tree which should be equal to the root node. */
  53836. pResourceManager->pRootDataBufferNode = NULL;
  53837. } else {
  53838. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  53839. pDataBufferNode->pParent->pChildLo = NULL;
  53840. } else {
  53841. pDataBufferNode->pParent->pChildHi = NULL;
  53842. }
  53843. }
  53844. } else {
  53845. /* Node has one child - pChildHi != NULL. */
  53846. pDataBufferNode->pChildHi->pParent = pDataBufferNode->pParent;
  53847. if (pDataBufferNode->pParent == NULL) {
  53848. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  53849. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildHi;
  53850. } else {
  53851. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  53852. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildHi;
  53853. } else {
  53854. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildHi;
  53855. }
  53856. }
  53857. }
  53858. } else {
  53859. if (pDataBufferNode->pChildHi == NULL) {
  53860. /* Node has one child - pChildLo != NULL. */
  53861. pDataBufferNode->pChildLo->pParent = pDataBufferNode->pParent;
  53862. if (pDataBufferNode->pParent == NULL) {
  53863. MA_ASSERT(pResourceManager->pRootDataBufferNode == pDataBufferNode);
  53864. pResourceManager->pRootDataBufferNode = pDataBufferNode->pChildLo;
  53865. } else {
  53866. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  53867. pDataBufferNode->pParent->pChildLo = pDataBufferNode->pChildLo;
  53868. } else {
  53869. pDataBufferNode->pParent->pChildHi = pDataBufferNode->pChildLo;
  53870. }
  53871. }
  53872. } else {
  53873. /* Complex case - deleting a node with two children. */
  53874. ma_resource_manager_data_buffer_node* pReplacementDataBufferNode;
  53875. /* 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. */
  53876. pReplacementDataBufferNode = ma_resource_manager_data_buffer_node_find_inorder_successor(pDataBufferNode);
  53877. MA_ASSERT(pReplacementDataBufferNode != NULL);
  53878. /*
  53879. 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
  53880. 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
  53881. 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
  53882. replacement node and reinserting it into the same position as the deleted node.
  53883. */
  53884. MA_ASSERT(pReplacementDataBufferNode->pParent != NULL); /* The replacement node should never be the root which means it should always have a parent. */
  53885. MA_ASSERT(pReplacementDataBufferNode->pChildLo == NULL); /* Because we used in-order successor. This would be pChildHi == NULL if we used in-order predecessor. */
  53886. if (pReplacementDataBufferNode->pChildHi == NULL) {
  53887. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  53888. pReplacementDataBufferNode->pParent->pChildLo = NULL;
  53889. } else {
  53890. pReplacementDataBufferNode->pParent->pChildHi = NULL;
  53891. }
  53892. } else {
  53893. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode->pParent;
  53894. if (pReplacementDataBufferNode->pParent->pChildLo == pReplacementDataBufferNode) {
  53895. pReplacementDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode->pChildHi;
  53896. } else {
  53897. pReplacementDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode->pChildHi;
  53898. }
  53899. }
  53900. /* 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 */
  53901. if (pDataBufferNode->pParent != NULL) {
  53902. if (pDataBufferNode->pParent->pChildLo == pDataBufferNode) {
  53903. pDataBufferNode->pParent->pChildLo = pReplacementDataBufferNode;
  53904. } else {
  53905. pDataBufferNode->pParent->pChildHi = pReplacementDataBufferNode;
  53906. }
  53907. }
  53908. /* Now need to update the replacement node's pointers. */
  53909. pReplacementDataBufferNode->pParent = pDataBufferNode->pParent;
  53910. pReplacementDataBufferNode->pChildLo = pDataBufferNode->pChildLo;
  53911. pReplacementDataBufferNode->pChildHi = pDataBufferNode->pChildHi;
  53912. /* Now the children of the replacement node need to have their parent pointers updated. */
  53913. if (pReplacementDataBufferNode->pChildLo != NULL) {
  53914. pReplacementDataBufferNode->pChildLo->pParent = pReplacementDataBufferNode;
  53915. }
  53916. if (pReplacementDataBufferNode->pChildHi != NULL) {
  53917. pReplacementDataBufferNode->pChildHi->pParent = pReplacementDataBufferNode;
  53918. }
  53919. /* Now the root node needs to be updated. */
  53920. if (pResourceManager->pRootDataBufferNode == pDataBufferNode) {
  53921. pResourceManager->pRootDataBufferNode = pReplacementDataBufferNode;
  53922. }
  53923. }
  53924. }
  53925. return MA_SUCCESS;
  53926. }
  53927. #if 0 /* Unused for now. */
  53928. static ma_result ma_resource_manager_data_buffer_node_remove_by_key(ma_resource_manager* pResourceManager, ma_uint32 hashedName32)
  53929. {
  53930. ma_result result;
  53931. ma_resource_manager_data_buffer_node* pDataBufferNode;
  53932. result = ma_resource_manager_data_buffer_search(pResourceManager, hashedName32, &pDataBufferNode);
  53933. if (result != MA_SUCCESS) {
  53934. return result; /* Could not find the data buffer. */
  53935. }
  53936. return ma_resource_manager_data_buffer_remove(pResourceManager, pDataBufferNode);
  53937. }
  53938. #endif
  53939. static ma_resource_manager_data_supply_type ma_resource_manager_data_buffer_node_get_data_supply_type(ma_resource_manager_data_buffer_node* pDataBufferNode)
  53940. {
  53941. return (ma_resource_manager_data_supply_type)c89atomic_load_i32(&pDataBufferNode->data.type);
  53942. }
  53943. 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)
  53944. {
  53945. c89atomic_exchange_i32(&pDataBufferNode->data.type, supplyType);
  53946. }
  53947. 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)
  53948. {
  53949. ma_uint32 refCount;
  53950. MA_ASSERT(pResourceManager != NULL);
  53951. MA_ASSERT(pDataBufferNode != NULL);
  53952. (void)pResourceManager;
  53953. refCount = c89atomic_fetch_add_32(&pDataBufferNode->refCount, 1) + 1;
  53954. if (pNewRefCount != NULL) {
  53955. *pNewRefCount = refCount;
  53956. }
  53957. return MA_SUCCESS;
  53958. }
  53959. 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)
  53960. {
  53961. ma_uint32 refCount;
  53962. MA_ASSERT(pResourceManager != NULL);
  53963. MA_ASSERT(pDataBufferNode != NULL);
  53964. (void)pResourceManager;
  53965. refCount = c89atomic_fetch_sub_32(&pDataBufferNode->refCount, 1) - 1;
  53966. if (pNewRefCount != NULL) {
  53967. *pNewRefCount = refCount;
  53968. }
  53969. return MA_SUCCESS;
  53970. }
  53971. static void ma_resource_manager_data_buffer_node_free(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer_node* pDataBufferNode)
  53972. {
  53973. MA_ASSERT(pResourceManager != NULL);
  53974. MA_ASSERT(pDataBufferNode != NULL);
  53975. if (pDataBufferNode->isDataOwnedByResourceManager) {
  53976. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_encoded) {
  53977. ma_free((void*)pDataBufferNode->data.backend.encoded.pData, &pResourceManager->config.allocationCallbacks);
  53978. pDataBufferNode->data.backend.encoded.pData = NULL;
  53979. pDataBufferNode->data.backend.encoded.sizeInBytes = 0;
  53980. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded) {
  53981. ma_free((void*)pDataBufferNode->data.backend.decoded.pData, &pResourceManager->config.allocationCallbacks);
  53982. pDataBufferNode->data.backend.decoded.pData = NULL;
  53983. pDataBufferNode->data.backend.decoded.totalFrameCount = 0;
  53984. } else if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode) == ma_resource_manager_data_supply_type_decoded_paged) {
  53985. ma_paged_audio_buffer_data_uninit(&pDataBufferNode->data.backend.decodedPaged.data, &pResourceManager->config.allocationCallbacks);
  53986. } else {
  53987. /* Should never hit this if the node was successfully initialized. */
  53988. MA_ASSERT(pDataBufferNode->result != MA_SUCCESS);
  53989. }
  53990. }
  53991. /* The data buffer itself needs to be freed. */
  53992. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  53993. }
  53994. static ma_result ma_resource_manager_data_buffer_node_result(const ma_resource_manager_data_buffer_node* pDataBufferNode)
  53995. {
  53996. MA_ASSERT(pDataBufferNode != NULL);
  53997. return (ma_result)c89atomic_load_i32((ma_result*)&pDataBufferNode->result); /* Need a naughty const-cast here. */
  53998. }
  53999. static ma_bool32 ma_resource_manager_is_threading_enabled(const ma_resource_manager* pResourceManager)
  54000. {
  54001. MA_ASSERT(pResourceManager != NULL);
  54002. return (pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) == 0;
  54003. }
  54004. typedef struct
  54005. {
  54006. union
  54007. {
  54008. ma_async_notification_event e;
  54009. ma_async_notification_poll p;
  54010. } backend; /* Must be the first member. */
  54011. ma_resource_manager* pResourceManager;
  54012. } ma_resource_manager_inline_notification;
  54013. static ma_result ma_resource_manager_inline_notification_init(ma_resource_manager* pResourceManager, ma_resource_manager_inline_notification* pNotification)
  54014. {
  54015. MA_ASSERT(pResourceManager != NULL);
  54016. MA_ASSERT(pNotification != NULL);
  54017. pNotification->pResourceManager = pResourceManager;
  54018. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54019. return ma_async_notification_event_init(&pNotification->backend.e);
  54020. } else {
  54021. return ma_async_notification_poll_init(&pNotification->backend.p);
  54022. }
  54023. }
  54024. static void ma_resource_manager_inline_notification_uninit(ma_resource_manager_inline_notification* pNotification)
  54025. {
  54026. MA_ASSERT(pNotification != NULL);
  54027. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  54028. ma_async_notification_event_uninit(&pNotification->backend.e);
  54029. } else {
  54030. /* No need to uninitialize a polling notification. */
  54031. }
  54032. }
  54033. static void ma_resource_manager_inline_notification_wait(ma_resource_manager_inline_notification* pNotification)
  54034. {
  54035. MA_ASSERT(pNotification != NULL);
  54036. if (ma_resource_manager_is_threading_enabled(pNotification->pResourceManager)) {
  54037. ma_async_notification_event_wait(&pNotification->backend.e);
  54038. } else {
  54039. while (ma_async_notification_poll_is_signalled(&pNotification->backend.p) == MA_FALSE) {
  54040. ma_result result = ma_resource_manager_process_next_job(pNotification->pResourceManager);
  54041. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  54042. break;
  54043. }
  54044. }
  54045. }
  54046. }
  54047. static void ma_resource_manager_inline_notification_wait_and_uninit(ma_resource_manager_inline_notification* pNotification)
  54048. {
  54049. ma_resource_manager_inline_notification_wait(pNotification);
  54050. ma_resource_manager_inline_notification_uninit(pNotification);
  54051. }
  54052. static void ma_resource_manager_data_buffer_bst_lock(ma_resource_manager* pResourceManager)
  54053. {
  54054. MA_ASSERT(pResourceManager != NULL);
  54055. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54056. #ifndef MA_NO_THREADING
  54057. {
  54058. ma_mutex_lock(&pResourceManager->dataBufferBSTLock);
  54059. }
  54060. #else
  54061. {
  54062. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  54063. }
  54064. #endif
  54065. } else {
  54066. /* Threading not enabled. Do nothing. */
  54067. }
  54068. }
  54069. static void ma_resource_manager_data_buffer_bst_unlock(ma_resource_manager* pResourceManager)
  54070. {
  54071. MA_ASSERT(pResourceManager != NULL);
  54072. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54073. #ifndef MA_NO_THREADING
  54074. {
  54075. ma_mutex_unlock(&pResourceManager->dataBufferBSTLock);
  54076. }
  54077. #else
  54078. {
  54079. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  54080. }
  54081. #endif
  54082. } else {
  54083. /* Threading not enabled. Do nothing. */
  54084. }
  54085. }
  54086. #ifndef MA_NO_THREADING
  54087. static ma_thread_result MA_THREADCALL ma_resource_manager_job_thread(void* pUserData)
  54088. {
  54089. ma_resource_manager* pResourceManager = (ma_resource_manager*)pUserData;
  54090. MA_ASSERT(pResourceManager != NULL);
  54091. for (;;) {
  54092. ma_result result;
  54093. ma_job job;
  54094. result = ma_resource_manager_next_job(pResourceManager, &job);
  54095. if (result != MA_SUCCESS) {
  54096. break;
  54097. }
  54098. /* Terminate if we got a quit message. */
  54099. if (job.toc.breakup.code == MA_JOB_TYPE_QUIT) {
  54100. break;
  54101. }
  54102. ma_job_process(&job);
  54103. }
  54104. return (ma_thread_result)0;
  54105. }
  54106. #endif
  54107. MA_API ma_resource_manager_config ma_resource_manager_config_init(void)
  54108. {
  54109. ma_resource_manager_config config;
  54110. MA_ZERO_OBJECT(&config);
  54111. config.decodedFormat = ma_format_unknown;
  54112. config.decodedChannels = 0;
  54113. config.decodedSampleRate = 0;
  54114. config.jobThreadCount = 1; /* A single miniaudio-managed job thread by default. */
  54115. config.jobQueueCapacity = MA_JOB_TYPE_RESOURCE_MANAGER_QUEUE_CAPACITY;
  54116. /* Flags. */
  54117. config.flags = 0;
  54118. #ifdef MA_NO_THREADING
  54119. {
  54120. /* Threading is disabled at compile time so disable threading at runtime as well by default. */
  54121. config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  54122. config.jobThreadCount = 0;
  54123. }
  54124. #endif
  54125. return config;
  54126. }
  54127. MA_API ma_result ma_resource_manager_init(const ma_resource_manager_config* pConfig, ma_resource_manager* pResourceManager)
  54128. {
  54129. ma_result result;
  54130. ma_job_queue_config jobQueueConfig;
  54131. if (pResourceManager == NULL) {
  54132. return MA_INVALID_ARGS;
  54133. }
  54134. MA_ZERO_OBJECT(pResourceManager);
  54135. if (pConfig == NULL) {
  54136. return MA_INVALID_ARGS;
  54137. }
  54138. #ifndef MA_NO_THREADING
  54139. {
  54140. if (pConfig->jobThreadCount > ma_countof(pResourceManager->jobThreads)) {
  54141. return MA_INVALID_ARGS; /* Requesting too many job threads. */
  54142. }
  54143. }
  54144. #endif
  54145. pResourceManager->config = *pConfig;
  54146. ma_allocation_callbacks_init_copy(&pResourceManager->config.allocationCallbacks, &pConfig->allocationCallbacks);
  54147. /* Get the log set up early so we can start using it as soon as possible. */
  54148. if (pResourceManager->config.pLog == NULL) {
  54149. result = ma_log_init(&pResourceManager->config.allocationCallbacks, &pResourceManager->log);
  54150. if (result == MA_SUCCESS) {
  54151. pResourceManager->config.pLog = &pResourceManager->log;
  54152. } else {
  54153. pResourceManager->config.pLog = NULL; /* Logging is unavailable. */
  54154. }
  54155. }
  54156. if (pResourceManager->config.pVFS == NULL) {
  54157. result = ma_default_vfs_init(&pResourceManager->defaultVFS, &pResourceManager->config.allocationCallbacks);
  54158. if (result != MA_SUCCESS) {
  54159. return result; /* Failed to initialize the default file system. */
  54160. }
  54161. pResourceManager->config.pVFS = &pResourceManager->defaultVFS;
  54162. }
  54163. /* If threading has been disabled at compile time, enfore it at run time as well. */
  54164. #ifdef MA_NO_THREADING
  54165. {
  54166. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  54167. }
  54168. #endif
  54169. /* We need to force MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING if MA_RESOURCE_MANAGER_FLAG_NO_THREADING is set. */
  54170. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  54171. pResourceManager->config.flags |= MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING;
  54172. /* We cannot allow job threads when MA_RESOURCE_MANAGER_FLAG_NO_THREADING has been set. This is an invalid use case. */
  54173. if (pResourceManager->config.jobThreadCount > 0) {
  54174. return MA_INVALID_ARGS;
  54175. }
  54176. }
  54177. /* Job queue. */
  54178. jobQueueConfig.capacity = pResourceManager->config.jobQueueCapacity;
  54179. jobQueueConfig.flags = 0;
  54180. if ((pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NON_BLOCKING) != 0) {
  54181. if (pResourceManager->config.jobThreadCount > 0) {
  54182. return MA_INVALID_ARGS; /* Non-blocking mode is only valid for self-managed job threads. */
  54183. }
  54184. jobQueueConfig.flags |= MA_JOB_QUEUE_FLAG_NON_BLOCKING;
  54185. }
  54186. result = ma_job_queue_init(&jobQueueConfig, &pResourceManager->config.allocationCallbacks, &pResourceManager->jobQueue);
  54187. if (result != MA_SUCCESS) {
  54188. return result;
  54189. }
  54190. /* Custom decoding backends. */
  54191. if (pConfig->ppCustomDecodingBackendVTables != NULL && pConfig->customDecodingBackendCount > 0) {
  54192. size_t sizeInBytes = sizeof(*pResourceManager->config.ppCustomDecodingBackendVTables) * pConfig->customDecodingBackendCount;
  54193. pResourceManager->config.ppCustomDecodingBackendVTables = (ma_decoding_backend_vtable**)ma_malloc(sizeInBytes, &pResourceManager->config.allocationCallbacks);
  54194. if (pResourceManager->config.ppCustomDecodingBackendVTables == NULL) {
  54195. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  54196. return MA_OUT_OF_MEMORY;
  54197. }
  54198. MA_COPY_MEMORY(pResourceManager->config.ppCustomDecodingBackendVTables, pConfig->ppCustomDecodingBackendVTables, sizeInBytes);
  54199. pResourceManager->config.customDecodingBackendCount = pConfig->customDecodingBackendCount;
  54200. pResourceManager->config.pCustomDecodingBackendUserData = pConfig->pCustomDecodingBackendUserData;
  54201. }
  54202. /* Here is where we initialize our threading stuff. We don't do this if we don't support threading. */
  54203. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54204. #ifndef MA_NO_THREADING
  54205. {
  54206. ma_uint32 iJobThread;
  54207. /* Data buffer lock. */
  54208. result = ma_mutex_init(&pResourceManager->dataBufferBSTLock);
  54209. if (result != MA_SUCCESS) {
  54210. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  54211. return result;
  54212. }
  54213. /* Create the job threads last to ensure the threads has access to valid data. */
  54214. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  54215. result = ma_thread_create(&pResourceManager->jobThreads[iJobThread], ma_thread_priority_normal, 0, ma_resource_manager_job_thread, pResourceManager, &pResourceManager->config.allocationCallbacks);
  54216. if (result != MA_SUCCESS) {
  54217. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  54218. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  54219. return result;
  54220. }
  54221. }
  54222. }
  54223. #else
  54224. {
  54225. /* Threading is disabled at compile time. We should never get here because validation checks should have already been performed. */
  54226. MA_ASSERT(MA_FALSE);
  54227. }
  54228. #endif
  54229. }
  54230. return MA_SUCCESS;
  54231. }
  54232. static void ma_resource_manager_delete_all_data_buffer_nodes(ma_resource_manager* pResourceManager)
  54233. {
  54234. MA_ASSERT(pResourceManager);
  54235. /* If everything was done properly, there shouldn't be any active data buffers. */
  54236. while (pResourceManager->pRootDataBufferNode != NULL) {
  54237. ma_resource_manager_data_buffer_node* pDataBufferNode = pResourceManager->pRootDataBufferNode;
  54238. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  54239. /* The data buffer has been removed from the BST, so now we need to free it's data. */
  54240. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  54241. }
  54242. }
  54243. MA_API void ma_resource_manager_uninit(ma_resource_manager* pResourceManager)
  54244. {
  54245. if (pResourceManager == NULL) {
  54246. return;
  54247. }
  54248. /*
  54249. 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
  54250. queue which means it will never not be returned after being encounted for the first time which means all threads will eventually receive it.
  54251. */
  54252. ma_resource_manager_post_job_quit(pResourceManager);
  54253. /* Wait for every job to finish before continuing to ensure nothing is sill trying to access any of our objects below. */
  54254. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54255. #ifndef MA_NO_THREADING
  54256. {
  54257. ma_uint32 iJobThread;
  54258. for (iJobThread = 0; iJobThread < pResourceManager->config.jobThreadCount; iJobThread += 1) {
  54259. ma_thread_wait(&pResourceManager->jobThreads[iJobThread]);
  54260. }
  54261. }
  54262. #else
  54263. {
  54264. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  54265. }
  54266. #endif
  54267. }
  54268. /* At this point the thread should have returned and no other thread should be accessing our data. We can now delete all data buffers. */
  54269. ma_resource_manager_delete_all_data_buffer_nodes(pResourceManager);
  54270. /* The job queue is no longer needed. */
  54271. ma_job_queue_uninit(&pResourceManager->jobQueue, &pResourceManager->config.allocationCallbacks);
  54272. /* We're no longer doing anything with data buffers so the lock can now be uninitialized. */
  54273. if (ma_resource_manager_is_threading_enabled(pResourceManager)) {
  54274. #ifndef MA_NO_THREADING
  54275. {
  54276. ma_mutex_uninit(&pResourceManager->dataBufferBSTLock);
  54277. }
  54278. #else
  54279. {
  54280. MA_ASSERT(MA_FALSE); /* Should never hit this. */
  54281. }
  54282. #endif
  54283. }
  54284. ma_free(pResourceManager->config.ppCustomDecodingBackendVTables, &pResourceManager->config.allocationCallbacks);
  54285. if (pResourceManager->config.pLog == &pResourceManager->log) {
  54286. ma_log_uninit(&pResourceManager->log);
  54287. }
  54288. }
  54289. MA_API ma_log* ma_resource_manager_get_log(ma_resource_manager* pResourceManager)
  54290. {
  54291. if (pResourceManager == NULL) {
  54292. return NULL;
  54293. }
  54294. return pResourceManager->config.pLog;
  54295. }
  54296. MA_API ma_resource_manager_data_source_config ma_resource_manager_data_source_config_init(void)
  54297. {
  54298. ma_resource_manager_data_source_config config;
  54299. MA_ZERO_OBJECT(&config);
  54300. config.rangeEndInPCMFrames = ~((ma_uint64)0);
  54301. config.loopPointEndInPCMFrames = ~((ma_uint64)0);
  54302. return config;
  54303. }
  54304. static ma_decoder_config ma_resource_manager__init_decoder_config(ma_resource_manager* pResourceManager)
  54305. {
  54306. ma_decoder_config config;
  54307. config = ma_decoder_config_init(pResourceManager->config.decodedFormat, pResourceManager->config.decodedChannels, pResourceManager->config.decodedSampleRate);
  54308. config.allocationCallbacks = pResourceManager->config.allocationCallbacks;
  54309. config.ppCustomBackendVTables = pResourceManager->config.ppCustomDecodingBackendVTables;
  54310. config.customBackendCount = pResourceManager->config.customDecodingBackendCount;
  54311. config.pCustomBackendUserData = pResourceManager->config.pCustomDecodingBackendUserData;
  54312. return config;
  54313. }
  54314. static ma_result ma_resource_manager__init_decoder(ma_resource_manager* pResourceManager, const char* pFilePath, const wchar_t* pFilePathW, ma_decoder* pDecoder)
  54315. {
  54316. ma_result result;
  54317. ma_decoder_config config;
  54318. MA_ASSERT(pResourceManager != NULL);
  54319. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  54320. MA_ASSERT(pDecoder != NULL);
  54321. config = ma_resource_manager__init_decoder_config(pResourceManager);
  54322. if (pFilePath != NULL) {
  54323. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pFilePath, &config, pDecoder);
  54324. if (result != MA_SUCCESS) {
  54325. 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));
  54326. return result;
  54327. }
  54328. } else {
  54329. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pFilePathW, &config, pDecoder);
  54330. if (result != MA_SUCCESS) {
  54331. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  54332. 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));
  54333. #endif
  54334. return result;
  54335. }
  54336. }
  54337. return MA_SUCCESS;
  54338. }
  54339. static ma_data_source* ma_resource_manager_data_buffer_get_connector(ma_resource_manager_data_buffer* pDataBuffer)
  54340. {
  54341. switch (pDataBuffer->pNode->data.type)
  54342. {
  54343. case ma_resource_manager_data_supply_type_encoded: return &pDataBuffer->connector.decoder;
  54344. case ma_resource_manager_data_supply_type_decoded: return &pDataBuffer->connector.buffer;
  54345. case ma_resource_manager_data_supply_type_decoded_paged: return &pDataBuffer->connector.pagedBuffer;
  54346. case ma_resource_manager_data_supply_type_unknown:
  54347. default:
  54348. {
  54349. 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");
  54350. return NULL;
  54351. };
  54352. };
  54353. }
  54354. 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)
  54355. {
  54356. ma_result result;
  54357. MA_ASSERT(pDataBuffer != NULL);
  54358. MA_ASSERT(pConfig != NULL);
  54359. MA_ASSERT(pDataBuffer->isConnectorInitialized == MA_FALSE);
  54360. /* The underlying data buffer must be initialized before we'll be able to know how to initialize the backend. */
  54361. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  54362. if (result != MA_SUCCESS && result != MA_BUSY) {
  54363. return result; /* The data buffer is in an erroneous state. */
  54364. }
  54365. /*
  54366. 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
  54367. "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
  54368. an ma_audio_buffer. This enables us to use memory mapping when mixing which saves us a bit of data movement overhead.
  54369. */
  54370. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  54371. {
  54372. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  54373. {
  54374. ma_decoder_config config;
  54375. config = ma_resource_manager__init_decoder_config(pDataBuffer->pResourceManager);
  54376. result = ma_decoder_init_memory(pDataBuffer->pNode->data.backend.encoded.pData, pDataBuffer->pNode->data.backend.encoded.sizeInBytes, &config, &pDataBuffer->connector.decoder);
  54377. } break;
  54378. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  54379. {
  54380. ma_audio_buffer_config config;
  54381. 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);
  54382. result = ma_audio_buffer_init(&config, &pDataBuffer->connector.buffer);
  54383. } break;
  54384. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  54385. {
  54386. ma_paged_audio_buffer_config config;
  54387. config = ma_paged_audio_buffer_config_init(&pDataBuffer->pNode->data.backend.decodedPaged.data);
  54388. result = ma_paged_audio_buffer_init(&config, &pDataBuffer->connector.pagedBuffer);
  54389. } break;
  54390. case ma_resource_manager_data_supply_type_unknown:
  54391. default:
  54392. {
  54393. /* Unknown data supply type. Should never happen. Need to post an error here. */
  54394. return MA_INVALID_ARGS;
  54395. };
  54396. }
  54397. /*
  54398. Initialization of the connector is when we can fire the init notification. This will give the application access to
  54399. the format/channels/rate of the data source.
  54400. */
  54401. if (result == MA_SUCCESS) {
  54402. /*
  54403. Make sure the looping state is set before returning in order to handle the case where the
  54404. loop state was set on the data buffer before the connector was initialized.
  54405. */
  54406. ma_data_source_set_range_in_pcm_frames(pDataBuffer, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  54407. ma_data_source_set_loop_point_in_pcm_frames(pDataBuffer, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  54408. ma_data_source_set_looping(pDataBuffer, pConfig->isLooping);
  54409. pDataBuffer->isConnectorInitialized = MA_TRUE;
  54410. if (pInitNotification != NULL) {
  54411. ma_async_notification_signal(pInitNotification);
  54412. }
  54413. if (pInitFence != NULL) {
  54414. ma_fence_release(pInitFence);
  54415. }
  54416. }
  54417. /* 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. */
  54418. return result;
  54419. }
  54420. static ma_result ma_resource_manager_data_buffer_uninit_connector(ma_resource_manager* pResourceManager, ma_resource_manager_data_buffer* pDataBuffer)
  54421. {
  54422. MA_ASSERT(pResourceManager != NULL);
  54423. MA_ASSERT(pDataBuffer != NULL);
  54424. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  54425. {
  54426. case ma_resource_manager_data_supply_type_encoded: /* Connector is a decoder. */
  54427. {
  54428. ma_decoder_uninit(&pDataBuffer->connector.decoder);
  54429. } break;
  54430. case ma_resource_manager_data_supply_type_decoded: /* Connector is an audio buffer. */
  54431. {
  54432. ma_audio_buffer_uninit(&pDataBuffer->connector.buffer);
  54433. } break;
  54434. case ma_resource_manager_data_supply_type_decoded_paged: /* Connector is a paged audio buffer. */
  54435. {
  54436. ma_paged_audio_buffer_uninit(&pDataBuffer->connector.pagedBuffer);
  54437. } break;
  54438. case ma_resource_manager_data_supply_type_unknown:
  54439. default:
  54440. {
  54441. /* Unknown data supply type. Should never happen. Need to post an error here. */
  54442. return MA_INVALID_ARGS;
  54443. };
  54444. }
  54445. return MA_SUCCESS;
  54446. }
  54447. static ma_uint32 ma_resource_manager_data_buffer_node_next_execution_order(ma_resource_manager_data_buffer_node* pDataBufferNode)
  54448. {
  54449. MA_ASSERT(pDataBufferNode != NULL);
  54450. return c89atomic_fetch_add_32(&pDataBufferNode->executionCounter, 1);
  54451. }
  54452. 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)
  54453. {
  54454. ma_result result;
  54455. size_t dataSizeInBytes;
  54456. void* pData;
  54457. MA_ASSERT(pResourceManager != NULL);
  54458. MA_ASSERT(pDataBufferNode != NULL);
  54459. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  54460. result = ma_vfs_open_and_read_file_ex(pResourceManager->config.pVFS, pFilePath, pFilePathW, &pData, &dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  54461. if (result != MA_SUCCESS) {
  54462. if (pFilePath != NULL) {
  54463. 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));
  54464. } else {
  54465. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  54466. 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));
  54467. #endif
  54468. }
  54469. return result;
  54470. }
  54471. pDataBufferNode->data.backend.encoded.pData = pData;
  54472. pDataBufferNode->data.backend.encoded.sizeInBytes = dataSizeInBytes;
  54473. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_encoded); /* <-- Must be set last. */
  54474. return MA_SUCCESS;
  54475. }
  54476. 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)
  54477. {
  54478. ma_result result = MA_SUCCESS;
  54479. ma_decoder* pDecoder;
  54480. ma_uint64 totalFrameCount;
  54481. MA_ASSERT(pResourceManager != NULL);
  54482. MA_ASSERT(pDataBufferNode != NULL);
  54483. MA_ASSERT(ppDecoder != NULL);
  54484. MA_ASSERT(pFilePath != NULL || pFilePathW != NULL);
  54485. *ppDecoder = NULL; /* For safety. */
  54486. pDecoder = (ma_decoder*)ma_malloc(sizeof(*pDecoder), &pResourceManager->config.allocationCallbacks);
  54487. if (pDecoder == NULL) {
  54488. return MA_OUT_OF_MEMORY;
  54489. }
  54490. result = ma_resource_manager__init_decoder(pResourceManager, pFilePath, pFilePathW, pDecoder);
  54491. if (result != MA_SUCCESS) {
  54492. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  54493. return result;
  54494. }
  54495. /*
  54496. At this point we have the decoder and we now need to initialize the data supply. This will
  54497. be either a decoded buffer, or a decoded paged buffer. A regular buffer is just one big heap
  54498. allocated buffer, whereas a paged buffer is a linked list of paged-sized buffers. The latter
  54499. is used when the length of a sound is unknown until a full decode has been performed.
  54500. */
  54501. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  54502. result = ma_decoder_get_length_in_pcm_frames(pDecoder, &totalFrameCount);
  54503. if (result != MA_SUCCESS) {
  54504. return result;
  54505. }
  54506. } else {
  54507. totalFrameCount = 0;
  54508. }
  54509. if (totalFrameCount > 0) {
  54510. /* It's a known length. The data supply is a regular decoded buffer. */
  54511. ma_uint64 dataSizeInBytes;
  54512. void* pData;
  54513. dataSizeInBytes = totalFrameCount * ma_get_bytes_per_frame(pDecoder->outputFormat, pDecoder->outputChannels);
  54514. if (dataSizeInBytes > MA_SIZE_MAX) {
  54515. ma_decoder_uninit(pDecoder);
  54516. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  54517. return MA_TOO_BIG;
  54518. }
  54519. pData = ma_malloc((size_t)dataSizeInBytes, &pResourceManager->config.allocationCallbacks);
  54520. if (pData == NULL) {
  54521. ma_decoder_uninit(pDecoder);
  54522. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  54523. return MA_OUT_OF_MEMORY;
  54524. }
  54525. /* The buffer needs to be initialized to silence in case the caller reads from it. */
  54526. ma_silence_pcm_frames(pData, totalFrameCount, pDecoder->outputFormat, pDecoder->outputChannels);
  54527. /* Data has been allocated and the data supply can now be initialized. */
  54528. pDataBufferNode->data.backend.decoded.pData = pData;
  54529. pDataBufferNode->data.backend.decoded.totalFrameCount = totalFrameCount;
  54530. pDataBufferNode->data.backend.decoded.format = pDecoder->outputFormat;
  54531. pDataBufferNode->data.backend.decoded.channels = pDecoder->outputChannels;
  54532. pDataBufferNode->data.backend.decoded.sampleRate = pDecoder->outputSampleRate;
  54533. pDataBufferNode->data.backend.decoded.decodedFrameCount = 0;
  54534. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded); /* <-- Must be set last. */
  54535. } else {
  54536. /*
  54537. It's an unknown length. The data supply is a paged decoded buffer. Setting this up is
  54538. actually easier than the non-paged decoded buffer because we just need to initialize
  54539. a ma_paged_audio_buffer object.
  54540. */
  54541. result = ma_paged_audio_buffer_data_init(pDecoder->outputFormat, pDecoder->outputChannels, &pDataBufferNode->data.backend.decodedPaged.data);
  54542. if (result != MA_SUCCESS) {
  54543. ma_decoder_uninit(pDecoder);
  54544. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  54545. return result;
  54546. }
  54547. pDataBufferNode->data.backend.decodedPaged.sampleRate = pDecoder->outputSampleRate;
  54548. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount = 0;
  54549. ma_resource_manager_data_buffer_node_set_data_supply_type(pDataBufferNode, ma_resource_manager_data_supply_type_decoded_paged); /* <-- Must be set last. */
  54550. }
  54551. *ppDecoder = pDecoder;
  54552. return MA_SUCCESS;
  54553. }
  54554. 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)
  54555. {
  54556. ma_result result = MA_SUCCESS;
  54557. ma_uint64 pageSizeInFrames;
  54558. ma_uint64 framesToTryReading;
  54559. ma_uint64 framesRead;
  54560. MA_ASSERT(pResourceManager != NULL);
  54561. MA_ASSERT(pDataBufferNode != NULL);
  54562. MA_ASSERT(pDecoder != NULL);
  54563. /* We need to know the size of a page in frames to know how many frames to decode. */
  54564. pageSizeInFrames = MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDecoder->outputSampleRate/1000);
  54565. framesToTryReading = pageSizeInFrames;
  54566. /*
  54567. Here is where we do the decoding of the next page. We'll run a slightly different path depending
  54568. on whether or not we're using a flat or paged buffer because the allocation of the page differs
  54569. between the two. For a flat buffer it's an offset to an already-allocated buffer. For a paged
  54570. buffer, we need to allocate a new page and attach it to the linked list.
  54571. */
  54572. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBufferNode))
  54573. {
  54574. case ma_resource_manager_data_supply_type_decoded:
  54575. {
  54576. /* The destination buffer is an offset to the existing buffer. Don't read more than we originally retrieved when we first initialized the decoder. */
  54577. void* pDst;
  54578. ma_uint64 framesRemaining = pDataBufferNode->data.backend.decoded.totalFrameCount - pDataBufferNode->data.backend.decoded.decodedFrameCount;
  54579. if (framesToTryReading > framesRemaining) {
  54580. framesToTryReading = framesRemaining;
  54581. }
  54582. if (framesToTryReading > 0) {
  54583. pDst = ma_offset_ptr(
  54584. pDataBufferNode->data.backend.decoded.pData,
  54585. pDataBufferNode->data.backend.decoded.decodedFrameCount * ma_get_bytes_per_frame(pDataBufferNode->data.backend.decoded.format, pDataBufferNode->data.backend.decoded.channels)
  54586. );
  54587. MA_ASSERT(pDst != NULL);
  54588. result = ma_decoder_read_pcm_frames(pDecoder, pDst, framesToTryReading, &framesRead);
  54589. if (framesRead > 0) {
  54590. pDataBufferNode->data.backend.decoded.decodedFrameCount += framesRead;
  54591. }
  54592. } else {
  54593. framesRead = 0;
  54594. }
  54595. } break;
  54596. case ma_resource_manager_data_supply_type_decoded_paged:
  54597. {
  54598. /* The destination buffer is a freshly allocated page. */
  54599. ma_paged_audio_buffer_page* pPage;
  54600. result = ma_paged_audio_buffer_data_allocate_page(&pDataBufferNode->data.backend.decodedPaged.data, framesToTryReading, NULL, &pResourceManager->config.allocationCallbacks, &pPage);
  54601. if (result != MA_SUCCESS) {
  54602. return result;
  54603. }
  54604. result = ma_decoder_read_pcm_frames(pDecoder, pPage->pAudioData, framesToTryReading, &framesRead);
  54605. if (framesRead > 0) {
  54606. pPage->sizeInFrames = framesRead;
  54607. result = ma_paged_audio_buffer_data_append_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage);
  54608. if (result == MA_SUCCESS) {
  54609. pDataBufferNode->data.backend.decodedPaged.decodedFrameCount += framesRead;
  54610. } else {
  54611. /* Failed to append the page. Just abort and set the status to MA_AT_END. */
  54612. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  54613. result = MA_AT_END;
  54614. }
  54615. } else {
  54616. /* No frames were read. Free the page and just set the status to MA_AT_END. */
  54617. ma_paged_audio_buffer_data_free_page(&pDataBufferNode->data.backend.decodedPaged.data, pPage, &pResourceManager->config.allocationCallbacks);
  54618. result = MA_AT_END;
  54619. }
  54620. } break;
  54621. case ma_resource_manager_data_supply_type_encoded:
  54622. case ma_resource_manager_data_supply_type_unknown:
  54623. default:
  54624. {
  54625. /* Unexpected data supply type. */
  54626. 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));
  54627. return MA_ERROR;
  54628. };
  54629. }
  54630. if (result == MA_SUCCESS && framesRead == 0) {
  54631. result = MA_AT_END;
  54632. }
  54633. return result;
  54634. }
  54635. 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)
  54636. {
  54637. ma_result result = MA_SUCCESS;
  54638. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  54639. ma_resource_manager_data_buffer_node* pInsertPoint;
  54640. if (ppDataBufferNode != NULL) {
  54641. *ppDataBufferNode = NULL;
  54642. }
  54643. result = ma_resource_manager_data_buffer_node_insert_point(pResourceManager, hashedName32, &pInsertPoint);
  54644. if (result == MA_ALREADY_EXISTS) {
  54645. /* The node already exists. We just need to increment the reference count. */
  54646. pDataBufferNode = pInsertPoint;
  54647. result = ma_resource_manager_data_buffer_node_increment_ref(pResourceManager, pDataBufferNode, NULL);
  54648. if (result != MA_SUCCESS) {
  54649. return result; /* Should never happen. Failed to increment the reference count. */
  54650. }
  54651. result = MA_ALREADY_EXISTS;
  54652. goto done;
  54653. } else {
  54654. /*
  54655. The node does not already exist. We need to post a LOAD_DATA_BUFFER_NODE job here. This
  54656. needs to be done inside the critical section to ensure an uninitialization of the node
  54657. does not occur before initialization on another thread.
  54658. */
  54659. pDataBufferNode = (ma_resource_manager_data_buffer_node*)ma_malloc(sizeof(*pDataBufferNode), &pResourceManager->config.allocationCallbacks);
  54660. if (pDataBufferNode == NULL) {
  54661. return MA_OUT_OF_MEMORY;
  54662. }
  54663. MA_ZERO_OBJECT(pDataBufferNode);
  54664. pDataBufferNode->hashedName32 = hashedName32;
  54665. pDataBufferNode->refCount = 1; /* Always set to 1 by default (this is our first reference). */
  54666. if (pExistingData == NULL) {
  54667. pDataBufferNode->data.type = ma_resource_manager_data_supply_type_unknown; /* <-- We won't know this until we start decoding. */
  54668. pDataBufferNode->result = MA_BUSY; /* Must be set to MA_BUSY before we leave the critical section, so might as well do it now. */
  54669. pDataBufferNode->isDataOwnedByResourceManager = MA_TRUE;
  54670. } else {
  54671. pDataBufferNode->data = *pExistingData;
  54672. pDataBufferNode->result = MA_SUCCESS; /* Not loading asynchronously, so just set the status */
  54673. pDataBufferNode->isDataOwnedByResourceManager = MA_FALSE;
  54674. }
  54675. result = ma_resource_manager_data_buffer_node_insert_at(pResourceManager, pDataBufferNode, pInsertPoint);
  54676. if (result != MA_SUCCESS) {
  54677. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  54678. return result; /* Should never happen. Failed to insert the data buffer into the BST. */
  54679. }
  54680. /*
  54681. Here is where we'll post the job, but only if we're loading asynchronously. If we're
  54682. loading synchronously we'll defer loading to a later stage, outside of the critical
  54683. section.
  54684. */
  54685. if (pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  54686. /* Loading asynchronously. Post the job. */
  54687. ma_job job;
  54688. char* pFilePathCopy = NULL;
  54689. wchar_t* pFilePathWCopy = NULL;
  54690. /* 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. */
  54691. if (pFilePath != NULL) {
  54692. pFilePathCopy = ma_copy_string(pFilePath, &pResourceManager->config.allocationCallbacks);
  54693. } else {
  54694. pFilePathWCopy = ma_copy_string_w(pFilePathW, &pResourceManager->config.allocationCallbacks);
  54695. }
  54696. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  54697. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  54698. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  54699. return MA_OUT_OF_MEMORY;
  54700. }
  54701. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  54702. ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification);
  54703. }
  54704. /* Acquire init and done fences before posting the job. These will be unacquired by the job thread. */
  54705. if (pInitFence != NULL) { ma_fence_acquire(pInitFence); }
  54706. if (pDoneFence != NULL) { ma_fence_acquire(pDoneFence); }
  54707. /* We now have everything we need to post the job to the job thread. */
  54708. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER_NODE);
  54709. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  54710. job.data.resourceManager.loadDataBufferNode.pResourceManager = pResourceManager;
  54711. job.data.resourceManager.loadDataBufferNode.pDataBufferNode = pDataBufferNode;
  54712. job.data.resourceManager.loadDataBufferNode.pFilePath = pFilePathCopy;
  54713. job.data.resourceManager.loadDataBufferNode.pFilePathW = pFilePathWCopy;
  54714. job.data.resourceManager.loadDataBufferNode.flags = flags;
  54715. job.data.resourceManager.loadDataBufferNode.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? pInitNotification : NULL;
  54716. job.data.resourceManager.loadDataBufferNode.pDoneNotification = NULL;
  54717. job.data.resourceManager.loadDataBufferNode.pInitFence = pInitFence;
  54718. job.data.resourceManager.loadDataBufferNode.pDoneFence = pDoneFence;
  54719. result = ma_resource_manager_post_job(pResourceManager, &job);
  54720. if (result != MA_SUCCESS) {
  54721. /* Failed to post job. Probably ran out of memory. */
  54722. 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));
  54723. /*
  54724. Fences were acquired before posting the job, but since the job was not able to
  54725. be posted, we need to make sure we release them so nothing gets stuck waiting.
  54726. */
  54727. if (pInitFence != NULL) { ma_fence_release(pInitFence); }
  54728. if (pDoneFence != NULL) { ma_fence_release(pDoneFence); }
  54729. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  54730. ma_resource_manager_inline_notification_init(pResourceManager, pInitNotification);
  54731. }
  54732. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  54733. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  54734. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  54735. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  54736. return result;
  54737. }
  54738. }
  54739. }
  54740. done:
  54741. if (ppDataBufferNode != NULL) {
  54742. *ppDataBufferNode = pDataBufferNode;
  54743. }
  54744. return result;
  54745. }
  54746. 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)
  54747. {
  54748. ma_result result = MA_SUCCESS;
  54749. ma_bool32 nodeAlreadyExists = MA_FALSE;
  54750. ma_resource_manager_data_buffer_node* pDataBufferNode = NULL;
  54751. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  54752. if (ppDataBufferNode != NULL) {
  54753. *ppDataBufferNode = NULL; /* Safety. */
  54754. }
  54755. if (pResourceManager == NULL || (pFilePath == NULL && pFilePathW == NULL && hashedName32 == 0)) {
  54756. return MA_INVALID_ARGS;
  54757. }
  54758. /* If we're specifying existing data, it must be valid. */
  54759. if (pExistingData != NULL && pExistingData->type == ma_resource_manager_data_supply_type_unknown) {
  54760. return MA_INVALID_ARGS;
  54761. }
  54762. /* If we don't support threading, remove the ASYNC flag to make the rest of this a bit simpler. */
  54763. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  54764. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  54765. }
  54766. if (hashedName32 == 0) {
  54767. if (pFilePath != NULL) {
  54768. hashedName32 = ma_hash_string_32(pFilePath);
  54769. } else {
  54770. hashedName32 = ma_hash_string_w_32(pFilePathW);
  54771. }
  54772. }
  54773. /*
  54774. Here is where we either increment the node's reference count or allocate a new one and add it
  54775. to the BST. When allocating a new node, we need to make sure the LOAD_DATA_BUFFER_NODE job is
  54776. posted inside the critical section just in case the caller immediately uninitializes the node
  54777. as this will ensure the FREE_DATA_BUFFER_NODE job is given an execution order such that the
  54778. node is not uninitialized before initialization.
  54779. */
  54780. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  54781. {
  54782. result = ma_resource_manager_data_buffer_node_acquire_critical_section(pResourceManager, pFilePath, pFilePathW, hashedName32, flags, pExistingData, pInitFence, pDoneFence, &initNotification, &pDataBufferNode);
  54783. }
  54784. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  54785. if (result == MA_ALREADY_EXISTS) {
  54786. nodeAlreadyExists = MA_TRUE;
  54787. result = MA_SUCCESS;
  54788. } else {
  54789. if (result != MA_SUCCESS) {
  54790. return result;
  54791. }
  54792. }
  54793. /*
  54794. If we're loading synchronously, we'll need to load everything now. When loading asynchronously,
  54795. a job will have been posted inside the BST critical section so that an uninitialization can be
  54796. allocated an appropriate execution order thereby preventing it from being uninitialized before
  54797. the node is initialized by the decoding thread(s).
  54798. */
  54799. if (nodeAlreadyExists == MA_FALSE) { /* Don't need to try loading anything if the node already exists. */
  54800. if (pFilePath == NULL && pFilePathW == NULL) {
  54801. /*
  54802. If this path is hit, it means a buffer is being copied (i.e. initialized from only the
  54803. hashed name), but that node has been freed in the meantime, probably from some other
  54804. thread. This is an invalid operation.
  54805. */
  54806. 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");
  54807. result = MA_INVALID_OPERATION;
  54808. goto done;
  54809. }
  54810. if (pDataBufferNode->isDataOwnedByResourceManager) {
  54811. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0) {
  54812. /* Loading synchronously. Load the sound in it's entirety here. */
  54813. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) == 0) {
  54814. /* No decoding. This is the simple case - just store the file contents in memory. */
  54815. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW);
  54816. if (result != MA_SUCCESS) {
  54817. goto done;
  54818. }
  54819. } else {
  54820. /* Decoding. We do this the same way as we do when loading asynchronously. */
  54821. ma_decoder* pDecoder;
  54822. result = ma_resource_manager_data_buffer_node_init_supply_decoded(pResourceManager, pDataBufferNode, pFilePath, pFilePathW, flags, &pDecoder);
  54823. if (result != MA_SUCCESS) {
  54824. goto done;
  54825. }
  54826. /* We have the decoder, now decode page by page just like we do when loading asynchronously. */
  54827. for (;;) {
  54828. /* Decode next page. */
  54829. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, pDecoder);
  54830. if (result != MA_SUCCESS) {
  54831. break; /* Will return MA_AT_END when the last page has been decoded. */
  54832. }
  54833. }
  54834. /* Reaching the end needs to be considered successful. */
  54835. if (result == MA_AT_END) {
  54836. result = MA_SUCCESS;
  54837. }
  54838. /*
  54839. At this point the data buffer is either fully decoded or some error occurred. Either
  54840. way, the decoder is no longer necessary.
  54841. */
  54842. ma_decoder_uninit(pDecoder);
  54843. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  54844. }
  54845. /* Getting here means we were successful. Make sure the status of the node is updated accordingly. */
  54846. c89atomic_exchange_i32(&pDataBufferNode->result, result);
  54847. } else {
  54848. /* Loading asynchronously. We may need to wait for initialization. */
  54849. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  54850. ma_resource_manager_inline_notification_wait(&initNotification);
  54851. }
  54852. }
  54853. } else {
  54854. /* The data is not managed by the resource manager so there's nothing else to do. */
  54855. MA_ASSERT(pExistingData != NULL);
  54856. }
  54857. }
  54858. done:
  54859. /* If we failed to initialize the data buffer we need to free it. */
  54860. if (result != MA_SUCCESS) {
  54861. if (nodeAlreadyExists == MA_FALSE) {
  54862. ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  54863. ma_free(pDataBufferNode, &pResourceManager->config.allocationCallbacks);
  54864. }
  54865. }
  54866. /*
  54867. The init notification needs to be uninitialized. This will be used if the node does not already
  54868. exist, and we've specified ASYNC | WAIT_INIT.
  54869. */
  54870. if (nodeAlreadyExists == MA_FALSE && pDataBufferNode->isDataOwnedByResourceManager && (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0) {
  54871. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  54872. ma_resource_manager_inline_notification_uninit(&initNotification);
  54873. }
  54874. }
  54875. if (ppDataBufferNode != NULL) {
  54876. *ppDataBufferNode = pDataBufferNode;
  54877. }
  54878. return result;
  54879. }
  54880. 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)
  54881. {
  54882. ma_result result = MA_SUCCESS;
  54883. 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. */
  54884. ma_uint32 hashedName32 = 0;
  54885. if (pResourceManager == NULL) {
  54886. return MA_INVALID_ARGS;
  54887. }
  54888. if (pDataBufferNode == NULL) {
  54889. if (pName == NULL && pNameW == NULL) {
  54890. return MA_INVALID_ARGS;
  54891. }
  54892. if (pName != NULL) {
  54893. hashedName32 = ma_hash_string_32(pName);
  54894. } else {
  54895. hashedName32 = ma_hash_string_w_32(pNameW);
  54896. }
  54897. }
  54898. /*
  54899. The first thing to do is decrement the reference counter of the node. Then, if the reference
  54900. count is zero, we need to free the node. If the node is still in the process of loading, we'll
  54901. need to post a job to the job queue to free the node. Otherwise we'll just do it here.
  54902. */
  54903. ma_resource_manager_data_buffer_bst_lock(pResourceManager);
  54904. {
  54905. /* Might need to find the node. Must be done inside the critical section. */
  54906. if (pDataBufferNode == NULL) {
  54907. result = ma_resource_manager_data_buffer_node_search(pResourceManager, hashedName32, &pDataBufferNode);
  54908. if (result != MA_SUCCESS) {
  54909. goto stage2; /* Couldn't find the node. */
  54910. }
  54911. }
  54912. result = ma_resource_manager_data_buffer_node_decrement_ref(pResourceManager, pDataBufferNode, &refCount);
  54913. if (result != MA_SUCCESS) {
  54914. goto stage2; /* Should never happen. */
  54915. }
  54916. if (refCount == 0) {
  54917. result = ma_resource_manager_data_buffer_node_remove(pResourceManager, pDataBufferNode);
  54918. if (result != MA_SUCCESS) {
  54919. goto stage2; /* An error occurred when trying to remove the data buffer. This should never happen. */
  54920. }
  54921. }
  54922. }
  54923. ma_resource_manager_data_buffer_bst_unlock(pResourceManager);
  54924. stage2:
  54925. if (result != MA_SUCCESS) {
  54926. return result;
  54927. }
  54928. /*
  54929. Here is where we need to free the node. We don't want to do this inside the critical section
  54930. above because we want to keep that as small as possible for multi-threaded efficiency.
  54931. */
  54932. if (refCount == 0) {
  54933. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  54934. /* The sound is still loading. We need to delay the freeing of the node to a safe time. */
  54935. ma_job job;
  54936. /* We need to mark the node as unavailable for the sake of the resource manager worker threads. */
  54937. c89atomic_exchange_i32(&pDataBufferNode->result, MA_UNAVAILABLE);
  54938. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER_NODE);
  54939. job.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  54940. job.data.resourceManager.freeDataBufferNode.pResourceManager = pResourceManager;
  54941. job.data.resourceManager.freeDataBufferNode.pDataBufferNode = pDataBufferNode;
  54942. result = ma_resource_manager_post_job(pResourceManager, &job);
  54943. if (result != MA_SUCCESS) {
  54944. 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));
  54945. return result;
  54946. }
  54947. /* If we don't support threading, process the job queue here. */
  54948. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  54949. while (ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_BUSY) {
  54950. result = ma_resource_manager_process_next_job(pResourceManager);
  54951. if (result == MA_NO_DATA_AVAILABLE || result == MA_CANCELLED) {
  54952. result = MA_SUCCESS;
  54953. break;
  54954. }
  54955. }
  54956. } else {
  54957. /* Threading is enabled. The job queue will deal with the rest of the cleanup from here. */
  54958. }
  54959. } else {
  54960. /* The sound isn't loading so we can just free the node here. */
  54961. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  54962. }
  54963. }
  54964. return result;
  54965. }
  54966. static ma_uint32 ma_resource_manager_data_buffer_next_execution_order(ma_resource_manager_data_buffer* pDataBuffer)
  54967. {
  54968. MA_ASSERT(pDataBuffer != NULL);
  54969. return c89atomic_fetch_add_32(&pDataBuffer->executionCounter, 1);
  54970. }
  54971. static ma_result ma_resource_manager_data_buffer_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  54972. {
  54973. return ma_resource_manager_data_buffer_read_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pFramesOut, frameCount, pFramesRead);
  54974. }
  54975. static ma_result ma_resource_manager_data_buffer_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  54976. {
  54977. return ma_resource_manager_data_buffer_seek_to_pcm_frame((ma_resource_manager_data_buffer*)pDataSource, frameIndex);
  54978. }
  54979. 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)
  54980. {
  54981. return ma_resource_manager_data_buffer_get_data_format((ma_resource_manager_data_buffer*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  54982. }
  54983. static ma_result ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  54984. {
  54985. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pCursor);
  54986. }
  54987. static ma_result ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  54988. {
  54989. return ma_resource_manager_data_buffer_get_length_in_pcm_frames((ma_resource_manager_data_buffer*)pDataSource, pLength);
  54990. }
  54991. static ma_result ma_resource_manager_data_buffer_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  54992. {
  54993. ma_resource_manager_data_buffer* pDataBuffer = (ma_resource_manager_data_buffer*)pDataSource;
  54994. MA_ASSERT(pDataBuffer != NULL);
  54995. c89atomic_exchange_32(&pDataBuffer->isLooping, isLooping);
  54996. /* The looping state needs to be set on the connector as well or else looping won't work when we read audio data. */
  54997. ma_data_source_set_looping(ma_resource_manager_data_buffer_get_connector(pDataBuffer), isLooping);
  54998. return MA_SUCCESS;
  54999. }
  55000. static ma_data_source_vtable g_ma_resource_manager_data_buffer_vtable =
  55001. {
  55002. ma_resource_manager_data_buffer_cb__read_pcm_frames,
  55003. ma_resource_manager_data_buffer_cb__seek_to_pcm_frame,
  55004. ma_resource_manager_data_buffer_cb__get_data_format,
  55005. ma_resource_manager_data_buffer_cb__get_cursor_in_pcm_frames,
  55006. ma_resource_manager_data_buffer_cb__get_length_in_pcm_frames,
  55007. ma_resource_manager_data_buffer_cb__set_looping,
  55008. 0
  55009. };
  55010. 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)
  55011. {
  55012. ma_result result = MA_SUCCESS;
  55013. ma_resource_manager_data_buffer_node* pDataBufferNode;
  55014. ma_data_source_config dataSourceConfig;
  55015. ma_bool32 async;
  55016. ma_uint32 flags;
  55017. ma_resource_manager_pipeline_notifications notifications;
  55018. if (pDataBuffer == NULL) {
  55019. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  55020. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  55021. }
  55022. return MA_INVALID_ARGS;
  55023. }
  55024. MA_ZERO_OBJECT(pDataBuffer);
  55025. if (pConfig == NULL) {
  55026. return MA_INVALID_ARGS;
  55027. }
  55028. if (pConfig->pNotifications != NULL) {
  55029. 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. */
  55030. } else {
  55031. MA_ZERO_OBJECT(&notifications);
  55032. }
  55033. /* For safety, always remove the ASYNC flag if threading is disabled on the resource manager. */
  55034. flags = pConfig->flags;
  55035. if (ma_resource_manager_is_threading_enabled(pResourceManager) == MA_FALSE) {
  55036. flags &= ~MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC;
  55037. }
  55038. async = (flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) != 0;
  55039. /*
  55040. Fences need to be acquired before doing anything. These must be aquired and released outside of
  55041. the node to ensure there's no holes where ma_fence_wait() could prematurely return before the
  55042. data buffer has completed initialization.
  55043. When loading asynchronously, the node acquisition routine below will acquire the fences on this
  55044. thread and then release them on the async thread when the operation is complete.
  55045. These fences are always released at the "done" tag at the end of this function. They'll be
  55046. acquired a second if loading asynchronously. This double acquisition system is just done to
  55047. simplify code maintanence.
  55048. */
  55049. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  55050. {
  55051. /* We first need to acquire a node. If ASYNC is not set, this will not return until the entire sound has been loaded. */
  55052. result = ma_resource_manager_data_buffer_node_acquire(pResourceManager, pConfig->pFilePath, pConfig->pFilePathW, hashedName32, flags, NULL, notifications.init.pFence, notifications.done.pFence, &pDataBufferNode);
  55053. if (result != MA_SUCCESS) {
  55054. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55055. goto done;
  55056. }
  55057. dataSourceConfig = ma_data_source_config_init();
  55058. dataSourceConfig.vtable = &g_ma_resource_manager_data_buffer_vtable;
  55059. result = ma_data_source_init(&dataSourceConfig, &pDataBuffer->ds);
  55060. if (result != MA_SUCCESS) {
  55061. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  55062. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55063. goto done;
  55064. }
  55065. pDataBuffer->pResourceManager = pResourceManager;
  55066. pDataBuffer->pNode = pDataBufferNode;
  55067. pDataBuffer->flags = flags;
  55068. pDataBuffer->result = MA_BUSY; /* Always default to MA_BUSY for safety. It'll be overwritten when loading completes or an error occurs. */
  55069. /* If we're loading asynchronously we need to post a job to the job queue to initialize the connector. */
  55070. if (async == MA_FALSE || ma_resource_manager_data_buffer_node_result(pDataBufferNode) == MA_SUCCESS) {
  55071. /* Loading synchronously or the data has already been fully loaded. We can just initialize the connector from here without a job. */
  55072. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, pConfig, NULL, NULL);
  55073. c89atomic_exchange_i32(&pDataBuffer->result, result);
  55074. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55075. goto done;
  55076. } else {
  55077. /* 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. */
  55078. ma_job job;
  55079. ma_resource_manager_inline_notification initNotification; /* Used when the WAIT_INIT flag is set. */
  55080. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  55081. ma_resource_manager_inline_notification_init(pResourceManager, &initNotification);
  55082. }
  55083. /*
  55084. The status of the data buffer needs to be set to MA_BUSY before posting the job so that the
  55085. worker thread is aware of it's busy state. If the LOAD_DATA_BUFFER job sees a status other
  55086. than MA_BUSY, it'll assume an error and fall through to an early exit.
  55087. */
  55088. c89atomic_exchange_i32(&pDataBuffer->result, MA_BUSY);
  55089. /* Acquire fences a second time. These will be released by the async thread. */
  55090. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  55091. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_BUFFER);
  55092. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  55093. job.data.resourceManager.loadDataBuffer.pDataBuffer = pDataBuffer;
  55094. job.data.resourceManager.loadDataBuffer.pInitNotification = ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) ? &initNotification : notifications.init.pNotification;
  55095. job.data.resourceManager.loadDataBuffer.pDoneNotification = notifications.done.pNotification;
  55096. job.data.resourceManager.loadDataBuffer.pInitFence = notifications.init.pFence;
  55097. job.data.resourceManager.loadDataBuffer.pDoneFence = notifications.done.pFence;
  55098. job.data.resourceManager.loadDataBuffer.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  55099. job.data.resourceManager.loadDataBuffer.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  55100. job.data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  55101. job.data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  55102. job.data.resourceManager.loadDataBuffer.isLooping = pConfig->isLooping;
  55103. result = ma_resource_manager_post_job(pResourceManager, &job);
  55104. if (result != MA_SUCCESS) {
  55105. /* We failed to post the job. Most likely there isn't enough room in the queue's buffer. */
  55106. 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));
  55107. c89atomic_exchange_i32(&pDataBuffer->result, result);
  55108. /* Release the fences after the result has been set on the data buffer. */
  55109. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  55110. } else {
  55111. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  55112. ma_resource_manager_inline_notification_wait(&initNotification);
  55113. if (notifications.init.pNotification != NULL) {
  55114. ma_async_notification_signal(notifications.init.pNotification);
  55115. }
  55116. /* NOTE: Do not release the init fence here. It will have been done by the job. */
  55117. /* Make sure we return an error if initialization failed on the async thread. */
  55118. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  55119. if (result == MA_BUSY) {
  55120. result = MA_SUCCESS;
  55121. }
  55122. }
  55123. }
  55124. if ((flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  55125. ma_resource_manager_inline_notification_uninit(&initNotification);
  55126. }
  55127. }
  55128. if (result != MA_SUCCESS) {
  55129. ma_resource_manager_data_buffer_node_unacquire(pResourceManager, pDataBufferNode, NULL, NULL);
  55130. goto done;
  55131. }
  55132. }
  55133. done:
  55134. if (result == MA_SUCCESS) {
  55135. if (pConfig->initialSeekPointInPCMFrames > 0) {
  55136. ma_resource_manager_data_buffer_seek_to_pcm_frame(pDataBuffer, pConfig->initialSeekPointInPCMFrames);
  55137. }
  55138. }
  55139. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  55140. return result;
  55141. }
  55142. 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)
  55143. {
  55144. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, pConfig, 0, pDataBuffer);
  55145. }
  55146. 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)
  55147. {
  55148. ma_resource_manager_data_source_config config;
  55149. config = ma_resource_manager_data_source_config_init();
  55150. config.pFilePath = pFilePath;
  55151. config.flags = flags;
  55152. config.pNotifications = pNotifications;
  55153. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  55154. }
  55155. 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)
  55156. {
  55157. ma_resource_manager_data_source_config config;
  55158. config = ma_resource_manager_data_source_config_init();
  55159. config.pFilePathW = pFilePath;
  55160. config.flags = flags;
  55161. config.pNotifications = pNotifications;
  55162. return ma_resource_manager_data_buffer_init_ex(pResourceManager, &config, pDataBuffer);
  55163. }
  55164. 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)
  55165. {
  55166. ma_resource_manager_data_source_config config;
  55167. if (pExistingDataBuffer == NULL) {
  55168. return MA_INVALID_ARGS;
  55169. }
  55170. MA_ASSERT(pExistingDataBuffer->pNode != NULL); /* <-- If you've triggered this, you've passed in an invalid existing data buffer. */
  55171. config = ma_resource_manager_data_source_config_init();
  55172. config.flags = pExistingDataBuffer->flags;
  55173. return ma_resource_manager_data_buffer_init_ex_internal(pResourceManager, &config, pExistingDataBuffer->pNode->hashedName32, pDataBuffer);
  55174. }
  55175. static ma_result ma_resource_manager_data_buffer_uninit_internal(ma_resource_manager_data_buffer* pDataBuffer)
  55176. {
  55177. MA_ASSERT(pDataBuffer != NULL);
  55178. /* The connector should be uninitialized first. */
  55179. ma_resource_manager_data_buffer_uninit_connector(pDataBuffer->pResourceManager, pDataBuffer);
  55180. /* With the connector uninitialized we can unacquire the node. */
  55181. ma_resource_manager_data_buffer_node_unacquire(pDataBuffer->pResourceManager, pDataBuffer->pNode, NULL, NULL);
  55182. /* The base data source needs to be uninitialized as well. */
  55183. ma_data_source_uninit(&pDataBuffer->ds);
  55184. return MA_SUCCESS;
  55185. }
  55186. MA_API ma_result ma_resource_manager_data_buffer_uninit(ma_resource_manager_data_buffer* pDataBuffer)
  55187. {
  55188. ma_result result;
  55189. if (pDataBuffer == NULL) {
  55190. return MA_INVALID_ARGS;
  55191. }
  55192. if (ma_resource_manager_data_buffer_result(pDataBuffer) == MA_SUCCESS) {
  55193. /* The data buffer can be deleted synchronously. */
  55194. return ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  55195. } else {
  55196. /*
  55197. The data buffer needs to be deleted asynchronously because it's still loading. With the status set to MA_UNAVAILABLE, no more pages will
  55198. be loaded and the uninitialization should happen fairly quickly. Since the caller owns the data buffer, we need to wait for this event
  55199. to get processed before returning.
  55200. */
  55201. ma_resource_manager_inline_notification notification;
  55202. ma_job job;
  55203. /*
  55204. We need to mark the node as unavailable so we don't try reading from it anymore, but also to
  55205. let the loading thread know that it needs to abort it's loading procedure.
  55206. */
  55207. c89atomic_exchange_i32(&pDataBuffer->result, MA_UNAVAILABLE);
  55208. result = ma_resource_manager_inline_notification_init(pDataBuffer->pResourceManager, &notification);
  55209. if (result != MA_SUCCESS) {
  55210. return result; /* Failed to create the notification. This should rarely, if ever, happen. */
  55211. }
  55212. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_BUFFER);
  55213. job.order = ma_resource_manager_data_buffer_next_execution_order(pDataBuffer);
  55214. job.data.resourceManager.freeDataBuffer.pDataBuffer = pDataBuffer;
  55215. job.data.resourceManager.freeDataBuffer.pDoneNotification = &notification;
  55216. job.data.resourceManager.freeDataBuffer.pDoneFence = NULL;
  55217. result = ma_resource_manager_post_job(pDataBuffer->pResourceManager, &job);
  55218. if (result != MA_SUCCESS) {
  55219. ma_resource_manager_inline_notification_uninit(&notification);
  55220. return result;
  55221. }
  55222. ma_resource_manager_inline_notification_wait_and_uninit(&notification);
  55223. }
  55224. return result;
  55225. }
  55226. 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)
  55227. {
  55228. ma_result result = MA_SUCCESS;
  55229. ma_uint64 framesRead = 0;
  55230. ma_bool32 isDecodedBufferBusy = MA_FALSE;
  55231. /* Safety. */
  55232. if (pFramesRead != NULL) {
  55233. *pFramesRead = 0;
  55234. }
  55235. if (frameCount == 0) {
  55236. return MA_INVALID_ARGS;
  55237. }
  55238. /*
  55239. 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
  55240. it's been uninitialized or is in the process of uninitializing.
  55241. */
  55242. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  55243. /* If the node is not initialized we need to abort with a busy code. */
  55244. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  55245. return MA_BUSY; /* Still loading. */
  55246. }
  55247. if (pDataBuffer->seekToCursorOnNextRead) {
  55248. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  55249. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pDataBuffer->seekTargetInPCMFrames);
  55250. if (result != MA_SUCCESS) {
  55251. return result;
  55252. }
  55253. }
  55254. /*
  55255. For decoded buffers (not paged) we need to check beforehand how many frames we have available. We cannot
  55256. exceed this amount. We'll read as much as we can, and then return MA_BUSY.
  55257. */
  55258. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_decoded) {
  55259. ma_uint64 availableFrames;
  55260. isDecodedBufferBusy = (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY);
  55261. if (ma_resource_manager_data_buffer_get_available_frames(pDataBuffer, &availableFrames) == MA_SUCCESS) {
  55262. /* Don't try reading more than the available frame count. */
  55263. if (frameCount > availableFrames) {
  55264. frameCount = availableFrames;
  55265. /*
  55266. If there's no frames available we want to set the status to MA_AT_END. The logic below
  55267. will check if the node is busy, and if so, change it to MA_BUSY. The reason we do this
  55268. is because we don't want to call `ma_data_source_read_pcm_frames()` if the frame count
  55269. is 0 because that'll result in a situation where it's possible MA_AT_END won't get
  55270. returned.
  55271. */
  55272. if (frameCount == 0) {
  55273. result = MA_AT_END;
  55274. }
  55275. } else {
  55276. isDecodedBufferBusy = MA_FALSE; /* We have enough frames available in the buffer to avoid a MA_BUSY status. */
  55277. }
  55278. }
  55279. }
  55280. /* Don't attempt to read anything if we've got no frames available. */
  55281. if (frameCount > 0) {
  55282. result = ma_data_source_read_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pFramesOut, frameCount, &framesRead);
  55283. }
  55284. /*
  55285. 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
  55286. as at the end and terminate decoding.
  55287. */
  55288. if (result == MA_AT_END) {
  55289. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  55290. result = MA_BUSY;
  55291. }
  55292. }
  55293. if (isDecodedBufferBusy) {
  55294. result = MA_BUSY;
  55295. }
  55296. if (pFramesRead != NULL) {
  55297. *pFramesRead = framesRead;
  55298. }
  55299. if (result == MA_SUCCESS && framesRead == 0) {
  55300. result = MA_AT_END;
  55301. }
  55302. return result;
  55303. }
  55304. MA_API ma_result ma_resource_manager_data_buffer_seek_to_pcm_frame(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64 frameIndex)
  55305. {
  55306. ma_result result;
  55307. /* We cannot be using the data source after it's been uninitialized. */
  55308. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  55309. /* If we haven't yet got a connector we need to abort. */
  55310. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  55311. pDataBuffer->seekTargetInPCMFrames = frameIndex;
  55312. pDataBuffer->seekToCursorOnNextRead = MA_TRUE;
  55313. return MA_BUSY; /* Still loading. */
  55314. }
  55315. result = ma_data_source_seek_to_pcm_frame(ma_resource_manager_data_buffer_get_connector(pDataBuffer), frameIndex);
  55316. if (result != MA_SUCCESS) {
  55317. return result;
  55318. }
  55319. pDataBuffer->seekTargetInPCMFrames = ~(ma_uint64)0; /* <-- For identification purposes. */
  55320. pDataBuffer->seekToCursorOnNextRead = MA_FALSE;
  55321. return MA_SUCCESS;
  55322. }
  55323. 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)
  55324. {
  55325. /* We cannot be using the data source after it's been uninitialized. */
  55326. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  55327. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  55328. {
  55329. case ma_resource_manager_data_supply_type_encoded:
  55330. {
  55331. return ma_data_source_get_data_format(&pDataBuffer->connector.decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  55332. };
  55333. case ma_resource_manager_data_supply_type_decoded:
  55334. {
  55335. *pFormat = pDataBuffer->pNode->data.backend.decoded.format;
  55336. *pChannels = pDataBuffer->pNode->data.backend.decoded.channels;
  55337. *pSampleRate = pDataBuffer->pNode->data.backend.decoded.sampleRate;
  55338. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  55339. return MA_SUCCESS;
  55340. };
  55341. case ma_resource_manager_data_supply_type_decoded_paged:
  55342. {
  55343. *pFormat = pDataBuffer->pNode->data.backend.decodedPaged.data.format;
  55344. *pChannels = pDataBuffer->pNode->data.backend.decodedPaged.data.channels;
  55345. *pSampleRate = pDataBuffer->pNode->data.backend.decodedPaged.sampleRate;
  55346. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, pDataBuffer->pNode->data.backend.decoded.channels);
  55347. return MA_SUCCESS;
  55348. };
  55349. case ma_resource_manager_data_supply_type_unknown:
  55350. {
  55351. return MA_BUSY; /* Still loading. */
  55352. };
  55353. default:
  55354. {
  55355. /* Unknown supply type. Should never hit this. */
  55356. return MA_INVALID_ARGS;
  55357. }
  55358. }
  55359. }
  55360. MA_API ma_result ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pCursor)
  55361. {
  55362. /* We cannot be using the data source after it's been uninitialized. */
  55363. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  55364. if (pDataBuffer == NULL || pCursor == NULL) {
  55365. return MA_INVALID_ARGS;
  55366. }
  55367. *pCursor = 0;
  55368. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  55369. {
  55370. case ma_resource_manager_data_supply_type_encoded:
  55371. {
  55372. return ma_decoder_get_cursor_in_pcm_frames(&pDataBuffer->connector.decoder, pCursor);
  55373. };
  55374. case ma_resource_manager_data_supply_type_decoded:
  55375. {
  55376. return ma_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.buffer, pCursor);
  55377. };
  55378. case ma_resource_manager_data_supply_type_decoded_paged:
  55379. {
  55380. return ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, pCursor);
  55381. };
  55382. case ma_resource_manager_data_supply_type_unknown:
  55383. {
  55384. return MA_BUSY;
  55385. };
  55386. default:
  55387. {
  55388. return MA_INVALID_ARGS;
  55389. }
  55390. }
  55391. }
  55392. MA_API ma_result ma_resource_manager_data_buffer_get_length_in_pcm_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pLength)
  55393. {
  55394. /* We cannot be using the data source after it's been uninitialized. */
  55395. MA_ASSERT(ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) != MA_UNAVAILABLE);
  55396. if (pDataBuffer == NULL || pLength == NULL) {
  55397. return MA_INVALID_ARGS;
  55398. }
  55399. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  55400. return MA_BUSY; /* Still loading. */
  55401. }
  55402. return ma_data_source_get_length_in_pcm_frames(ma_resource_manager_data_buffer_get_connector(pDataBuffer), pLength);
  55403. }
  55404. MA_API ma_result ma_resource_manager_data_buffer_result(const ma_resource_manager_data_buffer* pDataBuffer)
  55405. {
  55406. if (pDataBuffer == NULL) {
  55407. return MA_INVALID_ARGS;
  55408. }
  55409. return (ma_result)c89atomic_load_i32((ma_result*)&pDataBuffer->result); /* Need a naughty const-cast here. */
  55410. }
  55411. MA_API ma_result ma_resource_manager_data_buffer_set_looping(ma_resource_manager_data_buffer* pDataBuffer, ma_bool32 isLooping)
  55412. {
  55413. return ma_data_source_set_looping(pDataBuffer, isLooping);
  55414. }
  55415. MA_API ma_bool32 ma_resource_manager_data_buffer_is_looping(const ma_resource_manager_data_buffer* pDataBuffer)
  55416. {
  55417. return ma_data_source_is_looping(pDataBuffer);
  55418. }
  55419. MA_API ma_result ma_resource_manager_data_buffer_get_available_frames(ma_resource_manager_data_buffer* pDataBuffer, ma_uint64* pAvailableFrames)
  55420. {
  55421. if (pAvailableFrames == NULL) {
  55422. return MA_INVALID_ARGS;
  55423. }
  55424. *pAvailableFrames = 0;
  55425. if (pDataBuffer == NULL) {
  55426. return MA_INVALID_ARGS;
  55427. }
  55428. if (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode) == ma_resource_manager_data_supply_type_unknown) {
  55429. if (ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode) == MA_BUSY) {
  55430. return MA_BUSY;
  55431. } else {
  55432. return MA_INVALID_OPERATION; /* No connector. */
  55433. }
  55434. }
  55435. switch (ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode))
  55436. {
  55437. case ma_resource_manager_data_supply_type_encoded:
  55438. {
  55439. return ma_decoder_get_available_frames(&pDataBuffer->connector.decoder, pAvailableFrames);
  55440. };
  55441. case ma_resource_manager_data_supply_type_decoded:
  55442. {
  55443. return ma_audio_buffer_get_available_frames(&pDataBuffer->connector.buffer, pAvailableFrames);
  55444. };
  55445. case ma_resource_manager_data_supply_type_decoded_paged:
  55446. {
  55447. ma_uint64 cursor;
  55448. ma_paged_audio_buffer_get_cursor_in_pcm_frames(&pDataBuffer->connector.pagedBuffer, &cursor);
  55449. if (pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount > cursor) {
  55450. *pAvailableFrames = pDataBuffer->pNode->data.backend.decodedPaged.decodedFrameCount - cursor;
  55451. } else {
  55452. *pAvailableFrames = 0;
  55453. }
  55454. return MA_SUCCESS;
  55455. };
  55456. case ma_resource_manager_data_supply_type_unknown:
  55457. default:
  55458. {
  55459. /* Unknown supply type. Should never hit this. */
  55460. return MA_INVALID_ARGS;
  55461. }
  55462. }
  55463. }
  55464. MA_API ma_result ma_resource_manager_register_file(ma_resource_manager* pResourceManager, const char* pFilePath, ma_uint32 flags)
  55465. {
  55466. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pFilePath, NULL, 0, flags, NULL, NULL, NULL, NULL);
  55467. }
  55468. MA_API ma_result ma_resource_manager_register_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath, ma_uint32 flags)
  55469. {
  55470. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, NULL, pFilePath, 0, flags, NULL, NULL, NULL, NULL);
  55471. }
  55472. 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)
  55473. {
  55474. return ma_resource_manager_data_buffer_node_acquire(pResourceManager, pName, pNameW, 0, 0, pExistingData, NULL, NULL, NULL);
  55475. }
  55476. 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)
  55477. {
  55478. ma_resource_manager_data_supply data;
  55479. data.type = ma_resource_manager_data_supply_type_decoded;
  55480. data.backend.decoded.pData = pData;
  55481. data.backend.decoded.totalFrameCount = frameCount;
  55482. data.backend.decoded.format = format;
  55483. data.backend.decoded.channels = channels;
  55484. data.backend.decoded.sampleRate = sampleRate;
  55485. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  55486. }
  55487. 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)
  55488. {
  55489. return ma_resource_manager_register_decoded_data_internal(pResourceManager, pName, NULL, pData, frameCount, format, channels, sampleRate);
  55490. }
  55491. 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)
  55492. {
  55493. return ma_resource_manager_register_decoded_data_internal(pResourceManager, NULL, pName, pData, frameCount, format, channels, sampleRate);
  55494. }
  55495. 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)
  55496. {
  55497. ma_resource_manager_data_supply data;
  55498. data.type = ma_resource_manager_data_supply_type_encoded;
  55499. data.backend.encoded.pData = pData;
  55500. data.backend.encoded.sizeInBytes = sizeInBytes;
  55501. return ma_resource_manager_register_data(pResourceManager, pName, pNameW, &data);
  55502. }
  55503. MA_API ma_result ma_resource_manager_register_encoded_data(ma_resource_manager* pResourceManager, const char* pName, const void* pData, size_t sizeInBytes)
  55504. {
  55505. return ma_resource_manager_register_encoded_data_internal(pResourceManager, pName, NULL, pData, sizeInBytes);
  55506. }
  55507. 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)
  55508. {
  55509. return ma_resource_manager_register_encoded_data_internal(pResourceManager, NULL, pName, pData, sizeInBytes);
  55510. }
  55511. MA_API ma_result ma_resource_manager_unregister_file(ma_resource_manager* pResourceManager, const char* pFilePath)
  55512. {
  55513. return ma_resource_manager_unregister_data(pResourceManager, pFilePath);
  55514. }
  55515. MA_API ma_result ma_resource_manager_unregister_file_w(ma_resource_manager* pResourceManager, const wchar_t* pFilePath)
  55516. {
  55517. return ma_resource_manager_unregister_data_w(pResourceManager, pFilePath);
  55518. }
  55519. MA_API ma_result ma_resource_manager_unregister_data(ma_resource_manager* pResourceManager, const char* pName)
  55520. {
  55521. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, pName, NULL);
  55522. }
  55523. MA_API ma_result ma_resource_manager_unregister_data_w(ma_resource_manager* pResourceManager, const wchar_t* pName)
  55524. {
  55525. return ma_resource_manager_data_buffer_node_unacquire(pResourceManager, NULL, NULL, pName);
  55526. }
  55527. static ma_uint32 ma_resource_manager_data_stream_next_execution_order(ma_resource_manager_data_stream* pDataStream)
  55528. {
  55529. MA_ASSERT(pDataStream != NULL);
  55530. return c89atomic_fetch_add_32(&pDataStream->executionCounter, 1);
  55531. }
  55532. static ma_bool32 ma_resource_manager_data_stream_is_decoder_at_end(const ma_resource_manager_data_stream* pDataStream)
  55533. {
  55534. MA_ASSERT(pDataStream != NULL);
  55535. return c89atomic_load_32((ma_bool32*)&pDataStream->isDecoderAtEnd);
  55536. }
  55537. static ma_uint32 ma_resource_manager_data_stream_seek_counter(const ma_resource_manager_data_stream* pDataStream)
  55538. {
  55539. MA_ASSERT(pDataStream != NULL);
  55540. return c89atomic_load_32((ma_uint32*)&pDataStream->seekCounter);
  55541. }
  55542. static ma_result ma_resource_manager_data_stream_cb__read_pcm_frames(ma_data_source* pDataSource, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  55543. {
  55544. return ma_resource_manager_data_stream_read_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pFramesOut, frameCount, pFramesRead);
  55545. }
  55546. static ma_result ma_resource_manager_data_stream_cb__seek_to_pcm_frame(ma_data_source* pDataSource, ma_uint64 frameIndex)
  55547. {
  55548. return ma_resource_manager_data_stream_seek_to_pcm_frame((ma_resource_manager_data_stream*)pDataSource, frameIndex);
  55549. }
  55550. 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)
  55551. {
  55552. return ma_resource_manager_data_stream_get_data_format((ma_resource_manager_data_stream*)pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  55553. }
  55554. static ma_result ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pCursor)
  55555. {
  55556. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pCursor);
  55557. }
  55558. static ma_result ma_resource_manager_data_stream_cb__get_length_in_pcm_frames(ma_data_source* pDataSource, ma_uint64* pLength)
  55559. {
  55560. return ma_resource_manager_data_stream_get_length_in_pcm_frames((ma_resource_manager_data_stream*)pDataSource, pLength);
  55561. }
  55562. static ma_result ma_resource_manager_data_stream_cb__set_looping(ma_data_source* pDataSource, ma_bool32 isLooping)
  55563. {
  55564. ma_resource_manager_data_stream* pDataStream = (ma_resource_manager_data_stream*)pDataSource;
  55565. MA_ASSERT(pDataStream != NULL);
  55566. c89atomic_exchange_32(&pDataStream->isLooping, isLooping);
  55567. return MA_SUCCESS;
  55568. }
  55569. static ma_data_source_vtable g_ma_resource_manager_data_stream_vtable =
  55570. {
  55571. ma_resource_manager_data_stream_cb__read_pcm_frames,
  55572. ma_resource_manager_data_stream_cb__seek_to_pcm_frame,
  55573. ma_resource_manager_data_stream_cb__get_data_format,
  55574. ma_resource_manager_data_stream_cb__get_cursor_in_pcm_frames,
  55575. ma_resource_manager_data_stream_cb__get_length_in_pcm_frames,
  55576. ma_resource_manager_data_stream_cb__set_looping,
  55577. MA_DATA_SOURCE_SELF_MANAGED_RANGE_AND_LOOP_POINT
  55578. };
  55579. static void ma_resource_manager_data_stream_set_absolute_cursor(ma_resource_manager_data_stream* pDataStream, ma_uint64 absoluteCursor)
  55580. {
  55581. /* Loop if possible. */
  55582. if (absoluteCursor > pDataStream->totalLengthInPCMFrames && pDataStream->totalLengthInPCMFrames > 0) {
  55583. absoluteCursor = absoluteCursor % pDataStream->totalLengthInPCMFrames;
  55584. }
  55585. c89atomic_exchange_64(&pDataStream->absoluteCursor, absoluteCursor);
  55586. }
  55587. 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)
  55588. {
  55589. ma_result result;
  55590. ma_data_source_config dataSourceConfig;
  55591. char* pFilePathCopy = NULL;
  55592. wchar_t* pFilePathWCopy = NULL;
  55593. ma_job job;
  55594. ma_bool32 waitBeforeReturning = MA_FALSE;
  55595. ma_resource_manager_inline_notification waitNotification;
  55596. ma_resource_manager_pipeline_notifications notifications;
  55597. if (pDataStream == NULL) {
  55598. if (pConfig != NULL && pConfig->pNotifications != NULL) {
  55599. ma_resource_manager_pipeline_notifications_signal_all_notifications(pConfig->pNotifications);
  55600. }
  55601. return MA_INVALID_ARGS;
  55602. }
  55603. MA_ZERO_OBJECT(pDataStream);
  55604. if (pConfig == NULL) {
  55605. return MA_INVALID_ARGS;
  55606. }
  55607. if (pConfig->pNotifications != NULL) {
  55608. 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. */
  55609. } else {
  55610. MA_ZERO_OBJECT(&notifications);
  55611. }
  55612. dataSourceConfig = ma_data_source_config_init();
  55613. dataSourceConfig.vtable = &g_ma_resource_manager_data_stream_vtable;
  55614. result = ma_data_source_init(&dataSourceConfig, &pDataStream->ds);
  55615. if (result != MA_SUCCESS) {
  55616. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55617. return result;
  55618. }
  55619. pDataStream->pResourceManager = pResourceManager;
  55620. pDataStream->flags = pConfig->flags;
  55621. pDataStream->result = MA_BUSY;
  55622. ma_data_source_set_range_in_pcm_frames(pDataStream, pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  55623. ma_data_source_set_loop_point_in_pcm_frames(pDataStream, pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  55624. ma_data_source_set_looping(pDataStream, pConfig->isLooping);
  55625. if (pResourceManager == NULL || (pConfig->pFilePath == NULL && pConfig->pFilePathW == NULL)) {
  55626. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55627. return MA_INVALID_ARGS;
  55628. }
  55629. /* 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. */
  55630. /* 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. */
  55631. if (pConfig->pFilePath != NULL) {
  55632. pFilePathCopy = ma_copy_string(pConfig->pFilePath, &pResourceManager->config.allocationCallbacks);
  55633. } else {
  55634. pFilePathWCopy = ma_copy_string_w(pConfig->pFilePathW, &pResourceManager->config.allocationCallbacks);
  55635. }
  55636. if (pFilePathCopy == NULL && pFilePathWCopy == NULL) {
  55637. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55638. return MA_OUT_OF_MEMORY;
  55639. }
  55640. /*
  55641. 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
  55642. can return immediately. Likewise, we'll also check for MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT and do the same.
  55643. */
  55644. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_ASYNC) == 0 || (pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT) != 0) {
  55645. waitBeforeReturning = MA_TRUE;
  55646. ma_resource_manager_inline_notification_init(pResourceManager, &waitNotification);
  55647. }
  55648. ma_resource_manager_pipeline_notifications_acquire_all_fences(&notifications);
  55649. /* Set the absolute cursor to our initial seek position so retrieval of the cursor returns a good value. */
  55650. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, pConfig->initialSeekPointInPCMFrames);
  55651. /* 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. */
  55652. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_LOAD_DATA_STREAM);
  55653. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  55654. job.data.resourceManager.loadDataStream.pDataStream = pDataStream;
  55655. job.data.resourceManager.loadDataStream.pFilePath = pFilePathCopy;
  55656. job.data.resourceManager.loadDataStream.pFilePathW = pFilePathWCopy;
  55657. job.data.resourceManager.loadDataStream.initialSeekPoint = pConfig->initialSeekPointInPCMFrames;
  55658. job.data.resourceManager.loadDataStream.pInitNotification = (waitBeforeReturning == MA_TRUE) ? &waitNotification : notifications.init.pNotification;
  55659. job.data.resourceManager.loadDataStream.pInitFence = notifications.init.pFence;
  55660. result = ma_resource_manager_post_job(pResourceManager, &job);
  55661. if (result != MA_SUCCESS) {
  55662. ma_resource_manager_pipeline_notifications_signal_all_notifications(&notifications);
  55663. ma_resource_manager_pipeline_notifications_release_all_fences(&notifications);
  55664. if (waitBeforeReturning) {
  55665. ma_resource_manager_inline_notification_uninit(&waitNotification);
  55666. }
  55667. ma_free(pFilePathCopy, &pResourceManager->config.allocationCallbacks);
  55668. ma_free(pFilePathWCopy, &pResourceManager->config.allocationCallbacks);
  55669. return result;
  55670. }
  55671. /* Wait if needed. */
  55672. if (waitBeforeReturning) {
  55673. ma_resource_manager_inline_notification_wait_and_uninit(&waitNotification);
  55674. if (notifications.init.pNotification != NULL) {
  55675. ma_async_notification_signal(notifications.init.pNotification);
  55676. }
  55677. /* NOTE: Do not release pInitFence here. That will be done by the job. */
  55678. }
  55679. return MA_SUCCESS;
  55680. }
  55681. 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)
  55682. {
  55683. ma_resource_manager_data_source_config config;
  55684. config = ma_resource_manager_data_source_config_init();
  55685. config.pFilePath = pFilePath;
  55686. config.flags = flags;
  55687. config.pNotifications = pNotifications;
  55688. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  55689. }
  55690. 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)
  55691. {
  55692. ma_resource_manager_data_source_config config;
  55693. config = ma_resource_manager_data_source_config_init();
  55694. config.pFilePathW = pFilePath;
  55695. config.flags = flags;
  55696. config.pNotifications = pNotifications;
  55697. return ma_resource_manager_data_stream_init_ex(pResourceManager, &config, pDataStream);
  55698. }
  55699. MA_API ma_result ma_resource_manager_data_stream_uninit(ma_resource_manager_data_stream* pDataStream)
  55700. {
  55701. ma_resource_manager_inline_notification freeEvent;
  55702. ma_job job;
  55703. if (pDataStream == NULL) {
  55704. return MA_INVALID_ARGS;
  55705. }
  55706. /* The first thing to do is set the result to unavailable. This will prevent future page decoding. */
  55707. c89atomic_exchange_i32(&pDataStream->result, MA_UNAVAILABLE);
  55708. /*
  55709. 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
  55710. to wait for it to complete before returning which means we need an event.
  55711. */
  55712. ma_resource_manager_inline_notification_init(pDataStream->pResourceManager, &freeEvent);
  55713. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_FREE_DATA_STREAM);
  55714. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  55715. job.data.resourceManager.freeDataStream.pDataStream = pDataStream;
  55716. job.data.resourceManager.freeDataStream.pDoneNotification = &freeEvent;
  55717. job.data.resourceManager.freeDataStream.pDoneFence = NULL;
  55718. ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  55719. /* We need to wait for the job to finish processing before we return. */
  55720. ma_resource_manager_inline_notification_wait_and_uninit(&freeEvent);
  55721. return MA_SUCCESS;
  55722. }
  55723. static ma_uint32 ma_resource_manager_data_stream_get_page_size_in_frames(ma_resource_manager_data_stream* pDataStream)
  55724. {
  55725. MA_ASSERT(pDataStream != NULL);
  55726. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  55727. return MA_RESOURCE_MANAGER_PAGE_SIZE_IN_MILLISECONDS * (pDataStream->decoder.outputSampleRate/1000);
  55728. }
  55729. static void* ma_resource_manager_data_stream_get_page_data_pointer(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex, ma_uint32 relativeCursor)
  55730. {
  55731. MA_ASSERT(pDataStream != NULL);
  55732. MA_ASSERT(pDataStream->isDecoderInitialized == MA_TRUE);
  55733. MA_ASSERT(pageIndex == 0 || pageIndex == 1);
  55734. 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));
  55735. }
  55736. static void ma_resource_manager_data_stream_fill_page(ma_resource_manager_data_stream* pDataStream, ma_uint32 pageIndex)
  55737. {
  55738. ma_result result = MA_SUCCESS;
  55739. ma_uint64 pageSizeInFrames;
  55740. ma_uint64 totalFramesReadForThisPage = 0;
  55741. void* pPageData = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pageIndex, 0);
  55742. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  55743. /* The decoder needs to inherit the stream's looping and range state. */
  55744. {
  55745. ma_uint64 rangeBeg;
  55746. ma_uint64 rangeEnd;
  55747. ma_uint64 loopPointBeg;
  55748. ma_uint64 loopPointEnd;
  55749. ma_data_source_set_looping(&pDataStream->decoder, ma_resource_manager_data_stream_is_looping(pDataStream));
  55750. ma_data_source_get_range_in_pcm_frames(pDataStream, &rangeBeg, &rangeEnd);
  55751. ma_data_source_set_range_in_pcm_frames(&pDataStream->decoder, rangeBeg, rangeEnd);
  55752. ma_data_source_get_loop_point_in_pcm_frames(pDataStream, &loopPointBeg, &loopPointEnd);
  55753. ma_data_source_set_loop_point_in_pcm_frames(&pDataStream->decoder, loopPointBeg, loopPointEnd);
  55754. }
  55755. /* Just read straight from the decoder. It will deal with ranges and looping for us. */
  55756. result = ma_data_source_read_pcm_frames(&pDataStream->decoder, pPageData, pageSizeInFrames, &totalFramesReadForThisPage);
  55757. if (result == MA_AT_END || totalFramesReadForThisPage < pageSizeInFrames) {
  55758. c89atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_TRUE);
  55759. }
  55760. c89atomic_exchange_32(&pDataStream->pageFrameCount[pageIndex], (ma_uint32)totalFramesReadForThisPage);
  55761. c89atomic_exchange_32(&pDataStream->isPageValid[pageIndex], MA_TRUE);
  55762. }
  55763. static void ma_resource_manager_data_stream_fill_pages(ma_resource_manager_data_stream* pDataStream)
  55764. {
  55765. ma_uint32 iPage;
  55766. MA_ASSERT(pDataStream != NULL);
  55767. for (iPage = 0; iPage < 2; iPage += 1) {
  55768. ma_resource_manager_data_stream_fill_page(pDataStream, iPage);
  55769. }
  55770. }
  55771. static ma_result ma_resource_manager_data_stream_map(ma_resource_manager_data_stream* pDataStream, void** ppFramesOut, ma_uint64* pFrameCount)
  55772. {
  55773. ma_uint64 framesAvailable;
  55774. ma_uint64 frameCount = 0;
  55775. /* We cannot be using the data source after it's been uninitialized. */
  55776. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  55777. if (pFrameCount != NULL) {
  55778. frameCount = *pFrameCount;
  55779. *pFrameCount = 0;
  55780. }
  55781. if (ppFramesOut != NULL) {
  55782. *ppFramesOut = NULL;
  55783. }
  55784. if (pDataStream == NULL || ppFramesOut == NULL || pFrameCount == NULL) {
  55785. return MA_INVALID_ARGS;
  55786. }
  55787. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  55788. return MA_INVALID_OPERATION;
  55789. }
  55790. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  55791. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  55792. return MA_BUSY;
  55793. }
  55794. /* If the page we're on is invalid it means we've caught up to the job thread. */
  55795. if (c89atomic_load_32(&pDataStream->isPageValid[pDataStream->currentPageIndex]) == MA_FALSE) {
  55796. framesAvailable = 0;
  55797. } else {
  55798. /*
  55799. 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
  55800. that the unmap process will only post an update for one page at a time. Keeping mapping tied to page boundaries makes this simpler.
  55801. */
  55802. ma_uint32 currentPageFrameCount = c89atomic_load_32(&pDataStream->pageFrameCount[pDataStream->currentPageIndex]);
  55803. MA_ASSERT(currentPageFrameCount >= pDataStream->relativeCursor);
  55804. framesAvailable = currentPageFrameCount - pDataStream->relativeCursor;
  55805. }
  55806. /* If there's no frames available and the result is set to MA_AT_END we need to return MA_AT_END. */
  55807. if (framesAvailable == 0) {
  55808. if (ma_resource_manager_data_stream_is_decoder_at_end(pDataStream)) {
  55809. return MA_AT_END;
  55810. } else {
  55811. 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. */
  55812. }
  55813. }
  55814. MA_ASSERT(framesAvailable > 0);
  55815. if (frameCount > framesAvailable) {
  55816. frameCount = framesAvailable;
  55817. }
  55818. *ppFramesOut = ma_resource_manager_data_stream_get_page_data_pointer(pDataStream, pDataStream->currentPageIndex, pDataStream->relativeCursor);
  55819. *pFrameCount = frameCount;
  55820. return MA_SUCCESS;
  55821. }
  55822. static ma_result ma_resource_manager_data_stream_unmap(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameCount)
  55823. {
  55824. ma_uint32 newRelativeCursor;
  55825. ma_uint32 pageSizeInFrames;
  55826. ma_job job;
  55827. /* We cannot be using the data source after it's been uninitialized. */
  55828. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  55829. if (pDataStream == NULL) {
  55830. return MA_INVALID_ARGS;
  55831. }
  55832. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  55833. return MA_INVALID_OPERATION;
  55834. }
  55835. /* The frame count should always fit inside a 32-bit integer. */
  55836. if (frameCount > 0xFFFFFFFF) {
  55837. return MA_INVALID_ARGS;
  55838. }
  55839. pageSizeInFrames = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream);
  55840. /* The absolute cursor needs to be updated for ma_resource_manager_data_stream_get_cursor_in_pcm_frames(). */
  55841. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, c89atomic_load_64(&pDataStream->absoluteCursor) + frameCount);
  55842. /* Here is where we need to check if we need to load a new page, and if so, post a job to load it. */
  55843. newRelativeCursor = pDataStream->relativeCursor + (ma_uint32)frameCount;
  55844. /* 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. */
  55845. if (newRelativeCursor >= pageSizeInFrames) {
  55846. newRelativeCursor -= pageSizeInFrames;
  55847. /* Here is where we post the job start decoding. */
  55848. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_STREAM);
  55849. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  55850. job.data.resourceManager.pageDataStream.pDataStream = pDataStream;
  55851. job.data.resourceManager.pageDataStream.pageIndex = pDataStream->currentPageIndex;
  55852. /* The page needs to be marked as invalid so that the public API doesn't try reading from it. */
  55853. c89atomic_exchange_32(&pDataStream->isPageValid[pDataStream->currentPageIndex], MA_FALSE);
  55854. /* Before posting the job we need to make sure we set some state. */
  55855. pDataStream->relativeCursor = newRelativeCursor;
  55856. pDataStream->currentPageIndex = (pDataStream->currentPageIndex + 1) & 0x01;
  55857. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  55858. } else {
  55859. /* We haven't moved into a new page so we can just move the cursor forward. */
  55860. pDataStream->relativeCursor = newRelativeCursor;
  55861. return MA_SUCCESS;
  55862. }
  55863. }
  55864. 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)
  55865. {
  55866. ma_result result = MA_SUCCESS;
  55867. ma_uint64 totalFramesProcessed;
  55868. ma_format format;
  55869. ma_uint32 channels;
  55870. /* Safety. */
  55871. if (pFramesRead != NULL) {
  55872. *pFramesRead = 0;
  55873. }
  55874. if (frameCount == 0) {
  55875. return MA_INVALID_ARGS;
  55876. }
  55877. /* We cannot be using the data source after it's been uninitialized. */
  55878. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  55879. if (pDataStream == NULL) {
  55880. return MA_INVALID_ARGS;
  55881. }
  55882. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  55883. return MA_INVALID_OPERATION;
  55884. }
  55885. /* Don't attempt to read while we're in the middle of seeking. Tell the caller that we're busy. */
  55886. if (ma_resource_manager_data_stream_seek_counter(pDataStream) > 0) {
  55887. return MA_BUSY;
  55888. }
  55889. ma_resource_manager_data_stream_get_data_format(pDataStream, &format, &channels, NULL, NULL, 0);
  55890. /* Reading is implemented in terms of map/unmap. We need to run this in a loop because mapping is clamped against page boundaries. */
  55891. totalFramesProcessed = 0;
  55892. while (totalFramesProcessed < frameCount) {
  55893. void* pMappedFrames;
  55894. ma_uint64 mappedFrameCount;
  55895. mappedFrameCount = frameCount - totalFramesProcessed;
  55896. result = ma_resource_manager_data_stream_map(pDataStream, &pMappedFrames, &mappedFrameCount);
  55897. if (result != MA_SUCCESS) {
  55898. break;
  55899. }
  55900. /* 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. */
  55901. if (pFramesOut != NULL) {
  55902. ma_copy_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesProcessed, format, channels), pMappedFrames, mappedFrameCount, format, channels);
  55903. }
  55904. totalFramesProcessed += mappedFrameCount;
  55905. result = ma_resource_manager_data_stream_unmap(pDataStream, mappedFrameCount);
  55906. if (result != MA_SUCCESS) {
  55907. 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. */
  55908. }
  55909. }
  55910. if (pFramesRead != NULL) {
  55911. *pFramesRead = totalFramesProcessed;
  55912. }
  55913. if (result == MA_SUCCESS && totalFramesProcessed == 0) {
  55914. result = MA_AT_END;
  55915. }
  55916. return result;
  55917. }
  55918. MA_API ma_result ma_resource_manager_data_stream_seek_to_pcm_frame(ma_resource_manager_data_stream* pDataStream, ma_uint64 frameIndex)
  55919. {
  55920. ma_job job;
  55921. ma_result streamResult;
  55922. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  55923. /* We cannot be using the data source after it's been uninitialized. */
  55924. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  55925. if (pDataStream == NULL) {
  55926. return MA_INVALID_ARGS;
  55927. }
  55928. if (streamResult != MA_SUCCESS && streamResult != MA_BUSY) {
  55929. return MA_INVALID_OPERATION;
  55930. }
  55931. /* If we're not already seeking and we're sitting on the same frame, just make this a no-op. */
  55932. if (c89atomic_load_32(&pDataStream->seekCounter) == 0) {
  55933. if (c89atomic_load_64(&pDataStream->absoluteCursor) == frameIndex) {
  55934. return MA_SUCCESS;
  55935. }
  55936. }
  55937. /* 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. */
  55938. c89atomic_fetch_add_32(&pDataStream->seekCounter, 1);
  55939. /* Update the absolute cursor so that ma_resource_manager_data_stream_get_cursor_in_pcm_frames() returns the new position. */
  55940. ma_resource_manager_data_stream_set_absolute_cursor(pDataStream, frameIndex);
  55941. /*
  55942. 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
  55943. 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
  55944. the first page.
  55945. */
  55946. pDataStream->relativeCursor = 0;
  55947. pDataStream->currentPageIndex = 0;
  55948. c89atomic_exchange_32(&pDataStream->isPageValid[0], MA_FALSE);
  55949. c89atomic_exchange_32(&pDataStream->isPageValid[1], MA_FALSE);
  55950. /* 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. */
  55951. c89atomic_exchange_32(&pDataStream->isDecoderAtEnd, MA_FALSE);
  55952. /*
  55953. 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
  55954. are invalid and any content contained within them will be discarded and replaced with newly decoded data.
  55955. */
  55956. job = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_SEEK_DATA_STREAM);
  55957. job.order = ma_resource_manager_data_stream_next_execution_order(pDataStream);
  55958. job.data.resourceManager.seekDataStream.pDataStream = pDataStream;
  55959. job.data.resourceManager.seekDataStream.frameIndex = frameIndex;
  55960. return ma_resource_manager_post_job(pDataStream->pResourceManager, &job);
  55961. }
  55962. 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)
  55963. {
  55964. /* We cannot be using the data source after it's been uninitialized. */
  55965. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  55966. if (pFormat != NULL) {
  55967. *pFormat = ma_format_unknown;
  55968. }
  55969. if (pChannels != NULL) {
  55970. *pChannels = 0;
  55971. }
  55972. if (pSampleRate != NULL) {
  55973. *pSampleRate = 0;
  55974. }
  55975. if (pChannelMap != NULL) {
  55976. MA_ZERO_MEMORY(pChannelMap, sizeof(*pChannelMap) * channelMapCap);
  55977. }
  55978. if (pDataStream == NULL) {
  55979. return MA_INVALID_ARGS;
  55980. }
  55981. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  55982. return MA_INVALID_OPERATION;
  55983. }
  55984. /*
  55985. 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
  55986. such that the application is responsible for ensuring it's not called while uninitializing so it should be safe.
  55987. */
  55988. return ma_data_source_get_data_format(&pDataStream->decoder, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  55989. }
  55990. MA_API ma_result ma_resource_manager_data_stream_get_cursor_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pCursor)
  55991. {
  55992. ma_result result;
  55993. if (pCursor == NULL) {
  55994. return MA_INVALID_ARGS;
  55995. }
  55996. *pCursor = 0;
  55997. /* We cannot be using the data source after it's been uninitialized. */
  55998. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) != MA_UNAVAILABLE);
  55999. if (pDataStream == NULL) {
  56000. return MA_INVALID_ARGS;
  56001. }
  56002. /*
  56003. If the stream is in an erroneous state we need to return an invalid operation. We can allow
  56004. this to be called when the data stream is in a busy state because the caller may have asked
  56005. for an initial seek position and it's convenient to return that as the cursor position.
  56006. */
  56007. result = ma_resource_manager_data_stream_result(pDataStream);
  56008. if (result != MA_SUCCESS && result != MA_BUSY) {
  56009. return MA_INVALID_OPERATION;
  56010. }
  56011. *pCursor = c89atomic_load_64(&pDataStream->absoluteCursor);
  56012. return MA_SUCCESS;
  56013. }
  56014. MA_API ma_result ma_resource_manager_data_stream_get_length_in_pcm_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pLength)
  56015. {
  56016. ma_result streamResult;
  56017. if (pLength == NULL) {
  56018. return MA_INVALID_ARGS;
  56019. }
  56020. *pLength = 0;
  56021. streamResult = ma_resource_manager_data_stream_result(pDataStream);
  56022. /* We cannot be using the data source after it's been uninitialized. */
  56023. MA_ASSERT(streamResult != MA_UNAVAILABLE);
  56024. if (pDataStream == NULL) {
  56025. return MA_INVALID_ARGS;
  56026. }
  56027. if (streamResult != MA_SUCCESS) {
  56028. return streamResult;
  56029. }
  56030. /*
  56031. 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
  56032. calculated when we initialized it on the job thread.
  56033. */
  56034. *pLength = pDataStream->totalLengthInPCMFrames;
  56035. if (*pLength == 0) {
  56036. return MA_NOT_IMPLEMENTED; /* Some decoders may not have a known length. */
  56037. }
  56038. return MA_SUCCESS;
  56039. }
  56040. MA_API ma_result ma_resource_manager_data_stream_result(const ma_resource_manager_data_stream* pDataStream)
  56041. {
  56042. if (pDataStream == NULL) {
  56043. return MA_INVALID_ARGS;
  56044. }
  56045. return (ma_result)c89atomic_load_i32(&pDataStream->result);
  56046. }
  56047. MA_API ma_result ma_resource_manager_data_stream_set_looping(ma_resource_manager_data_stream* pDataStream, ma_bool32 isLooping)
  56048. {
  56049. return ma_data_source_set_looping(pDataStream, isLooping);
  56050. }
  56051. MA_API ma_bool32 ma_resource_manager_data_stream_is_looping(const ma_resource_manager_data_stream* pDataStream)
  56052. {
  56053. if (pDataStream == NULL) {
  56054. return MA_FALSE;
  56055. }
  56056. return c89atomic_load_32((ma_bool32*)&pDataStream->isLooping); /* Naughty const-cast. Value won't change from here in practice (maybe from another thread). */
  56057. }
  56058. MA_API ma_result ma_resource_manager_data_stream_get_available_frames(ma_resource_manager_data_stream* pDataStream, ma_uint64* pAvailableFrames)
  56059. {
  56060. ma_uint32 pageIndex0;
  56061. ma_uint32 pageIndex1;
  56062. ma_uint32 relativeCursor;
  56063. ma_uint64 availableFrames;
  56064. if (pAvailableFrames == NULL) {
  56065. return MA_INVALID_ARGS;
  56066. }
  56067. *pAvailableFrames = 0;
  56068. if (pDataStream == NULL) {
  56069. return MA_INVALID_ARGS;
  56070. }
  56071. pageIndex0 = pDataStream->currentPageIndex;
  56072. pageIndex1 = (pDataStream->currentPageIndex + 1) & 0x01;
  56073. relativeCursor = pDataStream->relativeCursor;
  56074. availableFrames = 0;
  56075. if (c89atomic_load_32(&pDataStream->isPageValid[pageIndex0])) {
  56076. availableFrames += c89atomic_load_32(&pDataStream->pageFrameCount[pageIndex0]) - relativeCursor;
  56077. if (c89atomic_load_32(&pDataStream->isPageValid[pageIndex1])) {
  56078. availableFrames += c89atomic_load_32(&pDataStream->pageFrameCount[pageIndex1]);
  56079. }
  56080. }
  56081. *pAvailableFrames = availableFrames;
  56082. return MA_SUCCESS;
  56083. }
  56084. 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)
  56085. {
  56086. if (pDataSource == NULL) {
  56087. return MA_INVALID_ARGS;
  56088. }
  56089. MA_ZERO_OBJECT(pDataSource);
  56090. if (pConfig == NULL) {
  56091. return MA_INVALID_ARGS;
  56092. }
  56093. if (pResourceManager == NULL) {
  56094. return MA_INVALID_ARGS;
  56095. }
  56096. pDataSource->flags = pConfig->flags;
  56097. return MA_SUCCESS;
  56098. }
  56099. 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)
  56100. {
  56101. ma_result result;
  56102. result = ma_resource_manager_data_source_preinit(pResourceManager, pConfig, pDataSource);
  56103. if (result != MA_SUCCESS) {
  56104. return result;
  56105. }
  56106. /* The data source itself is just a data stream or a data buffer. */
  56107. if ((pConfig->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56108. return ma_resource_manager_data_stream_init_ex(pResourceManager, pConfig, &pDataSource->backend.stream);
  56109. } else {
  56110. return ma_resource_manager_data_buffer_init_ex(pResourceManager, pConfig, &pDataSource->backend.buffer);
  56111. }
  56112. }
  56113. 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)
  56114. {
  56115. ma_resource_manager_data_source_config config;
  56116. config = ma_resource_manager_data_source_config_init();
  56117. config.pFilePath = pName;
  56118. config.flags = flags;
  56119. config.pNotifications = pNotifications;
  56120. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  56121. }
  56122. 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)
  56123. {
  56124. ma_resource_manager_data_source_config config;
  56125. config = ma_resource_manager_data_source_config_init();
  56126. config.pFilePathW = pName;
  56127. config.flags = flags;
  56128. config.pNotifications = pNotifications;
  56129. return ma_resource_manager_data_source_init_ex(pResourceManager, &config, pDataSource);
  56130. }
  56131. 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)
  56132. {
  56133. ma_result result;
  56134. ma_resource_manager_data_source_config config;
  56135. if (pExistingDataSource == NULL) {
  56136. return MA_INVALID_ARGS;
  56137. }
  56138. config = ma_resource_manager_data_source_config_init();
  56139. config.flags = pExistingDataSource->flags;
  56140. result = ma_resource_manager_data_source_preinit(pResourceManager, &config, pDataSource);
  56141. if (result != MA_SUCCESS) {
  56142. return result;
  56143. }
  56144. /* Copying can only be done from data buffers. Streams cannot be copied. */
  56145. if ((pExistingDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56146. return MA_INVALID_OPERATION;
  56147. }
  56148. return ma_resource_manager_data_buffer_init_copy(pResourceManager, &pExistingDataSource->backend.buffer, &pDataSource->backend.buffer);
  56149. }
  56150. MA_API ma_result ma_resource_manager_data_source_uninit(ma_resource_manager_data_source* pDataSource)
  56151. {
  56152. if (pDataSource == NULL) {
  56153. return MA_INVALID_ARGS;
  56154. }
  56155. /* All we need to is uninitialize the underlying data buffer or data stream. */
  56156. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56157. return ma_resource_manager_data_stream_uninit(&pDataSource->backend.stream);
  56158. } else {
  56159. return ma_resource_manager_data_buffer_uninit(&pDataSource->backend.buffer);
  56160. }
  56161. }
  56162. 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)
  56163. {
  56164. /* Safety. */
  56165. if (pFramesRead != NULL) {
  56166. *pFramesRead = 0;
  56167. }
  56168. if (pDataSource == NULL) {
  56169. return MA_INVALID_ARGS;
  56170. }
  56171. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56172. return ma_resource_manager_data_stream_read_pcm_frames(&pDataSource->backend.stream, pFramesOut, frameCount, pFramesRead);
  56173. } else {
  56174. return ma_resource_manager_data_buffer_read_pcm_frames(&pDataSource->backend.buffer, pFramesOut, frameCount, pFramesRead);
  56175. }
  56176. }
  56177. MA_API ma_result ma_resource_manager_data_source_seek_to_pcm_frame(ma_resource_manager_data_source* pDataSource, ma_uint64 frameIndex)
  56178. {
  56179. if (pDataSource == NULL) {
  56180. return MA_INVALID_ARGS;
  56181. }
  56182. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56183. return ma_resource_manager_data_stream_seek_to_pcm_frame(&pDataSource->backend.stream, frameIndex);
  56184. } else {
  56185. return ma_resource_manager_data_buffer_seek_to_pcm_frame(&pDataSource->backend.buffer, frameIndex);
  56186. }
  56187. }
  56188. MA_API ma_result ma_resource_manager_data_source_map(ma_resource_manager_data_source* pDataSource, void** ppFramesOut, ma_uint64* pFrameCount)
  56189. {
  56190. if (pDataSource == NULL) {
  56191. return MA_INVALID_ARGS;
  56192. }
  56193. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56194. return ma_resource_manager_data_stream_map(&pDataSource->backend.stream, ppFramesOut, pFrameCount);
  56195. } else {
  56196. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  56197. }
  56198. }
  56199. MA_API ma_result ma_resource_manager_data_source_unmap(ma_resource_manager_data_source* pDataSource, ma_uint64 frameCount)
  56200. {
  56201. if (pDataSource == NULL) {
  56202. return MA_INVALID_ARGS;
  56203. }
  56204. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56205. return ma_resource_manager_data_stream_unmap(&pDataSource->backend.stream, frameCount);
  56206. } else {
  56207. return MA_NOT_IMPLEMENTED; /* Mapping not supported with data buffers. */
  56208. }
  56209. }
  56210. 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)
  56211. {
  56212. if (pDataSource == NULL) {
  56213. return MA_INVALID_ARGS;
  56214. }
  56215. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56216. return ma_resource_manager_data_stream_get_data_format(&pDataSource->backend.stream, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  56217. } else {
  56218. return ma_resource_manager_data_buffer_get_data_format(&pDataSource->backend.buffer, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  56219. }
  56220. }
  56221. MA_API ma_result ma_resource_manager_data_source_get_cursor_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pCursor)
  56222. {
  56223. if (pDataSource == NULL) {
  56224. return MA_INVALID_ARGS;
  56225. }
  56226. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56227. return ma_resource_manager_data_stream_get_cursor_in_pcm_frames(&pDataSource->backend.stream, pCursor);
  56228. } else {
  56229. return ma_resource_manager_data_buffer_get_cursor_in_pcm_frames(&pDataSource->backend.buffer, pCursor);
  56230. }
  56231. }
  56232. MA_API ma_result ma_resource_manager_data_source_get_length_in_pcm_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pLength)
  56233. {
  56234. if (pDataSource == NULL) {
  56235. return MA_INVALID_ARGS;
  56236. }
  56237. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56238. return ma_resource_manager_data_stream_get_length_in_pcm_frames(&pDataSource->backend.stream, pLength);
  56239. } else {
  56240. return ma_resource_manager_data_buffer_get_length_in_pcm_frames(&pDataSource->backend.buffer, pLength);
  56241. }
  56242. }
  56243. MA_API ma_result ma_resource_manager_data_source_result(const ma_resource_manager_data_source* pDataSource)
  56244. {
  56245. if (pDataSource == NULL) {
  56246. return MA_INVALID_ARGS;
  56247. }
  56248. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56249. return ma_resource_manager_data_stream_result(&pDataSource->backend.stream);
  56250. } else {
  56251. return ma_resource_manager_data_buffer_result(&pDataSource->backend.buffer);
  56252. }
  56253. }
  56254. MA_API ma_result ma_resource_manager_data_source_set_looping(ma_resource_manager_data_source* pDataSource, ma_bool32 isLooping)
  56255. {
  56256. if (pDataSource == NULL) {
  56257. return MA_INVALID_ARGS;
  56258. }
  56259. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56260. return ma_resource_manager_data_stream_set_looping(&pDataSource->backend.stream, isLooping);
  56261. } else {
  56262. return ma_resource_manager_data_buffer_set_looping(&pDataSource->backend.buffer, isLooping);
  56263. }
  56264. }
  56265. MA_API ma_bool32 ma_resource_manager_data_source_is_looping(const ma_resource_manager_data_source* pDataSource)
  56266. {
  56267. if (pDataSource == NULL) {
  56268. return MA_FALSE;
  56269. }
  56270. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56271. return ma_resource_manager_data_stream_is_looping(&pDataSource->backend.stream);
  56272. } else {
  56273. return ma_resource_manager_data_buffer_is_looping(&pDataSource->backend.buffer);
  56274. }
  56275. }
  56276. MA_API ma_result ma_resource_manager_data_source_get_available_frames(ma_resource_manager_data_source* pDataSource, ma_uint64* pAvailableFrames)
  56277. {
  56278. if (pAvailableFrames == NULL) {
  56279. return MA_INVALID_ARGS;
  56280. }
  56281. *pAvailableFrames = 0;
  56282. if (pDataSource == NULL) {
  56283. return MA_INVALID_ARGS;
  56284. }
  56285. if ((pDataSource->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_STREAM) != 0) {
  56286. return ma_resource_manager_data_stream_get_available_frames(&pDataSource->backend.stream, pAvailableFrames);
  56287. } else {
  56288. return ma_resource_manager_data_buffer_get_available_frames(&pDataSource->backend.buffer, pAvailableFrames);
  56289. }
  56290. }
  56291. MA_API ma_result ma_resource_manager_post_job(ma_resource_manager* pResourceManager, const ma_job* pJob)
  56292. {
  56293. if (pResourceManager == NULL) {
  56294. return MA_INVALID_ARGS;
  56295. }
  56296. return ma_job_queue_post(&pResourceManager->jobQueue, pJob);
  56297. }
  56298. MA_API ma_result ma_resource_manager_post_job_quit(ma_resource_manager* pResourceManager)
  56299. {
  56300. ma_job job = ma_job_init(MA_JOB_TYPE_QUIT);
  56301. return ma_resource_manager_post_job(pResourceManager, &job);
  56302. }
  56303. MA_API ma_result ma_resource_manager_next_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  56304. {
  56305. if (pResourceManager == NULL) {
  56306. return MA_INVALID_ARGS;
  56307. }
  56308. return ma_job_queue_next(&pResourceManager->jobQueue, pJob);
  56309. }
  56310. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob)
  56311. {
  56312. ma_result result = MA_SUCCESS;
  56313. ma_resource_manager* pResourceManager;
  56314. ma_resource_manager_data_buffer_node* pDataBufferNode;
  56315. MA_ASSERT(pJob != NULL);
  56316. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.loadDataBufferNode.pResourceManager;
  56317. MA_ASSERT(pResourceManager != NULL);
  56318. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.loadDataBufferNode.pDataBufferNode;
  56319. MA_ASSERT(pDataBufferNode != NULL);
  56320. MA_ASSERT(pDataBufferNode->isDataOwnedByResourceManager == MA_TRUE); /* The data should always be owned by the resource manager. */
  56321. /* 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. */
  56322. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  56323. 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. */
  56324. }
  56325. /* First thing we need to do is check whether or not the data buffer is getting deleted. If so we just abort. */
  56326. if (ma_resource_manager_data_buffer_node_result(pDataBufferNode) != MA_BUSY) {
  56327. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode); /* The data buffer may be getting deleted before it's even been loaded. */
  56328. goto done;
  56329. }
  56330. /*
  56331. We're ready to start loading. Essentially what we're doing here is initializing the data supply
  56332. of the node. Once this is complete, data buffers can have their connectors initialized which
  56333. will allow then to have audio data read from them.
  56334. Note that when the data supply type has been moved away from "unknown", that is when other threads
  56335. will determine that the node is available for data delivery and the data buffer connectors can be
  56336. initialized. Therefore, it's important that it is set after the data supply has been initialized.
  56337. */
  56338. if ((pJob->data.resourceManager.loadDataBufferNode.flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_DECODE) != 0) {
  56339. /*
  56340. Decoding. This is the complex case because we're not going to be doing the entire decoding
  56341. process here. Instead it's going to be split of multiple jobs and loaded in pages. The
  56342. reason for this is to evenly distribute decoding time across multiple sounds, rather than
  56343. having one huge sound hog all the available processing resources.
  56344. The first thing we do is initialize a decoder. This is allocated on the heap and is passed
  56345. around to the paging jobs. When the last paging job has completed it's processing, it'll
  56346. free the decoder for us.
  56347. This job does not do any actual decoding. It instead just posts a PAGE_DATA_BUFFER_NODE job
  56348. which is where the actual decoding work will be done. However, once this job is complete,
  56349. the node will be in a state where data buffer connectors can be initialized.
  56350. */
  56351. ma_decoder* pDecoder; /* <-- Free'd on the last page decode. */
  56352. ma_job pageDataBufferNodeJob;
  56353. /* Allocate the decoder by initializing a decoded data supply. */
  56354. 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);
  56355. /*
  56356. Don't ever propagate an MA_BUSY result code or else the resource manager will think the
  56357. node is just busy decoding rather than in an error state. This should never happen, but
  56358. including this logic for safety just in case.
  56359. */
  56360. if (result == MA_BUSY) {
  56361. result = MA_ERROR;
  56362. }
  56363. if (result != MA_SUCCESS) {
  56364. if (pJob->data.resourceManager.loadDataBufferNode.pFilePath != NULL) {
  56365. 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));
  56366. } else {
  56367. #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(_MSC_VER)
  56368. 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));
  56369. #endif
  56370. }
  56371. goto done;
  56372. }
  56373. /*
  56374. At this point the node's data supply is initialized and other threads can start initializing
  56375. their data buffer connectors. However, no data will actually be available until we start to
  56376. actually decode it. To do this, we need to post a paging job which is where the decoding
  56377. work is done.
  56378. Note that if an error occurred at an earlier point, this section will have been skipped.
  56379. */
  56380. pageDataBufferNodeJob = ma_job_init(MA_JOB_TYPE_RESOURCE_MANAGER_PAGE_DATA_BUFFER_NODE);
  56381. pageDataBufferNodeJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode);
  56382. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pResourceManager = pResourceManager;
  56383. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDataBufferNode = pDataBufferNode;
  56384. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDecoder = pDecoder;
  56385. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneNotification = pJob->data.resourceManager.loadDataBufferNode.pDoneNotification;
  56386. pageDataBufferNodeJob.data.resourceManager.pageDataBufferNode.pDoneFence = pJob->data.resourceManager.loadDataBufferNode.pDoneFence;
  56387. /* The job has been set up so it can now be posted. */
  56388. result = ma_resource_manager_post_job(pResourceManager, &pageDataBufferNodeJob);
  56389. /*
  56390. When we get here, we want to make sure the result code is set to MA_BUSY. The reason for
  56391. this is that the result will be copied over to the node's internal result variable. In
  56392. this case, since the decoding is still in-progress, we need to make sure the result code
  56393. is set to MA_BUSY.
  56394. */
  56395. if (result != MA_SUCCESS) {
  56396. 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));
  56397. ma_decoder_uninit(pDecoder);
  56398. ma_free(pDecoder, &pResourceManager->config.allocationCallbacks);
  56399. } else {
  56400. result = MA_BUSY;
  56401. }
  56402. } else {
  56403. /* No decoding. This is the simple case. We need only read the file content into memory and we're done. */
  56404. result = ma_resource_manager_data_buffer_node_init_supply_encoded(pResourceManager, pDataBufferNode, pJob->data.resourceManager.loadDataBufferNode.pFilePath, pJob->data.resourceManager.loadDataBufferNode.pFilePathW);
  56405. }
  56406. done:
  56407. /* File paths are no longer needed. */
  56408. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePath, &pResourceManager->config.allocationCallbacks);
  56409. ma_free(pJob->data.resourceManager.loadDataBufferNode.pFilePathW, &pResourceManager->config.allocationCallbacks);
  56410. /*
  56411. 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
  56412. 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
  56413. 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
  56414. 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
  56415. other error code would cause the buffer to look like it's in a state that it's not.
  56416. */
  56417. c89atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  56418. /* At this point initialization is complete and we can signal the notification if any. */
  56419. if (pJob->data.resourceManager.loadDataBufferNode.pInitNotification != NULL) {
  56420. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pInitNotification);
  56421. }
  56422. if (pJob->data.resourceManager.loadDataBufferNode.pInitFence != NULL) {
  56423. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pInitFence);
  56424. }
  56425. /* If we have a success result it means we've fully loaded the buffer. This will happen in the non-decoding case. */
  56426. if (result != MA_BUSY) {
  56427. if (pJob->data.resourceManager.loadDataBufferNode.pDoneNotification != NULL) {
  56428. ma_async_notification_signal(pJob->data.resourceManager.loadDataBufferNode.pDoneNotification);
  56429. }
  56430. if (pJob->data.resourceManager.loadDataBufferNode.pDoneFence != NULL) {
  56431. ma_fence_release(pJob->data.resourceManager.loadDataBufferNode.pDoneFence);
  56432. }
  56433. }
  56434. /* Increment the node's execution pointer so that the next jobs can be processed. This is how we keep decoding of pages in-order. */
  56435. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  56436. return result;
  56437. }
  56438. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob)
  56439. {
  56440. ma_resource_manager* pResourceManager;
  56441. ma_resource_manager_data_buffer_node* pDataBufferNode;
  56442. MA_ASSERT(pJob != NULL);
  56443. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.freeDataBufferNode.pResourceManager;
  56444. MA_ASSERT(pResourceManager != NULL);
  56445. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.freeDataBufferNode.pDataBufferNode;
  56446. MA_ASSERT(pDataBufferNode != NULL);
  56447. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  56448. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56449. }
  56450. ma_resource_manager_data_buffer_node_free(pResourceManager, pDataBufferNode);
  56451. /* The event needs to be signalled last. */
  56452. if (pJob->data.resourceManager.freeDataBufferNode.pDoneNotification != NULL) {
  56453. ma_async_notification_signal(pJob->data.resourceManager.freeDataBufferNode.pDoneNotification);
  56454. }
  56455. if (pJob->data.resourceManager.freeDataBufferNode.pDoneFence != NULL) {
  56456. ma_fence_release(pJob->data.resourceManager.freeDataBufferNode.pDoneFence);
  56457. }
  56458. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  56459. return MA_SUCCESS;
  56460. }
  56461. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob)
  56462. {
  56463. ma_result result = MA_SUCCESS;
  56464. ma_resource_manager* pResourceManager;
  56465. ma_resource_manager_data_buffer_node* pDataBufferNode;
  56466. MA_ASSERT(pJob != NULL);
  56467. pResourceManager = (ma_resource_manager*)pJob->data.resourceManager.pageDataBufferNode.pResourceManager;
  56468. MA_ASSERT(pResourceManager != NULL);
  56469. pDataBufferNode = (ma_resource_manager_data_buffer_node*)pJob->data.resourceManager.pageDataBufferNode.pDataBufferNode;
  56470. MA_ASSERT(pDataBufferNode != NULL);
  56471. if (pJob->order != c89atomic_load_32(&pDataBufferNode->executionPointer)) {
  56472. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56473. }
  56474. /* Don't do any more decoding if the data buffer has started the uninitialization process. */
  56475. result = ma_resource_manager_data_buffer_node_result(pDataBufferNode);
  56476. if (result != MA_BUSY) {
  56477. goto done;
  56478. }
  56479. /* We're ready to decode the next page. */
  56480. result = ma_resource_manager_data_buffer_node_decode_next_page(pResourceManager, pDataBufferNode, (ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  56481. /*
  56482. If we have a success code by this point, we want to post another job. We're going to set the
  56483. result back to MA_BUSY to make it clear that there's still more to load.
  56484. */
  56485. if (result == MA_SUCCESS) {
  56486. ma_job newJob;
  56487. newJob = *pJob; /* Everything is the same as the input job, except the execution order. */
  56488. newJob.order = ma_resource_manager_data_buffer_node_next_execution_order(pDataBufferNode); /* We need a fresh execution order. */
  56489. result = ma_resource_manager_post_job(pResourceManager, &newJob);
  56490. /* Since the sound isn't yet fully decoded we want the status to be set to busy. */
  56491. if (result == MA_SUCCESS) {
  56492. result = MA_BUSY;
  56493. }
  56494. }
  56495. done:
  56496. /* If there's still more to decode the result will be set to MA_BUSY. Otherwise we can free the decoder. */
  56497. if (result != MA_BUSY) {
  56498. ma_decoder_uninit((ma_decoder*)pJob->data.resourceManager.pageDataBufferNode.pDecoder);
  56499. ma_free(pJob->data.resourceManager.pageDataBufferNode.pDecoder, &pResourceManager->config.allocationCallbacks);
  56500. }
  56501. /* If we reached the end we need to treat it as successful. */
  56502. if (result == MA_AT_END) {
  56503. result = MA_SUCCESS;
  56504. }
  56505. /* Make sure we set the result of node in case some error occurred. */
  56506. c89atomic_compare_and_swap_i32(&pDataBufferNode->result, MA_BUSY, result);
  56507. /* Signal the notification after setting the result in case the notification callback wants to inspect the result code. */
  56508. if (result != MA_BUSY) {
  56509. if (pJob->data.resourceManager.pageDataBufferNode.pDoneNotification != NULL) {
  56510. ma_async_notification_signal(pJob->data.resourceManager.pageDataBufferNode.pDoneNotification);
  56511. }
  56512. if (pJob->data.resourceManager.pageDataBufferNode.pDoneFence != NULL) {
  56513. ma_fence_release(pJob->data.resourceManager.pageDataBufferNode.pDoneFence);
  56514. }
  56515. }
  56516. c89atomic_fetch_add_32(&pDataBufferNode->executionPointer, 1);
  56517. return result;
  56518. }
  56519. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob)
  56520. {
  56521. ma_result result = MA_SUCCESS;
  56522. ma_resource_manager* pResourceManager;
  56523. ma_resource_manager_data_buffer* pDataBuffer;
  56524. ma_resource_manager_data_supply_type dataSupplyType = ma_resource_manager_data_supply_type_unknown;
  56525. ma_bool32 isConnectorInitialized = MA_FALSE;
  56526. /*
  56527. All we're doing here is checking if the node has finished loading. If not, we just re-post the job
  56528. and keep waiting. Otherwise we increment the execution counter and set the buffer's result code.
  56529. */
  56530. MA_ASSERT(pJob != NULL);
  56531. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.loadDataBuffer.pDataBuffer;
  56532. MA_ASSERT(pDataBuffer != NULL);
  56533. pResourceManager = pDataBuffer->pResourceManager;
  56534. if (pJob->order != c89atomic_load_32(&pDataBuffer->executionPointer)) {
  56535. 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. */
  56536. }
  56537. /*
  56538. First thing we need to do is check whether or not the data buffer is getting deleted. If so we
  56539. just abort, but making sure we increment the execution pointer.
  56540. */
  56541. result = ma_resource_manager_data_buffer_result(pDataBuffer);
  56542. if (result != MA_BUSY) {
  56543. goto done; /* <-- This will ensure the exucution pointer is incremented. */
  56544. } else {
  56545. result = MA_SUCCESS; /* <-- Make sure this is reset. */
  56546. }
  56547. /* Try initializing the connector if we haven't already. */
  56548. isConnectorInitialized = pDataBuffer->isConnectorInitialized;
  56549. if (isConnectorInitialized == MA_FALSE) {
  56550. dataSupplyType = ma_resource_manager_data_buffer_node_get_data_supply_type(pDataBuffer->pNode);
  56551. if (dataSupplyType != ma_resource_manager_data_supply_type_unknown) {
  56552. /* We can now initialize the connector. If this fails, we need to abort. It's very rare for this to fail. */
  56553. ma_resource_manager_data_source_config dataSourceConfig; /* For setting initial looping state and range. */
  56554. dataSourceConfig = ma_resource_manager_data_source_config_init();
  56555. dataSourceConfig.rangeBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeBegInPCMFrames;
  56556. dataSourceConfig.rangeEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.rangeEndInPCMFrames;
  56557. dataSourceConfig.loopPointBegInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointBegInPCMFrames;
  56558. dataSourceConfig.loopPointEndInPCMFrames = pJob->data.resourceManager.loadDataBuffer.loopPointEndInPCMFrames;
  56559. dataSourceConfig.isLooping = pJob->data.resourceManager.loadDataBuffer.isLooping;
  56560. result = ma_resource_manager_data_buffer_init_connector(pDataBuffer, &dataSourceConfig, pJob->data.resourceManager.loadDataBuffer.pInitNotification, pJob->data.resourceManager.loadDataBuffer.pInitFence);
  56561. if (result != MA_SUCCESS) {
  56562. 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));
  56563. goto done;
  56564. }
  56565. } else {
  56566. /* 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. */
  56567. }
  56568. } else {
  56569. /* The connector is already initialized. Nothing to do here. */
  56570. }
  56571. /*
  56572. If the data node is still loading, we need to repost the job and *not* increment the execution
  56573. pointer (i.e. we need to not fall through to the "done" label).
  56574. There is a hole between here and the where the data connector is initialized where the data
  56575. buffer node may have finished initializing. We need to check for this by checking the result of
  56576. the data buffer node and whether or not we had an unknown data supply type at the time of
  56577. trying to initialize the data connector.
  56578. */
  56579. result = ma_resource_manager_data_buffer_node_result(pDataBuffer->pNode);
  56580. if (result == MA_BUSY || (result == MA_SUCCESS && isConnectorInitialized == MA_FALSE && dataSupplyType == ma_resource_manager_data_supply_type_unknown)) {
  56581. return ma_resource_manager_post_job(pResourceManager, pJob);
  56582. }
  56583. done:
  56584. /* Only move away from a busy code so that we don't trash any existing error codes. */
  56585. c89atomic_compare_and_swap_i32(&pDataBuffer->result, MA_BUSY, result);
  56586. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  56587. if (pJob->data.resourceManager.loadDataBuffer.pDoneNotification != NULL) {
  56588. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pDoneNotification);
  56589. }
  56590. if (pJob->data.resourceManager.loadDataBuffer.pDoneFence != NULL) {
  56591. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pDoneFence);
  56592. }
  56593. /*
  56594. If at this point the data buffer has not had it's connector initialized, it means the
  56595. notification event was never signalled which means we need to signal it here.
  56596. */
  56597. if (pDataBuffer->isConnectorInitialized == MA_FALSE && result != MA_SUCCESS) {
  56598. if (pJob->data.resourceManager.loadDataBuffer.pInitNotification != NULL) {
  56599. ma_async_notification_signal(pJob->data.resourceManager.loadDataBuffer.pInitNotification);
  56600. }
  56601. if (pJob->data.resourceManager.loadDataBuffer.pInitFence != NULL) {
  56602. ma_fence_release(pJob->data.resourceManager.loadDataBuffer.pInitFence);
  56603. }
  56604. }
  56605. c89atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  56606. return result;
  56607. }
  56608. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob)
  56609. {
  56610. ma_resource_manager* pResourceManager;
  56611. ma_resource_manager_data_buffer* pDataBuffer;
  56612. MA_ASSERT(pJob != NULL);
  56613. pDataBuffer = (ma_resource_manager_data_buffer*)pJob->data.resourceManager.freeDataBuffer.pDataBuffer;
  56614. MA_ASSERT(pDataBuffer != NULL);
  56615. pResourceManager = pDataBuffer->pResourceManager;
  56616. if (pJob->order != c89atomic_load_32(&pDataBuffer->executionPointer)) {
  56617. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56618. }
  56619. ma_resource_manager_data_buffer_uninit_internal(pDataBuffer);
  56620. /* The event needs to be signalled last. */
  56621. if (pJob->data.resourceManager.freeDataBuffer.pDoneNotification != NULL) {
  56622. ma_async_notification_signal(pJob->data.resourceManager.freeDataBuffer.pDoneNotification);
  56623. }
  56624. if (pJob->data.resourceManager.freeDataBuffer.pDoneFence != NULL) {
  56625. ma_fence_release(pJob->data.resourceManager.freeDataBuffer.pDoneFence);
  56626. }
  56627. c89atomic_fetch_add_32(&pDataBuffer->executionPointer, 1);
  56628. return MA_SUCCESS;
  56629. }
  56630. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob)
  56631. {
  56632. ma_result result = MA_SUCCESS;
  56633. ma_decoder_config decoderConfig;
  56634. ma_uint32 pageBufferSizeInBytes;
  56635. ma_resource_manager* pResourceManager;
  56636. ma_resource_manager_data_stream* pDataStream;
  56637. MA_ASSERT(pJob != NULL);
  56638. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.loadDataStream.pDataStream;
  56639. MA_ASSERT(pDataStream != NULL);
  56640. pResourceManager = pDataStream->pResourceManager;
  56641. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  56642. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56643. }
  56644. if (ma_resource_manager_data_stream_result(pDataStream) != MA_BUSY) {
  56645. result = MA_INVALID_OPERATION; /* Most likely the data stream is being uninitialized. */
  56646. goto done;
  56647. }
  56648. /* We need to initialize the decoder first so we can determine the size of the pages. */
  56649. decoderConfig = ma_resource_manager__init_decoder_config(pResourceManager);
  56650. if (pJob->data.resourceManager.loadDataStream.pFilePath != NULL) {
  56651. result = ma_decoder_init_vfs(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePath, &decoderConfig, &pDataStream->decoder);
  56652. } else {
  56653. result = ma_decoder_init_vfs_w(pResourceManager->config.pVFS, pJob->data.resourceManager.loadDataStream.pFilePathW, &decoderConfig, &pDataStream->decoder);
  56654. }
  56655. if (result != MA_SUCCESS) {
  56656. goto done;
  56657. }
  56658. /* Retrieve the total length of the file before marking the decoder are loaded. */
  56659. if ((pDataStream->flags & MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_UNKNOWN_LENGTH) == 0) {
  56660. result = ma_decoder_get_length_in_pcm_frames(&pDataStream->decoder, &pDataStream->totalLengthInPCMFrames);
  56661. if (result != MA_SUCCESS) {
  56662. goto done; /* Failed to retrieve the length. */
  56663. }
  56664. } else {
  56665. pDataStream->totalLengthInPCMFrames = 0;
  56666. }
  56667. /*
  56668. 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
  56669. and we don't want to have another thread trying to access the decoder while it's scanning.
  56670. */
  56671. pDataStream->isDecoderInitialized = MA_TRUE;
  56672. /* We have the decoder so we can now initialize our page buffer. */
  56673. pageBufferSizeInBytes = ma_resource_manager_data_stream_get_page_size_in_frames(pDataStream) * 2 * ma_get_bytes_per_frame(pDataStream->decoder.outputFormat, pDataStream->decoder.outputChannels);
  56674. pDataStream->pPageData = ma_malloc(pageBufferSizeInBytes, &pResourceManager->config.allocationCallbacks);
  56675. if (pDataStream->pPageData == NULL) {
  56676. ma_decoder_uninit(&pDataStream->decoder);
  56677. result = MA_OUT_OF_MEMORY;
  56678. goto done;
  56679. }
  56680. /* Seek to our initial seek point before filling the initial pages. */
  56681. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.loadDataStream.initialSeekPoint);
  56682. /* We have our decoder and our page buffer, so now we need to fill our pages. */
  56683. ma_resource_manager_data_stream_fill_pages(pDataStream);
  56684. /* And now we're done. We want to make sure the result is MA_SUCCESS. */
  56685. result = MA_SUCCESS;
  56686. done:
  56687. ma_free(pJob->data.resourceManager.loadDataStream.pFilePath, &pResourceManager->config.allocationCallbacks);
  56688. ma_free(pJob->data.resourceManager.loadDataStream.pFilePathW, &pResourceManager->config.allocationCallbacks);
  56689. /* 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). */
  56690. c89atomic_compare_and_swap_i32(&pDataStream->result, MA_BUSY, result);
  56691. /* Only signal the other threads after the result has been set just for cleanliness sake. */
  56692. if (pJob->data.resourceManager.loadDataStream.pInitNotification != NULL) {
  56693. ma_async_notification_signal(pJob->data.resourceManager.loadDataStream.pInitNotification);
  56694. }
  56695. if (pJob->data.resourceManager.loadDataStream.pInitFence != NULL) {
  56696. ma_fence_release(pJob->data.resourceManager.loadDataStream.pInitFence);
  56697. }
  56698. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  56699. return result;
  56700. }
  56701. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob)
  56702. {
  56703. ma_resource_manager* pResourceManager;
  56704. ma_resource_manager_data_stream* pDataStream;
  56705. MA_ASSERT(pJob != NULL);
  56706. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.freeDataStream.pDataStream;
  56707. MA_ASSERT(pDataStream != NULL);
  56708. pResourceManager = pDataStream->pResourceManager;
  56709. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  56710. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56711. }
  56712. /* If our status is not MA_UNAVAILABLE we have a bug somewhere. */
  56713. MA_ASSERT(ma_resource_manager_data_stream_result(pDataStream) == MA_UNAVAILABLE);
  56714. if (pDataStream->isDecoderInitialized) {
  56715. ma_decoder_uninit(&pDataStream->decoder);
  56716. }
  56717. if (pDataStream->pPageData != NULL) {
  56718. ma_free(pDataStream->pPageData, &pResourceManager->config.allocationCallbacks);
  56719. pDataStream->pPageData = NULL; /* Just in case... */
  56720. }
  56721. ma_data_source_uninit(&pDataStream->ds);
  56722. /* The event needs to be signalled last. */
  56723. if (pJob->data.resourceManager.freeDataStream.pDoneNotification != NULL) {
  56724. ma_async_notification_signal(pJob->data.resourceManager.freeDataStream.pDoneNotification);
  56725. }
  56726. if (pJob->data.resourceManager.freeDataStream.pDoneFence != NULL) {
  56727. ma_fence_release(pJob->data.resourceManager.freeDataStream.pDoneFence);
  56728. }
  56729. /*c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);*/
  56730. return MA_SUCCESS;
  56731. }
  56732. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob)
  56733. {
  56734. ma_result result = MA_SUCCESS;
  56735. ma_resource_manager* pResourceManager;
  56736. ma_resource_manager_data_stream* pDataStream;
  56737. MA_ASSERT(pJob != NULL);
  56738. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.pageDataStream.pDataStream;
  56739. MA_ASSERT(pDataStream != NULL);
  56740. pResourceManager = pDataStream->pResourceManager;
  56741. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  56742. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56743. }
  56744. /* For streams, the status should be MA_SUCCESS. */
  56745. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS) {
  56746. result = MA_INVALID_OPERATION;
  56747. goto done;
  56748. }
  56749. ma_resource_manager_data_stream_fill_page(pDataStream, pJob->data.resourceManager.pageDataStream.pageIndex);
  56750. done:
  56751. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  56752. return result;
  56753. }
  56754. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob)
  56755. {
  56756. ma_result result = MA_SUCCESS;
  56757. ma_resource_manager* pResourceManager;
  56758. ma_resource_manager_data_stream* pDataStream;
  56759. MA_ASSERT(pJob != NULL);
  56760. pDataStream = (ma_resource_manager_data_stream*)pJob->data.resourceManager.seekDataStream.pDataStream;
  56761. MA_ASSERT(pDataStream != NULL);
  56762. pResourceManager = pDataStream->pResourceManager;
  56763. if (pJob->order != c89atomic_load_32(&pDataStream->executionPointer)) {
  56764. return ma_resource_manager_post_job(pResourceManager, pJob); /* Out of order. */
  56765. }
  56766. /* For streams the status should be MA_SUCCESS for this to do anything. */
  56767. if (ma_resource_manager_data_stream_result(pDataStream) != MA_SUCCESS || pDataStream->isDecoderInitialized == MA_FALSE) {
  56768. result = MA_INVALID_OPERATION;
  56769. goto done;
  56770. }
  56771. /*
  56772. 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
  56773. instead of initializing the decoder, we seek to a frame.
  56774. */
  56775. ma_decoder_seek_to_pcm_frame(&pDataStream->decoder, pJob->data.resourceManager.seekDataStream.frameIndex);
  56776. /* After seeking we'll need to reload the pages. */
  56777. ma_resource_manager_data_stream_fill_pages(pDataStream);
  56778. /* We need to let the public API know that we're done seeking. */
  56779. c89atomic_fetch_sub_32(&pDataStream->seekCounter, 1);
  56780. done:
  56781. c89atomic_fetch_add_32(&pDataStream->executionPointer, 1);
  56782. return result;
  56783. }
  56784. MA_API ma_result ma_resource_manager_process_job(ma_resource_manager* pResourceManager, ma_job* pJob)
  56785. {
  56786. if (pResourceManager == NULL || pJob == NULL) {
  56787. return MA_INVALID_ARGS;
  56788. }
  56789. return ma_job_process(pJob);
  56790. }
  56791. MA_API ma_result ma_resource_manager_process_next_job(ma_resource_manager* pResourceManager)
  56792. {
  56793. ma_result result;
  56794. ma_job job;
  56795. if (pResourceManager == NULL) {
  56796. return MA_INVALID_ARGS;
  56797. }
  56798. /* This will return MA_CANCELLED if the next job is a quit job. */
  56799. result = ma_resource_manager_next_job(pResourceManager, &job);
  56800. if (result != MA_SUCCESS) {
  56801. return result;
  56802. }
  56803. return ma_job_process(&job);
  56804. }
  56805. #else
  56806. /* 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. */
  56807. static ma_result ma_job_process__resource_manager__load_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56808. static ma_result ma_job_process__resource_manager__free_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56809. static ma_result ma_job_process__resource_manager__page_data_buffer_node(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56810. static ma_result ma_job_process__resource_manager__load_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56811. static ma_result ma_job_process__resource_manager__free_data_buffer(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56812. static ma_result ma_job_process__resource_manager__load_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56813. static ma_result ma_job_process__resource_manager__free_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56814. static ma_result ma_job_process__resource_manager__page_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56815. static ma_result ma_job_process__resource_manager__seek_data_stream(ma_job* pJob) { return ma_job_process__noop(pJob); }
  56816. #endif /* MA_NO_RESOURCE_MANAGER */
  56817. #ifndef MA_NO_NODE_GRAPH
  56818. /* 10ms @ 48K = 480. Must never exceed 65535. */
  56819. #ifndef MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS
  56820. #define MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS 480
  56821. #endif
  56822. 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);
  56823. 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)
  56824. {
  56825. #ifndef MA_NO_GENERATION
  56826. {
  56827. ma_waveform_config waveformConfig;
  56828. ma_waveform waveform;
  56829. waveformConfig = ma_waveform_config_init(format, channels, sampleRate, ma_waveform_type_sine, 1.0, 400);
  56830. ma_waveform_init(&waveformConfig, &waveform);
  56831. ma_waveform_read_pcm_frames(&waveform, pFramesOut, frameCount, NULL);
  56832. }
  56833. #else
  56834. {
  56835. (void)pFramesOut;
  56836. (void)frameCount;
  56837. (void)format;
  56838. (void)channels;
  56839. (void)sampleRate;
  56840. #if defined(MA_DEBUG_OUTPUT)
  56841. {
  56842. #if _MSC_VER
  56843. #pragma message ("ma_debug_fill_pcm_frames_with_sine_wave() will do nothing because MA_NO_GENERATION is enabled.")
  56844. #endif
  56845. }
  56846. #endif
  56847. }
  56848. #endif
  56849. }
  56850. static ma_result ma_mix_pcm_frames_f32(float* pDst, const float* pSrc, ma_uint64 frameCount, ma_uint32 channels, float volume)
  56851. {
  56852. ma_uint64 iSample;
  56853. ma_uint64 sampleCount;
  56854. if (pDst == NULL || pSrc == NULL || channels == 0) {
  56855. return MA_INVALID_ARGS;
  56856. }
  56857. if (volume == 0) {
  56858. return MA_SUCCESS; /* No changes if the volume is 0. */
  56859. }
  56860. sampleCount = frameCount * channels;
  56861. if (volume == 1) {
  56862. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  56863. pDst[iSample] += pSrc[iSample];
  56864. }
  56865. } else {
  56866. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  56867. pDst[iSample] += ma_apply_volume_unclipped_f32(pSrc[iSample], volume);
  56868. }
  56869. }
  56870. return MA_SUCCESS;
  56871. }
  56872. MA_API ma_node_graph_config ma_node_graph_config_init(ma_uint32 channels)
  56873. {
  56874. ma_node_graph_config config;
  56875. MA_ZERO_OBJECT(&config);
  56876. config.channels = channels;
  56877. config.nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  56878. return config;
  56879. }
  56880. static void ma_node_graph_set_is_reading(ma_node_graph* pNodeGraph, ma_bool32 isReading)
  56881. {
  56882. MA_ASSERT(pNodeGraph != NULL);
  56883. c89atomic_exchange_32(&pNodeGraph->isReading, isReading);
  56884. }
  56885. #if 0
  56886. static ma_bool32 ma_node_graph_is_reading(ma_node_graph* pNodeGraph)
  56887. {
  56888. MA_ASSERT(pNodeGraph != NULL);
  56889. return c89atomic_load_32(&pNodeGraph->isReading);
  56890. }
  56891. #endif
  56892. static void ma_node_graph_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  56893. {
  56894. ma_node_graph* pNodeGraph = (ma_node_graph*)pNode;
  56895. ma_uint64 framesRead;
  56896. ma_node_graph_read_pcm_frames(pNodeGraph, ppFramesOut[0], *pFrameCountOut, &framesRead);
  56897. *pFrameCountOut = (ma_uint32)framesRead; /* Safe cast. */
  56898. (void)ppFramesIn;
  56899. (void)pFrameCountIn;
  56900. }
  56901. static ma_node_vtable g_node_graph_node_vtable =
  56902. {
  56903. ma_node_graph_node_process_pcm_frames,
  56904. NULL, /* onGetRequiredInputFrameCount */
  56905. 0, /* 0 input buses. */
  56906. 1, /* 1 output bus. */
  56907. 0 /* Flags. */
  56908. };
  56909. static void ma_node_graph_endpoint_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  56910. {
  56911. MA_ASSERT(pNode != NULL);
  56912. MA_ASSERT(ma_node_get_input_bus_count(pNode) == 1);
  56913. MA_ASSERT(ma_node_get_output_bus_count(pNode) == 1);
  56914. /* Input channel count needs to be the same as the output channel count. */
  56915. MA_ASSERT(ma_node_get_input_channels(pNode, 0) == ma_node_get_output_channels(pNode, 0));
  56916. /* We don't need to do anything here because it's a passthrough. */
  56917. (void)pNode;
  56918. (void)ppFramesIn;
  56919. (void)pFrameCountIn;
  56920. (void)ppFramesOut;
  56921. (void)pFrameCountOut;
  56922. #if 0
  56923. /* The data has already been mixed. We just need to move it to the output buffer. */
  56924. if (ppFramesIn != NULL) {
  56925. ma_copy_pcm_frames(ppFramesOut[0], ppFramesIn[0], *pFrameCountOut, ma_format_f32, ma_node_get_output_channels(pNode, 0));
  56926. }
  56927. #endif
  56928. }
  56929. static ma_node_vtable g_node_graph_endpoint_vtable =
  56930. {
  56931. ma_node_graph_endpoint_process_pcm_frames,
  56932. NULL, /* onGetRequiredInputFrameCount */
  56933. 1, /* 1 input bus. */
  56934. 1, /* 1 output bus. */
  56935. MA_NODE_FLAG_PASSTHROUGH /* Flags. The endpoint is a passthrough. */
  56936. };
  56937. MA_API ma_result ma_node_graph_init(const ma_node_graph_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node_graph* pNodeGraph)
  56938. {
  56939. ma_result result;
  56940. ma_node_config baseConfig;
  56941. ma_node_config endpointConfig;
  56942. if (pNodeGraph == NULL) {
  56943. return MA_INVALID_ARGS;
  56944. }
  56945. MA_ZERO_OBJECT(pNodeGraph);
  56946. pNodeGraph->nodeCacheCapInFrames = pConfig->nodeCacheCapInFrames;
  56947. if (pNodeGraph->nodeCacheCapInFrames == 0) {
  56948. pNodeGraph->nodeCacheCapInFrames = MA_DEFAULT_NODE_CACHE_CAP_IN_FRAMES_PER_BUS;
  56949. }
  56950. /* Base node so we can use the node graph as a node into another graph. */
  56951. baseConfig = ma_node_config_init();
  56952. baseConfig.vtable = &g_node_graph_node_vtable;
  56953. baseConfig.pOutputChannels = &pConfig->channels;
  56954. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pNodeGraph->base);
  56955. if (result != MA_SUCCESS) {
  56956. return result;
  56957. }
  56958. /* Endpoint. */
  56959. endpointConfig = ma_node_config_init();
  56960. endpointConfig.vtable = &g_node_graph_endpoint_vtable;
  56961. endpointConfig.pInputChannels = &pConfig->channels;
  56962. endpointConfig.pOutputChannels = &pConfig->channels;
  56963. result = ma_node_init(pNodeGraph, &endpointConfig, pAllocationCallbacks, &pNodeGraph->endpoint);
  56964. if (result != MA_SUCCESS) {
  56965. ma_node_uninit(&pNodeGraph->base, pAllocationCallbacks);
  56966. return result;
  56967. }
  56968. return MA_SUCCESS;
  56969. }
  56970. MA_API void ma_node_graph_uninit(ma_node_graph* pNodeGraph, const ma_allocation_callbacks* pAllocationCallbacks)
  56971. {
  56972. if (pNodeGraph == NULL) {
  56973. return;
  56974. }
  56975. ma_node_uninit(&pNodeGraph->endpoint, pAllocationCallbacks);
  56976. }
  56977. MA_API ma_node* ma_node_graph_get_endpoint(ma_node_graph* pNodeGraph)
  56978. {
  56979. if (pNodeGraph == NULL) {
  56980. return NULL;
  56981. }
  56982. return &pNodeGraph->endpoint;
  56983. }
  56984. MA_API ma_result ma_node_graph_read_pcm_frames(ma_node_graph* pNodeGraph, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  56985. {
  56986. ma_result result = MA_SUCCESS;
  56987. ma_uint64 totalFramesRead;
  56988. ma_uint32 channels;
  56989. if (pFramesRead != NULL) {
  56990. *pFramesRead = 0; /* Safety. */
  56991. }
  56992. if (pNodeGraph == NULL) {
  56993. return MA_INVALID_ARGS;
  56994. }
  56995. channels = ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  56996. /* We'll be nice and try to do a full read of all frameCount frames. */
  56997. totalFramesRead = 0;
  56998. while (totalFramesRead < frameCount) {
  56999. ma_uint32 framesJustRead;
  57000. ma_uint64 framesToRead = frameCount - totalFramesRead;
  57001. if (framesToRead > 0xFFFFFFFF) {
  57002. framesToRead = 0xFFFFFFFF;
  57003. }
  57004. ma_node_graph_set_is_reading(pNodeGraph, MA_TRUE);
  57005. {
  57006. 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));
  57007. }
  57008. ma_node_graph_set_is_reading(pNodeGraph, MA_FALSE);
  57009. totalFramesRead += framesJustRead;
  57010. if (result != MA_SUCCESS) {
  57011. break;
  57012. }
  57013. /* Abort if we weren't able to read any frames or else we risk getting stuck in a loop. */
  57014. if (framesJustRead == 0) {
  57015. break;
  57016. }
  57017. }
  57018. /* 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. */
  57019. if (totalFramesRead < frameCount) {
  57020. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, totalFramesRead, ma_format_f32, channels), (frameCount - totalFramesRead), ma_format_f32, channels);
  57021. }
  57022. if (pFramesRead != NULL) {
  57023. *pFramesRead = totalFramesRead;
  57024. }
  57025. return result;
  57026. }
  57027. MA_API ma_uint32 ma_node_graph_get_channels(const ma_node_graph* pNodeGraph)
  57028. {
  57029. if (pNodeGraph == NULL) {
  57030. return 0;
  57031. }
  57032. return ma_node_get_output_channels(&pNodeGraph->endpoint, 0);
  57033. }
  57034. MA_API ma_uint64 ma_node_graph_get_time(const ma_node_graph* pNodeGraph)
  57035. {
  57036. if (pNodeGraph == NULL) {
  57037. return 0;
  57038. }
  57039. return ma_node_get_time(&pNodeGraph->endpoint); /* Global time is just the local time of the endpoint. */
  57040. }
  57041. MA_API ma_result ma_node_graph_set_time(ma_node_graph* pNodeGraph, ma_uint64 globalTime)
  57042. {
  57043. if (pNodeGraph == NULL) {
  57044. return MA_INVALID_ARGS;
  57045. }
  57046. return ma_node_set_time(&pNodeGraph->endpoint, globalTime); /* Global time is just the local time of the endpoint. */
  57047. }
  57048. #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. */
  57049. static ma_result ma_node_output_bus_init(ma_node* pNode, ma_uint32 outputBusIndex, ma_uint32 channels, ma_node_output_bus* pOutputBus)
  57050. {
  57051. MA_ASSERT(pOutputBus != NULL);
  57052. MA_ASSERT(outputBusIndex < MA_MAX_NODE_BUS_COUNT);
  57053. MA_ASSERT(outputBusIndex < ma_node_get_output_bus_count(pNode));
  57054. MA_ASSERT(channels < 256);
  57055. MA_ZERO_OBJECT(pOutputBus);
  57056. if (channels == 0) {
  57057. return MA_INVALID_ARGS;
  57058. }
  57059. pOutputBus->pNode = pNode;
  57060. pOutputBus->outputBusIndex = (ma_uint8)outputBusIndex;
  57061. pOutputBus->channels = (ma_uint8)channels;
  57062. pOutputBus->flags = MA_NODE_OUTPUT_BUS_FLAG_HAS_READ; /* <-- Important that this flag is set by default. */
  57063. pOutputBus->volume = 1;
  57064. return MA_SUCCESS;
  57065. }
  57066. static void ma_node_output_bus_lock(ma_node_output_bus* pOutputBus)
  57067. {
  57068. ma_spinlock_lock(&pOutputBus->lock);
  57069. }
  57070. static void ma_node_output_bus_unlock(ma_node_output_bus* pOutputBus)
  57071. {
  57072. ma_spinlock_unlock(&pOutputBus->lock);
  57073. }
  57074. static ma_uint32 ma_node_output_bus_get_channels(const ma_node_output_bus* pOutputBus)
  57075. {
  57076. return pOutputBus->channels;
  57077. }
  57078. static void ma_node_output_bus_set_has_read(ma_node_output_bus* pOutputBus, ma_bool32 hasRead)
  57079. {
  57080. if (hasRead) {
  57081. c89atomic_fetch_or_32(&pOutputBus->flags, MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  57082. } else {
  57083. c89atomic_fetch_and_32(&pOutputBus->flags, (ma_uint32)~MA_NODE_OUTPUT_BUS_FLAG_HAS_READ);
  57084. }
  57085. }
  57086. static ma_bool32 ma_node_output_bus_has_read(ma_node_output_bus* pOutputBus)
  57087. {
  57088. return (c89atomic_load_32(&pOutputBus->flags) & MA_NODE_OUTPUT_BUS_FLAG_HAS_READ) != 0;
  57089. }
  57090. static void ma_node_output_bus_set_is_attached(ma_node_output_bus* pOutputBus, ma_bool32 isAttached)
  57091. {
  57092. c89atomic_exchange_32(&pOutputBus->isAttached, isAttached);
  57093. }
  57094. static ma_bool32 ma_node_output_bus_is_attached(ma_node_output_bus* pOutputBus)
  57095. {
  57096. return c89atomic_load_32(&pOutputBus->isAttached);
  57097. }
  57098. static ma_result ma_node_output_bus_set_volume(ma_node_output_bus* pOutputBus, float volume)
  57099. {
  57100. MA_ASSERT(pOutputBus != NULL);
  57101. if (volume < 0.0f) {
  57102. volume = 0.0f;
  57103. }
  57104. c89atomic_exchange_f32(&pOutputBus->volume, volume);
  57105. return MA_SUCCESS;
  57106. }
  57107. static float ma_node_output_bus_get_volume(const ma_node_output_bus* pOutputBus)
  57108. {
  57109. return c89atomic_load_f32((float*)&pOutputBus->volume);
  57110. }
  57111. static ma_result ma_node_input_bus_init(ma_uint32 channels, ma_node_input_bus* pInputBus)
  57112. {
  57113. MA_ASSERT(pInputBus != NULL);
  57114. MA_ASSERT(channels < 256);
  57115. MA_ZERO_OBJECT(pInputBus);
  57116. if (channels == 0) {
  57117. return MA_INVALID_ARGS;
  57118. }
  57119. pInputBus->channels = (ma_uint8)channels;
  57120. return MA_SUCCESS;
  57121. }
  57122. static void ma_node_input_bus_lock(ma_node_input_bus* pInputBus)
  57123. {
  57124. MA_ASSERT(pInputBus != NULL);
  57125. ma_spinlock_lock(&pInputBus->lock);
  57126. }
  57127. static void ma_node_input_bus_unlock(ma_node_input_bus* pInputBus)
  57128. {
  57129. MA_ASSERT(pInputBus != NULL);
  57130. ma_spinlock_unlock(&pInputBus->lock);
  57131. }
  57132. static void ma_node_input_bus_next_begin(ma_node_input_bus* pInputBus)
  57133. {
  57134. c89atomic_fetch_add_32(&pInputBus->nextCounter, 1);
  57135. }
  57136. static void ma_node_input_bus_next_end(ma_node_input_bus* pInputBus)
  57137. {
  57138. c89atomic_fetch_sub_32(&pInputBus->nextCounter, 1);
  57139. }
  57140. static ma_uint32 ma_node_input_bus_get_next_counter(ma_node_input_bus* pInputBus)
  57141. {
  57142. return c89atomic_load_32(&pInputBus->nextCounter);
  57143. }
  57144. static ma_uint32 ma_node_input_bus_get_channels(const ma_node_input_bus* pInputBus)
  57145. {
  57146. return pInputBus->channels;
  57147. }
  57148. static void ma_node_input_bus_detach__no_output_bus_lock(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  57149. {
  57150. MA_ASSERT(pInputBus != NULL);
  57151. MA_ASSERT(pOutputBus != NULL);
  57152. /*
  57153. Mark the output bus as detached first. This will prevent future iterations on the audio thread
  57154. from iterating this output bus.
  57155. */
  57156. ma_node_output_bus_set_is_attached(pOutputBus, MA_FALSE);
  57157. /*
  57158. We cannot use the output bus lock here since it'll be getting used at a higher level, but we do
  57159. still need to use the input bus lock since we'll be updating pointers on two different output
  57160. buses. The same rules apply here as the attaching case. Although we're using a lock here, we're
  57161. *not* using a lock when iterating over the list in the audio thread. We therefore need to craft
  57162. this in a way such that the iteration on the audio thread doesn't break.
  57163. The the first thing to do is swap out the "next" pointer of the previous output bus with the
  57164. new "next" output bus. This is the operation that matters for iteration on the audio thread.
  57165. After that, the previous pointer on the new "next" pointer needs to be updated, after which
  57166. point the linked list will be in a good state.
  57167. */
  57168. ma_node_input_bus_lock(pInputBus);
  57169. {
  57170. ma_node_output_bus* pOldPrev = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pPrev);
  57171. ma_node_output_bus* pOldNext = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pNext);
  57172. if (pOldPrev != NULL) {
  57173. c89atomic_exchange_ptr(&pOldPrev->pNext, pOldNext); /* <-- This is where the output bus is detached from the list. */
  57174. }
  57175. if (pOldNext != NULL) {
  57176. c89atomic_exchange_ptr(&pOldNext->pPrev, pOldPrev); /* <-- This is required for detachment. */
  57177. }
  57178. }
  57179. ma_node_input_bus_unlock(pInputBus);
  57180. /* At this point the output bus is detached and the linked list is completely unaware of it. Reset some data for safety. */
  57181. c89atomic_exchange_ptr(&pOutputBus->pNext, NULL); /* Using atomic exchanges here, mainly for the benefit of analysis tools which don't always recognize spinlocks. */
  57182. c89atomic_exchange_ptr(&pOutputBus->pPrev, NULL); /* As above. */
  57183. pOutputBus->pInputNode = NULL;
  57184. pOutputBus->inputNodeInputBusIndex = 0;
  57185. /*
  57186. For thread-safety reasons, we don't want to be returning from this straight away. We need to
  57187. wait for the audio thread to finish with the output bus. There's two things we need to wait
  57188. for. The first is the part that selects the next output bus in the list, and the other is the
  57189. part that reads from the output bus. Basically all we're doing is waiting for the input bus
  57190. to stop referencing the output bus.
  57191. We're doing this part last because we want the section above to run while the audio thread
  57192. is finishing up with the output bus, just for efficiency reasons. We marked the output bus as
  57193. detached right at the top of this function which is going to prevent the audio thread from
  57194. iterating the output bus again.
  57195. */
  57196. /* Part 1: Wait for the current iteration to complete. */
  57197. while (ma_node_input_bus_get_next_counter(pInputBus) > 0) {
  57198. ma_yield();
  57199. }
  57200. /* Part 2: Wait for any reads to complete. */
  57201. while (c89atomic_load_32(&pOutputBus->refCount) > 0) {
  57202. ma_yield();
  57203. }
  57204. /*
  57205. At this point we're done detaching and we can be guaranteed that the audio thread is not going
  57206. to attempt to reference this output bus again (until attached again).
  57207. */
  57208. }
  57209. #if 0 /* Not used at the moment, but leaving here in case I need it later. */
  57210. static void ma_node_input_bus_detach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  57211. {
  57212. MA_ASSERT(pInputBus != NULL);
  57213. MA_ASSERT(pOutputBus != NULL);
  57214. ma_node_output_bus_lock(pOutputBus);
  57215. {
  57216. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  57217. }
  57218. ma_node_output_bus_unlock(pOutputBus);
  57219. }
  57220. #endif
  57221. static void ma_node_input_bus_attach(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus, ma_node* pNewInputNode, ma_uint32 inputNodeInputBusIndex)
  57222. {
  57223. MA_ASSERT(pInputBus != NULL);
  57224. MA_ASSERT(pOutputBus != NULL);
  57225. ma_node_output_bus_lock(pOutputBus);
  57226. {
  57227. ma_node_output_bus* pOldInputNode = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pInputNode);
  57228. /* Detach from any existing attachment first if necessary. */
  57229. if (pOldInputNode != NULL) {
  57230. ma_node_input_bus_detach__no_output_bus_lock(pInputBus, pOutputBus);
  57231. }
  57232. /*
  57233. At this point we can be sure the output bus is not attached to anything. The linked list in the
  57234. old input bus has been updated so that pOutputBus will not get iterated again.
  57235. */
  57236. pOutputBus->pInputNode = pNewInputNode; /* No need for an atomic assignment here because modification of this variable always happens within a lock. */
  57237. pOutputBus->inputNodeInputBusIndex = (ma_uint8)inputNodeInputBusIndex; /* As above. */
  57238. /*
  57239. Now we need to attach the output bus to the linked list. This involves updating two pointers on
  57240. two different output buses so I'm going to go ahead and keep this simple and just use a lock.
  57241. There are ways to do this without a lock, but it's just too hard to maintain for it's value.
  57242. Although we're locking here, it's important to remember that we're *not* locking when iterating
  57243. and reading audio data since that'll be running on the audio thread. As a result we need to be
  57244. careful how we craft this so that we don't break iteration. What we're going to do is always
  57245. attach the new item so that it becomes the first item in the list. That way, as we're iterating
  57246. we won't break any links in the list and iteration will continue safely. The detaching case will
  57247. also be crafted in a way as to not break list iteration. It's important to remember to use
  57248. atomic exchanges here since no locking is happening on the audio thread during iteration.
  57249. */
  57250. ma_node_input_bus_lock(pInputBus);
  57251. {
  57252. ma_node_output_bus* pNewPrev = &pInputBus->head;
  57253. ma_node_output_bus* pNewNext = (ma_node_output_bus*)c89atomic_load_ptr(&pInputBus->head.pNext);
  57254. /* Update the local output bus. */
  57255. c89atomic_exchange_ptr(&pOutputBus->pPrev, pNewPrev);
  57256. c89atomic_exchange_ptr(&pOutputBus->pNext, pNewNext);
  57257. /* Update the other output buses to point back to the local output bus. */
  57258. c89atomic_exchange_ptr(&pInputBus->head.pNext, pOutputBus); /* <-- This is where the output bus is actually attached to the input bus. */
  57259. /* Do the previous pointer last. This is only used for detachment. */
  57260. if (pNewNext != NULL) {
  57261. c89atomic_exchange_ptr(&pNewNext->pPrev, pOutputBus);
  57262. }
  57263. }
  57264. ma_node_input_bus_unlock(pInputBus);
  57265. /*
  57266. Mark the node as attached last. This is used to controlling whether or the output bus will be
  57267. iterated on the audio thread. Mainly required for detachment purposes.
  57268. */
  57269. ma_node_output_bus_set_is_attached(pOutputBus, MA_TRUE);
  57270. }
  57271. ma_node_output_bus_unlock(pOutputBus);
  57272. }
  57273. static ma_node_output_bus* ma_node_input_bus_next(ma_node_input_bus* pInputBus, ma_node_output_bus* pOutputBus)
  57274. {
  57275. ma_node_output_bus* pNext;
  57276. MA_ASSERT(pInputBus != NULL);
  57277. if (pOutputBus == NULL) {
  57278. return NULL;
  57279. }
  57280. ma_node_input_bus_next_begin(pInputBus);
  57281. {
  57282. pNext = pOutputBus;
  57283. for (;;) {
  57284. pNext = (ma_node_output_bus*)c89atomic_load_ptr(&pNext->pNext);
  57285. if (pNext == NULL) {
  57286. break; /* Reached the end. */
  57287. }
  57288. if (ma_node_output_bus_is_attached(pNext) == MA_FALSE) {
  57289. continue; /* The node is not attached. Keep checking. */
  57290. }
  57291. /* The next node has been selected. */
  57292. break;
  57293. }
  57294. /* We need to increment the reference count of the selected node. */
  57295. if (pNext != NULL) {
  57296. c89atomic_fetch_add_32(&pNext->refCount, 1);
  57297. }
  57298. /* The previous node is no longer being referenced. */
  57299. c89atomic_fetch_sub_32(&pOutputBus->refCount, 1);
  57300. }
  57301. ma_node_input_bus_next_end(pInputBus);
  57302. return pNext;
  57303. }
  57304. static ma_node_output_bus* ma_node_input_bus_first(ma_node_input_bus* pInputBus)
  57305. {
  57306. return ma_node_input_bus_next(pInputBus, &pInputBus->head);
  57307. }
  57308. 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)
  57309. {
  57310. ma_result result = MA_SUCCESS;
  57311. ma_node_output_bus* pOutputBus;
  57312. ma_node_output_bus* pFirst;
  57313. ma_uint32 inputChannels;
  57314. ma_bool32 doesOutputBufferHaveContent = MA_FALSE;
  57315. /*
  57316. This will be called from the audio thread which means we can't be doing any locking. Basically,
  57317. this function will not perfom any locking, whereas attaching and detaching will, but crafted in
  57318. such a way that we don't need to perform any locking here. The important thing to remember is
  57319. to always iterate in a forward direction.
  57320. In order to process any data we need to first read from all input buses. That's where this
  57321. function comes in. This iterates over each of the attachments and accumulates/mixes them. We
  57322. also convert the channels to the nodes output channel count before mixing. We want to do this
  57323. channel conversion so that the caller of this function can invoke the processing callback
  57324. without having to do it themselves.
  57325. When we iterate over each of the attachments on the input bus, we need to read as much data as
  57326. we can from each of them so that we don't end up with holes between each of the attachments. To
  57327. do this, we need to read from each attachment in a loop and read as many frames as we can, up
  57328. to `frameCount`.
  57329. */
  57330. MA_ASSERT(pInputNode != NULL);
  57331. 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. */
  57332. *pFramesRead = 0; /* Safety. */
  57333. inputChannels = ma_node_input_bus_get_channels(pInputBus);
  57334. /*
  57335. We need to be careful with how we call ma_node_input_bus_first() and ma_node_input_bus_next(). They
  57336. are both critical to our lock-free thread-safety system. We can only call ma_node_input_bus_first()
  57337. once per iteration, however we have an optimization to checks whether or not it's the first item in
  57338. the list. We therefore need to store a pointer to the first item rather than repeatedly calling
  57339. ma_node_input_bus_first(). It's safe to keep hold of this pointer, so long as we don't dereference it
  57340. after calling ma_node_input_bus_next(), which we won't be.
  57341. */
  57342. pFirst = ma_node_input_bus_first(pInputBus);
  57343. if (pFirst == NULL) {
  57344. return MA_SUCCESS; /* No attachments. Read nothing. */
  57345. }
  57346. for (pOutputBus = pFirst; pOutputBus != NULL; pOutputBus = ma_node_input_bus_next(pInputBus, pOutputBus)) {
  57347. ma_uint32 framesProcessed = 0;
  57348. ma_bool32 isSilentOutput = MA_FALSE;
  57349. MA_ASSERT(pOutputBus->pNode != NULL);
  57350. isSilentOutput = (((ma_node_base*)pOutputBus->pNode)->vtable->flags & MA_NODE_FLAG_SILENT_OUTPUT) != 0;
  57351. if (pFramesOut != NULL) {
  57352. /* Read. */
  57353. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  57354. ma_uint32 tempCapInFrames = ma_countof(temp) / inputChannels;
  57355. while (framesProcessed < frameCount) {
  57356. float* pRunningFramesOut;
  57357. ma_uint32 framesToRead;
  57358. ma_uint32 framesJustRead;
  57359. framesToRead = frameCount - framesProcessed;
  57360. if (framesToRead > tempCapInFrames) {
  57361. framesToRead = tempCapInFrames;
  57362. }
  57363. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(pFramesOut, framesProcessed, inputChannels);
  57364. if (doesOutputBufferHaveContent == MA_FALSE) {
  57365. /* Fast path. First attachment. We just read straight into the output buffer (no mixing required). */
  57366. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, pRunningFramesOut, framesToRead, &framesJustRead, globalTime + framesProcessed);
  57367. } else {
  57368. /* Slow path. Not the first attachment. Mixing required. */
  57369. result = ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, temp, framesToRead, &framesJustRead, globalTime + framesProcessed);
  57370. if (result == MA_SUCCESS || result == MA_AT_END) {
  57371. if (isSilentOutput == MA_FALSE) { /* Don't mix if the node outputs silence. */
  57372. ma_mix_pcm_frames_f32(pRunningFramesOut, temp, framesJustRead, inputChannels, /*volume*/1);
  57373. }
  57374. }
  57375. }
  57376. framesProcessed += framesJustRead;
  57377. /* If we reached the end or otherwise failed to read any data we need to finish up with this output node. */
  57378. if (result != MA_SUCCESS) {
  57379. break;
  57380. }
  57381. /* If we didn't read anything, abort so we don't get stuck in a loop. */
  57382. if (framesJustRead == 0) {
  57383. break;
  57384. }
  57385. }
  57386. /* If it's the first attachment we didn't do any mixing. Any leftover samples need to be silenced. */
  57387. if (pOutputBus == pFirst && framesProcessed < frameCount) {
  57388. ma_silence_pcm_frames(ma_offset_pcm_frames_ptr(pFramesOut, framesProcessed, ma_format_f32, inputChannels), (frameCount - framesProcessed), ma_format_f32, inputChannels);
  57389. }
  57390. if (isSilentOutput == MA_FALSE) {
  57391. doesOutputBufferHaveContent = MA_TRUE;
  57392. }
  57393. } else {
  57394. /* Seek. */
  57395. ma_node_read_pcm_frames(pOutputBus->pNode, pOutputBus->outputBusIndex, NULL, frameCount, &framesProcessed, globalTime);
  57396. }
  57397. }
  57398. /* If we didn't output anything, output silence. */
  57399. if (doesOutputBufferHaveContent == MA_FALSE && pFramesOut != NULL) {
  57400. ma_silence_pcm_frames(pFramesOut, frameCount, ma_format_f32, inputChannels);
  57401. }
  57402. /* In this path we always "process" the entire amount. */
  57403. *pFramesRead = frameCount;
  57404. return result;
  57405. }
  57406. MA_API ma_node_config ma_node_config_init(void)
  57407. {
  57408. ma_node_config config;
  57409. MA_ZERO_OBJECT(&config);
  57410. config.initialState = ma_node_state_started; /* Nodes are started by default. */
  57411. config.inputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  57412. config.outputBusCount = MA_NODE_BUS_COUNT_UNKNOWN;
  57413. return config;
  57414. }
  57415. static ma_result ma_node_detach_full(ma_node* pNode);
  57416. static float* ma_node_get_cached_input_ptr(ma_node* pNode, ma_uint32 inputBusIndex)
  57417. {
  57418. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57419. ma_uint32 iInputBus;
  57420. float* pBasePtr;
  57421. MA_ASSERT(pNodeBase != NULL);
  57422. /* Input data is stored at the front of the buffer. */
  57423. pBasePtr = pNodeBase->pCachedData;
  57424. for (iInputBus = 0; iInputBus < inputBusIndex; iInputBus += 1) {
  57425. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  57426. }
  57427. return pBasePtr;
  57428. }
  57429. static float* ma_node_get_cached_output_ptr(ma_node* pNode, ma_uint32 outputBusIndex)
  57430. {
  57431. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57432. ma_uint32 iInputBus;
  57433. ma_uint32 iOutputBus;
  57434. float* pBasePtr;
  57435. MA_ASSERT(pNodeBase != NULL);
  57436. /* Cached output data starts after the input data. */
  57437. pBasePtr = pNodeBase->pCachedData;
  57438. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  57439. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[iInputBus]);
  57440. }
  57441. for (iOutputBus = 0; iOutputBus < outputBusIndex; iOutputBus += 1) {
  57442. pBasePtr += pNodeBase->cachedDataCapInFramesPerBus * ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[iOutputBus]);
  57443. }
  57444. return pBasePtr;
  57445. }
  57446. typedef struct
  57447. {
  57448. size_t sizeInBytes;
  57449. size_t inputBusOffset;
  57450. size_t outputBusOffset;
  57451. size_t cachedDataOffset;
  57452. ma_uint32 inputBusCount; /* So it doesn't have to be calculated twice. */
  57453. ma_uint32 outputBusCount; /* So it doesn't have to be calculated twice. */
  57454. } ma_node_heap_layout;
  57455. static ma_result ma_node_translate_bus_counts(const ma_node_config* pConfig, ma_uint32* pInputBusCount, ma_uint32* pOutputBusCount)
  57456. {
  57457. ma_uint32 inputBusCount;
  57458. ma_uint32 outputBusCount;
  57459. MA_ASSERT(pConfig != NULL);
  57460. MA_ASSERT(pInputBusCount != NULL);
  57461. MA_ASSERT(pOutputBusCount != NULL);
  57462. /* 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. */
  57463. if (pConfig->vtable->inputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  57464. inputBusCount = pConfig->inputBusCount;
  57465. } else {
  57466. inputBusCount = pConfig->vtable->inputBusCount;
  57467. if (pConfig->inputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->inputBusCount != pConfig->vtable->inputBusCount) {
  57468. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  57469. }
  57470. }
  57471. if (pConfig->vtable->outputBusCount == MA_NODE_BUS_COUNT_UNKNOWN) {
  57472. outputBusCount = pConfig->outputBusCount;
  57473. } else {
  57474. outputBusCount = pConfig->vtable->outputBusCount;
  57475. if (pConfig->outputBusCount != MA_NODE_BUS_COUNT_UNKNOWN && pConfig->outputBusCount != pConfig->vtable->outputBusCount) {
  57476. return MA_INVALID_ARGS; /* Invalid configuration. You must not specify a conflicting bus count between the node's config and the vtable. */
  57477. }
  57478. }
  57479. /* Bus counts must be within limits. */
  57480. if (inputBusCount > MA_MAX_NODE_BUS_COUNT || outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  57481. return MA_INVALID_ARGS;
  57482. }
  57483. /* We must have channel counts for each bus. */
  57484. if ((inputBusCount > 0 && pConfig->pInputChannels == NULL) || (outputBusCount > 0 && pConfig->pOutputChannels == NULL)) {
  57485. return MA_INVALID_ARGS; /* You must specify channel counts for each input and output bus. */
  57486. }
  57487. /* Some special rules for passthrough nodes. */
  57488. if ((pConfig->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  57489. if (pConfig->vtable->inputBusCount != 1 || pConfig->vtable->outputBusCount != 1) {
  57490. return MA_INVALID_ARGS; /* Passthrough nodes must have exactly 1 input bus and 1 output bus. */
  57491. }
  57492. if (pConfig->pInputChannels[0] != pConfig->pOutputChannels[0]) {
  57493. return MA_INVALID_ARGS; /* Passthrough nodes must have the same number of channels between input and output nodes. */
  57494. }
  57495. }
  57496. *pInputBusCount = inputBusCount;
  57497. *pOutputBusCount = outputBusCount;
  57498. return MA_SUCCESS;
  57499. }
  57500. static ma_result ma_node_get_heap_layout(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, ma_node_heap_layout* pHeapLayout)
  57501. {
  57502. ma_result result;
  57503. ma_uint32 inputBusCount;
  57504. ma_uint32 outputBusCount;
  57505. MA_ASSERT(pHeapLayout != NULL);
  57506. MA_ZERO_OBJECT(pHeapLayout);
  57507. if (pConfig == NULL || pConfig->vtable == NULL || pConfig->vtable->onProcess == NULL) {
  57508. return MA_INVALID_ARGS;
  57509. }
  57510. result = ma_node_translate_bus_counts(pConfig, &inputBusCount, &outputBusCount);
  57511. if (result != MA_SUCCESS) {
  57512. return result;
  57513. }
  57514. pHeapLayout->sizeInBytes = 0;
  57515. /* Input buses. */
  57516. if (inputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  57517. pHeapLayout->inputBusOffset = pHeapLayout->sizeInBytes;
  57518. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_input_bus) * inputBusCount);
  57519. } else {
  57520. pHeapLayout->inputBusOffset = MA_SIZE_MAX; /* MA_SIZE_MAX indicates that no heap allocation is required for the input bus. */
  57521. }
  57522. /* Output buses. */
  57523. if (outputBusCount > MA_MAX_NODE_LOCAL_BUS_COUNT) {
  57524. pHeapLayout->outputBusOffset = pHeapLayout->sizeInBytes;
  57525. pHeapLayout->sizeInBytes += ma_align_64(sizeof(ma_node_output_bus) * outputBusCount);
  57526. } else {
  57527. pHeapLayout->outputBusOffset = MA_SIZE_MAX;
  57528. }
  57529. /*
  57530. Cached audio data.
  57531. We need to allocate memory for a caching both input and output data. We have an optimization
  57532. where no caching is necessary for specific conditions:
  57533. - The node has 0 inputs and 1 output.
  57534. When a node meets the above conditions, no cache is allocated.
  57535. The size choice for this buffer is a little bit finicky. We don't want to be too wasteful by
  57536. allocating too much, but at the same time we want it be large enough so that enough frames can
  57537. be processed for each call to ma_node_read_pcm_frames() so that it keeps things efficient. For
  57538. now I'm going with 10ms @ 48K which is 480 frames per bus. This is configurable at compile
  57539. time. It might also be worth investigating whether or not this can be configured at run time.
  57540. */
  57541. if (inputBusCount == 0 && outputBusCount == 1) {
  57542. /* Fast path. No cache needed. */
  57543. pHeapLayout->cachedDataOffset = MA_SIZE_MAX;
  57544. } else {
  57545. /* Slow path. Cache needed. */
  57546. size_t cachedDataSizeInBytes = 0;
  57547. ma_uint32 iBus;
  57548. for (iBus = 0; iBus < inputBusCount; iBus += 1) {
  57549. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pInputChannels[iBus]);
  57550. }
  57551. for (iBus = 0; iBus < outputBusCount; iBus += 1) {
  57552. cachedDataSizeInBytes += pNodeGraph->nodeCacheCapInFrames * ma_get_bytes_per_frame(ma_format_f32, pConfig->pOutputChannels[iBus]);
  57553. }
  57554. pHeapLayout->cachedDataOffset = pHeapLayout->sizeInBytes;
  57555. pHeapLayout->sizeInBytes += ma_align_64(cachedDataSizeInBytes);
  57556. }
  57557. /*
  57558. Not technically part of the heap, but we can output the input and output bus counts so we can
  57559. avoid a redundant call to ma_node_translate_bus_counts().
  57560. */
  57561. pHeapLayout->inputBusCount = inputBusCount;
  57562. pHeapLayout->outputBusCount = outputBusCount;
  57563. /* Make sure allocation size is aligned. */
  57564. pHeapLayout->sizeInBytes = ma_align_64(pHeapLayout->sizeInBytes);
  57565. return MA_SUCCESS;
  57566. }
  57567. MA_API ma_result ma_node_get_heap_size(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, size_t* pHeapSizeInBytes)
  57568. {
  57569. ma_result result;
  57570. ma_node_heap_layout heapLayout;
  57571. if (pHeapSizeInBytes == NULL) {
  57572. return MA_INVALID_ARGS;
  57573. }
  57574. *pHeapSizeInBytes = 0;
  57575. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  57576. if (result != MA_SUCCESS) {
  57577. return result;
  57578. }
  57579. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  57580. return MA_SUCCESS;
  57581. }
  57582. MA_API ma_result ma_node_init_preallocated(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, void* pHeap, ma_node* pNode)
  57583. {
  57584. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57585. ma_result result;
  57586. ma_node_heap_layout heapLayout;
  57587. ma_uint32 iInputBus;
  57588. ma_uint32 iOutputBus;
  57589. if (pNodeBase == NULL) {
  57590. return MA_INVALID_ARGS;
  57591. }
  57592. MA_ZERO_OBJECT(pNodeBase);
  57593. result = ma_node_get_heap_layout(pNodeGraph, pConfig, &heapLayout);
  57594. if (result != MA_SUCCESS) {
  57595. return result;
  57596. }
  57597. pNodeBase->_pHeap = pHeap;
  57598. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  57599. pNodeBase->pNodeGraph = pNodeGraph;
  57600. pNodeBase->vtable = pConfig->vtable;
  57601. pNodeBase->state = pConfig->initialState;
  57602. pNodeBase->stateTimes[ma_node_state_started] = 0;
  57603. pNodeBase->stateTimes[ma_node_state_stopped] = (ma_uint64)(ma_int64)-1; /* Weird casting for VC6 compatibility. */
  57604. pNodeBase->inputBusCount = heapLayout.inputBusCount;
  57605. pNodeBase->outputBusCount = heapLayout.outputBusCount;
  57606. if (heapLayout.inputBusOffset != MA_SIZE_MAX) {
  57607. pNodeBase->pInputBuses = (ma_node_input_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset);
  57608. } else {
  57609. pNodeBase->pInputBuses = pNodeBase->_inputBuses;
  57610. }
  57611. if (heapLayout.outputBusOffset != MA_SIZE_MAX) {
  57612. pNodeBase->pOutputBuses = (ma_node_output_bus*)ma_offset_ptr(pHeap, heapLayout.inputBusOffset);
  57613. } else {
  57614. pNodeBase->pOutputBuses = pNodeBase->_outputBuses;
  57615. }
  57616. if (heapLayout.cachedDataOffset != MA_SIZE_MAX) {
  57617. pNodeBase->pCachedData = (float*)ma_offset_ptr(pHeap, heapLayout.cachedDataOffset);
  57618. pNodeBase->cachedDataCapInFramesPerBus = pNodeGraph->nodeCacheCapInFrames;
  57619. } else {
  57620. pNodeBase->pCachedData = NULL;
  57621. }
  57622. /* We need to run an initialization step for each input and output bus. */
  57623. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNodeBase); iInputBus += 1) {
  57624. result = ma_node_input_bus_init(pConfig->pInputChannels[iInputBus], &pNodeBase->pInputBuses[iInputBus]);
  57625. if (result != MA_SUCCESS) {
  57626. return result;
  57627. }
  57628. }
  57629. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  57630. result = ma_node_output_bus_init(pNodeBase, iOutputBus, pConfig->pOutputChannels[iOutputBus], &pNodeBase->pOutputBuses[iOutputBus]);
  57631. if (result != MA_SUCCESS) {
  57632. return result;
  57633. }
  57634. }
  57635. /* The cached data needs to be initialized to silence (or a sine wave tone if we're debugging). */
  57636. if (pNodeBase->pCachedData != NULL) {
  57637. ma_uint32 iBus;
  57638. #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. */
  57639. /* For safety we'll go ahead and default the buffer to silence. */
  57640. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  57641. 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]));
  57642. }
  57643. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  57644. 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]));
  57645. }
  57646. #else
  57647. /* For debugging. Default to a sine wave. */
  57648. for (iBus = 0; iBus < ma_node_get_input_bus_count(pNodeBase); iBus += 1) {
  57649. 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);
  57650. }
  57651. for (iBus = 0; iBus < ma_node_get_output_bus_count(pNodeBase); iBus += 1) {
  57652. 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);
  57653. }
  57654. #endif
  57655. }
  57656. return MA_SUCCESS;
  57657. }
  57658. MA_API ma_result ma_node_init(ma_node_graph* pNodeGraph, const ma_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_node* pNode)
  57659. {
  57660. ma_result result;
  57661. size_t heapSizeInBytes;
  57662. void* pHeap;
  57663. result = ma_node_get_heap_size(pNodeGraph, pConfig, &heapSizeInBytes);
  57664. if (result != MA_SUCCESS) {
  57665. return result;
  57666. }
  57667. if (heapSizeInBytes > 0) {
  57668. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  57669. if (pHeap == NULL) {
  57670. return MA_OUT_OF_MEMORY;
  57671. }
  57672. } else {
  57673. pHeap = NULL;
  57674. }
  57675. result = ma_node_init_preallocated(pNodeGraph, pConfig, pHeap, pNode);
  57676. if (result != MA_SUCCESS) {
  57677. ma_free(pHeap, pAllocationCallbacks);
  57678. return result;
  57679. }
  57680. ((ma_node_base*)pNode)->_ownsHeap = MA_TRUE;
  57681. return MA_SUCCESS;
  57682. }
  57683. MA_API void ma_node_uninit(ma_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  57684. {
  57685. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57686. if (pNodeBase == NULL) {
  57687. return;
  57688. }
  57689. /*
  57690. The first thing we need to do is fully detach the node. This will detach all inputs and
  57691. outputs. We need to do this first because it will sever the connection with the node graph and
  57692. allow us to complete uninitialization without needing to worry about thread-safety with the
  57693. audio thread. The detachment process will wait for any local processing of the node to finish.
  57694. */
  57695. ma_node_detach_full(pNode);
  57696. /*
  57697. At this point the node should be completely unreferenced by the node graph and we can finish up
  57698. the uninitialization process without needing to worry about thread-safety.
  57699. */
  57700. if (pNodeBase->_ownsHeap) {
  57701. ma_free(pNodeBase->_pHeap, pAllocationCallbacks);
  57702. }
  57703. }
  57704. MA_API ma_node_graph* ma_node_get_node_graph(const ma_node* pNode)
  57705. {
  57706. if (pNode == NULL) {
  57707. return NULL;
  57708. }
  57709. return ((const ma_node_base*)pNode)->pNodeGraph;
  57710. }
  57711. MA_API ma_uint32 ma_node_get_input_bus_count(const ma_node* pNode)
  57712. {
  57713. if (pNode == NULL) {
  57714. return 0;
  57715. }
  57716. return ((ma_node_base*)pNode)->inputBusCount;
  57717. }
  57718. MA_API ma_uint32 ma_node_get_output_bus_count(const ma_node* pNode)
  57719. {
  57720. if (pNode == NULL) {
  57721. return 0;
  57722. }
  57723. return ((ma_node_base*)pNode)->outputBusCount;
  57724. }
  57725. MA_API ma_uint32 ma_node_get_input_channels(const ma_node* pNode, ma_uint32 inputBusIndex)
  57726. {
  57727. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  57728. if (pNode == NULL) {
  57729. return 0;
  57730. }
  57731. if (inputBusIndex >= ma_node_get_input_bus_count(pNode)) {
  57732. return 0; /* Invalid bus index. */
  57733. }
  57734. return ma_node_input_bus_get_channels(&pNodeBase->pInputBuses[inputBusIndex]);
  57735. }
  57736. MA_API ma_uint32 ma_node_get_output_channels(const ma_node* pNode, ma_uint32 outputBusIndex)
  57737. {
  57738. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  57739. if (pNode == NULL) {
  57740. return 0;
  57741. }
  57742. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  57743. return 0; /* Invalid bus index. */
  57744. }
  57745. return ma_node_output_bus_get_channels(&pNodeBase->pOutputBuses[outputBusIndex]);
  57746. }
  57747. static ma_result ma_node_detach_full(ma_node* pNode)
  57748. {
  57749. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57750. ma_uint32 iInputBus;
  57751. if (pNodeBase == NULL) {
  57752. return MA_INVALID_ARGS;
  57753. }
  57754. /*
  57755. Make sure the node is completely detached first. This will not return until the output bus is
  57756. guaranteed to no longer be referenced by the audio thread.
  57757. */
  57758. ma_node_detach_all_output_buses(pNode);
  57759. /*
  57760. At this point all output buses will have been detached from the graph and we can be guaranteed
  57761. that none of it's input nodes will be getting processed by the graph. We can detach these
  57762. without needing to worry about the audio thread touching them.
  57763. */
  57764. for (iInputBus = 0; iInputBus < ma_node_get_input_bus_count(pNode); iInputBus += 1) {
  57765. ma_node_input_bus* pInputBus;
  57766. ma_node_output_bus* pOutputBus;
  57767. pInputBus = &pNodeBase->pInputBuses[iInputBus];
  57768. /*
  57769. This is important. We cannot be using ma_node_input_bus_first() or ma_node_input_bus_next(). Those
  57770. functions are specifically for the audio thread. We'll instead just manually iterate using standard
  57771. linked list logic. We don't need to worry about the audio thread referencing these because the step
  57772. above severed the connection to the graph.
  57773. */
  57774. for (pOutputBus = (ma_node_output_bus*)c89atomic_load_ptr(&pInputBus->head.pNext); pOutputBus != NULL; pOutputBus = (ma_node_output_bus*)c89atomic_load_ptr(&pOutputBus->pNext)) {
  57775. ma_node_detach_output_bus(pOutputBus->pNode, pOutputBus->outputBusIndex); /* This won't do any waiting in practice and should be efficient. */
  57776. }
  57777. }
  57778. return MA_SUCCESS;
  57779. }
  57780. MA_API ma_result ma_node_detach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex)
  57781. {
  57782. ma_result result = MA_SUCCESS;
  57783. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57784. ma_node_base* pInputNodeBase;
  57785. if (pNode == NULL) {
  57786. return MA_INVALID_ARGS;
  57787. }
  57788. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  57789. return MA_INVALID_ARGS; /* Invalid output bus index. */
  57790. }
  57791. /* We need to lock the output bus because we need to inspect the input node and grab it's input bus. */
  57792. ma_node_output_bus_lock(&pNodeBase->pOutputBuses[outputBusIndex]);
  57793. {
  57794. pInputNodeBase = (ma_node_base*)pNodeBase->pOutputBuses[outputBusIndex].pInputNode;
  57795. if (pInputNodeBase != NULL) {
  57796. ma_node_input_bus_detach__no_output_bus_lock(&pInputNodeBase->pInputBuses[pNodeBase->pOutputBuses[outputBusIndex].inputNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex]);
  57797. }
  57798. }
  57799. ma_node_output_bus_unlock(&pNodeBase->pOutputBuses[outputBusIndex]);
  57800. return result;
  57801. }
  57802. MA_API ma_result ma_node_detach_all_output_buses(ma_node* pNode)
  57803. {
  57804. ma_uint32 iOutputBus;
  57805. if (pNode == NULL) {
  57806. return MA_INVALID_ARGS;
  57807. }
  57808. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNode); iOutputBus += 1) {
  57809. ma_node_detach_output_bus(pNode, iOutputBus);
  57810. }
  57811. return MA_SUCCESS;
  57812. }
  57813. MA_API ma_result ma_node_attach_output_bus(ma_node* pNode, ma_uint32 outputBusIndex, ma_node* pOtherNode, ma_uint32 otherNodeInputBusIndex)
  57814. {
  57815. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57816. ma_node_base* pOtherNodeBase = (ma_node_base*)pOtherNode;
  57817. if (pNodeBase == NULL || pOtherNodeBase == NULL) {
  57818. return MA_INVALID_ARGS;
  57819. }
  57820. if (pNodeBase == pOtherNodeBase) {
  57821. return MA_INVALID_OPERATION; /* Cannot attach a node to itself. */
  57822. }
  57823. if (outputBusIndex >= ma_node_get_output_bus_count(pNode) || otherNodeInputBusIndex >= ma_node_get_input_bus_count(pOtherNode)) {
  57824. return MA_INVALID_OPERATION; /* Invalid bus index. */
  57825. }
  57826. /* The output channel count of the output node must be the same as the input channel count of the input node. */
  57827. if (ma_node_get_output_channels(pNode, outputBusIndex) != ma_node_get_input_channels(pOtherNode, otherNodeInputBusIndex)) {
  57828. return MA_INVALID_OPERATION; /* Channel count is incompatible. */
  57829. }
  57830. /* This will deal with detaching if the output bus is already attached to something. */
  57831. ma_node_input_bus_attach(&pOtherNodeBase->pInputBuses[otherNodeInputBusIndex], &pNodeBase->pOutputBuses[outputBusIndex], pOtherNode, otherNodeInputBusIndex);
  57832. return MA_SUCCESS;
  57833. }
  57834. MA_API ma_result ma_node_set_output_bus_volume(ma_node* pNode, ma_uint32 outputBusIndex, float volume)
  57835. {
  57836. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57837. if (pNodeBase == NULL) {
  57838. return MA_INVALID_ARGS;
  57839. }
  57840. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  57841. return MA_INVALID_ARGS; /* Invalid bus index. */
  57842. }
  57843. return ma_node_output_bus_set_volume(&pNodeBase->pOutputBuses[outputBusIndex], volume);
  57844. }
  57845. MA_API float ma_node_get_output_bus_volume(const ma_node* pNode, ma_uint32 outputBusIndex)
  57846. {
  57847. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  57848. if (pNodeBase == NULL) {
  57849. return 0;
  57850. }
  57851. if (outputBusIndex >= ma_node_get_output_bus_count(pNode)) {
  57852. return 0; /* Invalid bus index. */
  57853. }
  57854. return ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]);
  57855. }
  57856. MA_API ma_result ma_node_set_state(ma_node* pNode, ma_node_state state)
  57857. {
  57858. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57859. if (pNodeBase == NULL) {
  57860. return MA_INVALID_ARGS;
  57861. }
  57862. c89atomic_exchange_i32(&pNodeBase->state, state);
  57863. return MA_SUCCESS;
  57864. }
  57865. MA_API ma_node_state ma_node_get_state(const ma_node* pNode)
  57866. {
  57867. const ma_node_base* pNodeBase = (const ma_node_base*)pNode;
  57868. if (pNodeBase == NULL) {
  57869. return ma_node_state_stopped;
  57870. }
  57871. return (ma_node_state)c89atomic_load_i32(&pNodeBase->state);
  57872. }
  57873. MA_API ma_result ma_node_set_state_time(ma_node* pNode, ma_node_state state, ma_uint64 globalTime)
  57874. {
  57875. if (pNode == NULL) {
  57876. return MA_INVALID_ARGS;
  57877. }
  57878. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  57879. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  57880. return MA_INVALID_ARGS;
  57881. }
  57882. c89atomic_exchange_64(&((ma_node_base*)pNode)->stateTimes[state], globalTime);
  57883. return MA_SUCCESS;
  57884. }
  57885. MA_API ma_uint64 ma_node_get_state_time(const ma_node* pNode, ma_node_state state)
  57886. {
  57887. if (pNode == NULL) {
  57888. return 0;
  57889. }
  57890. /* Validation check for safety since we'll be using this as an index into stateTimes[]. */
  57891. if (state != ma_node_state_started && state != ma_node_state_stopped) {
  57892. return 0;
  57893. }
  57894. return c89atomic_load_64(&((ma_node_base*)pNode)->stateTimes[state]);
  57895. }
  57896. MA_API ma_node_state ma_node_get_state_by_time(const ma_node* pNode, ma_uint64 globalTime)
  57897. {
  57898. if (pNode == NULL) {
  57899. return ma_node_state_stopped;
  57900. }
  57901. return ma_node_get_state_by_time_range(pNode, globalTime, globalTime);
  57902. }
  57903. MA_API ma_node_state ma_node_get_state_by_time_range(const ma_node* pNode, ma_uint64 globalTimeBeg, ma_uint64 globalTimeEnd)
  57904. {
  57905. ma_node_state state;
  57906. if (pNode == NULL) {
  57907. return ma_node_state_stopped;
  57908. }
  57909. state = ma_node_get_state(pNode);
  57910. /* An explicitly stopped node is always stopped. */
  57911. if (state == ma_node_state_stopped) {
  57912. return ma_node_state_stopped;
  57913. }
  57914. /*
  57915. Getting here means the node is marked as started, but it may still not be truly started due to
  57916. it's start time not having been reached yet. Also, the stop time may have also been reached in
  57917. which case it'll be considered stopped.
  57918. */
  57919. if (ma_node_get_state_time(pNode, ma_node_state_started) > globalTimeBeg) {
  57920. return ma_node_state_stopped; /* Start time has not yet been reached. */
  57921. }
  57922. if (ma_node_get_state_time(pNode, ma_node_state_stopped) <= globalTimeEnd) {
  57923. return ma_node_state_stopped; /* Stop time has been reached. */
  57924. }
  57925. /* Getting here means the node is marked as started and is within it's start/stop times. */
  57926. return ma_node_state_started;
  57927. }
  57928. MA_API ma_uint64 ma_node_get_time(const ma_node* pNode)
  57929. {
  57930. if (pNode == NULL) {
  57931. return 0;
  57932. }
  57933. return c89atomic_load_64(&((ma_node_base*)pNode)->localTime);
  57934. }
  57935. MA_API ma_result ma_node_set_time(ma_node* pNode, ma_uint64 localTime)
  57936. {
  57937. if (pNode == NULL) {
  57938. return MA_INVALID_ARGS;
  57939. }
  57940. c89atomic_exchange_64(&((ma_node_base*)pNode)->localTime, localTime);
  57941. return MA_SUCCESS;
  57942. }
  57943. static void ma_node_process_pcm_frames_internal(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  57944. {
  57945. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57946. MA_ASSERT(pNode != NULL);
  57947. if (pNodeBase->vtable->onProcess) {
  57948. pNodeBase->vtable->onProcess(pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  57949. }
  57950. }
  57951. 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)
  57952. {
  57953. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  57954. ma_result result = MA_SUCCESS;
  57955. ma_uint32 iInputBus;
  57956. ma_uint32 iOutputBus;
  57957. ma_uint32 inputBusCount;
  57958. ma_uint32 outputBusCount;
  57959. ma_uint32 totalFramesRead = 0;
  57960. float* ppFramesIn[MA_MAX_NODE_BUS_COUNT];
  57961. float* ppFramesOut[MA_MAX_NODE_BUS_COUNT];
  57962. ma_uint64 globalTimeBeg;
  57963. ma_uint64 globalTimeEnd;
  57964. ma_uint64 startTime;
  57965. ma_uint64 stopTime;
  57966. ma_uint32 timeOffsetBeg;
  57967. ma_uint32 timeOffsetEnd;
  57968. ma_uint32 frameCountIn;
  57969. ma_uint32 frameCountOut;
  57970. /*
  57971. pFramesRead is mandatory. It must be used to determine how many frames were read. It's normal and
  57972. expected that the number of frames read may be different to that requested. Therefore, the caller
  57973. must look at this value to correctly determine how many frames were read.
  57974. */
  57975. 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. */
  57976. if (pFramesRead == NULL) {
  57977. return MA_INVALID_ARGS;
  57978. }
  57979. *pFramesRead = 0; /* Safety. */
  57980. if (pNodeBase == NULL) {
  57981. return MA_INVALID_ARGS;
  57982. }
  57983. if (outputBusIndex >= ma_node_get_output_bus_count(pNodeBase)) {
  57984. return MA_INVALID_ARGS; /* Invalid output bus index. */
  57985. }
  57986. /* Don't do anything if we're in a stopped state. */
  57987. if (ma_node_get_state_by_time_range(pNode, globalTime, globalTime + frameCount) != ma_node_state_started) {
  57988. return MA_SUCCESS; /* We're in a stopped state. This is not an error - we just need to not read anything. */
  57989. }
  57990. globalTimeBeg = globalTime;
  57991. globalTimeEnd = globalTime + frameCount;
  57992. startTime = ma_node_get_state_time(pNode, ma_node_state_started);
  57993. stopTime = ma_node_get_state_time(pNode, ma_node_state_stopped);
  57994. /*
  57995. At this point we know that we are inside our start/stop times. However, we may need to adjust
  57996. our frame count and output pointer to accomodate since we could be straddling the time period
  57997. that this function is getting called for.
  57998. It's possible (and likely) that the start time does not line up with the output buffer. We
  57999. therefore need to offset it by a number of frames to accomodate. The same thing applies for
  58000. the stop time.
  58001. */
  58002. timeOffsetBeg = (globalTimeBeg < startTime) ? (ma_uint32)(globalTimeEnd - startTime) : 0;
  58003. timeOffsetEnd = (globalTimeEnd > stopTime) ? (ma_uint32)(globalTimeEnd - stopTime) : 0;
  58004. /* Trim based on the start offset. We need to silence the start of the buffer. */
  58005. if (timeOffsetBeg > 0) {
  58006. ma_silence_pcm_frames(pFramesOut, timeOffsetBeg, ma_format_f32, ma_node_get_output_channels(pNode, outputBusIndex));
  58007. pFramesOut += timeOffsetBeg * ma_node_get_output_channels(pNode, outputBusIndex);
  58008. frameCount -= timeOffsetBeg;
  58009. }
  58010. /* 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. */
  58011. if (timeOffsetEnd > 0) {
  58012. frameCount -= timeOffsetEnd;
  58013. }
  58014. /* We run on different paths depending on the bus counts. */
  58015. inputBusCount = ma_node_get_input_bus_count(pNode);
  58016. outputBusCount = ma_node_get_output_bus_count(pNode);
  58017. /*
  58018. Run a simplified path when there are no inputs and one output. In this case there's nothing to
  58019. actually read and we can go straight to output. This is a very common scenario because the vast
  58020. majority of data source nodes will use this setup so this optimization I think is worthwhile.
  58021. */
  58022. if (inputBusCount == 0 && outputBusCount == 1) {
  58023. /* Fast path. No need to read from input and no need for any caching. */
  58024. frameCountIn = 0;
  58025. frameCountOut = frameCount; /* Just read as much as we can. The callback will return what was actually read. */
  58026. ppFramesOut[0] = pFramesOut;
  58027. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  58028. totalFramesRead = frameCountOut;
  58029. } else {
  58030. /* Slow path. Need to read input data. */
  58031. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_PASSTHROUGH) != 0) {
  58032. /*
  58033. Fast path. We're running a passthrough. We need to read directly into the output buffer, but
  58034. still fire the callback so that event handling and trigger nodes can do their thing. Since
  58035. it's a passthrough there's no need for any kind of caching logic.
  58036. */
  58037. MA_ASSERT(outputBusCount == inputBusCount);
  58038. MA_ASSERT(outputBusCount == 1);
  58039. MA_ASSERT(outputBusIndex == 0);
  58040. /* We just read directly from input bus to output buffer, and then afterwards fire the callback. */
  58041. ppFramesOut[0] = pFramesOut;
  58042. ppFramesIn[0] = ppFramesOut[0];
  58043. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[0], ppFramesIn[0], frameCount, &totalFramesRead, globalTime);
  58044. if (result == MA_SUCCESS) {
  58045. /* Even though it's a passthrough, we still need to fire the callback. */
  58046. frameCountIn = totalFramesRead;
  58047. frameCountOut = totalFramesRead;
  58048. if (totalFramesRead > 0) {
  58049. 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. */
  58050. }
  58051. /*
  58052. A passthrough should never have modified the input and output frame counts. If you're
  58053. triggering these assers you need to fix your processing callback.
  58054. */
  58055. MA_ASSERT(frameCountIn == totalFramesRead);
  58056. MA_ASSERT(frameCountOut == totalFramesRead);
  58057. }
  58058. } else {
  58059. /* Slow path. Need to do caching. */
  58060. ma_uint32 framesToProcessIn;
  58061. ma_uint32 framesToProcessOut;
  58062. ma_bool32 consumeNullInput = MA_FALSE;
  58063. /*
  58064. We use frameCount as a basis for the number of frames to read since that's what's being
  58065. requested, however we still need to clamp it to whatever can fit in the cache.
  58066. This will also be used as the basis for determining how many input frames to read. This is
  58067. not ideal because it can result in too many input frames being read which introduces latency.
  58068. To solve this, nodes can implement an optional callback called onGetRequiredInputFrameCount
  58069. which is used as hint to miniaudio as to how many input frames it needs to read at a time. This
  58070. callback is completely optional, and if it's not set, miniaudio will assume `frameCount`.
  58071. This function will be called multiple times for each period of time, once for each output node.
  58072. We cannot read from each input node each time this function is called. Instead we need to check
  58073. whether or not this is first output bus to be read from for this time period, and if so, read
  58074. from our input data.
  58075. To determine whether or not we're ready to read data, we check a flag. There will be one flag
  58076. for each output. When the flag is set, it means data has been read previously and that we're
  58077. ready to advance time forward for our input nodes by reading fresh data.
  58078. */
  58079. framesToProcessOut = frameCount;
  58080. if (framesToProcessOut > pNodeBase->cachedDataCapInFramesPerBus) {
  58081. framesToProcessOut = pNodeBase->cachedDataCapInFramesPerBus;
  58082. }
  58083. framesToProcessIn = frameCount;
  58084. if (pNodeBase->vtable->onGetRequiredInputFrameCount) {
  58085. pNodeBase->vtable->onGetRequiredInputFrameCount(pNode, framesToProcessOut, &framesToProcessIn); /* <-- It does not matter if this fails. */
  58086. }
  58087. if (framesToProcessIn > pNodeBase->cachedDataCapInFramesPerBus) {
  58088. framesToProcessIn = pNodeBase->cachedDataCapInFramesPerBus;
  58089. }
  58090. MA_ASSERT(framesToProcessIn <= 0xFFFF);
  58091. MA_ASSERT(framesToProcessOut <= 0xFFFF);
  58092. if (ma_node_output_bus_has_read(&pNodeBase->pOutputBuses[outputBusIndex])) {
  58093. /* Getting here means we need to do another round of processing. */
  58094. pNodeBase->cachedFrameCountOut = 0;
  58095. for (;;) {
  58096. frameCountOut = 0;
  58097. /*
  58098. We need to prepare our output frame pointers for processing. In the same iteration we need
  58099. to mark every output bus as unread so that future calls to this function for different buses
  58100. for the current time period don't pull in data when they should instead be reading from cache.
  58101. */
  58102. for (iOutputBus = 0; iOutputBus < outputBusCount; iOutputBus += 1) {
  58103. 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. */
  58104. ppFramesOut[iOutputBus] = ma_node_get_cached_output_ptr(pNode, iOutputBus);
  58105. }
  58106. /* We only need to read from input buses if there isn't already some data in the cache. */
  58107. if (pNodeBase->cachedFrameCountIn == 0) {
  58108. ma_uint32 maxFramesReadIn = 0;
  58109. /* Here is where we pull in data from the input buses. This is what will trigger an advance in time. */
  58110. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  58111. ma_uint32 framesRead;
  58112. /* The first thing to do is get the offset within our bulk allocation to store this input data. */
  58113. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus);
  58114. /* 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. */
  58115. result = ma_node_input_bus_read_pcm_frames(pNodeBase, &pNodeBase->pInputBuses[iInputBus], ppFramesIn[iInputBus], framesToProcessIn, &framesRead, globalTime);
  58116. if (result != MA_SUCCESS) {
  58117. /* It doesn't really matter if we fail because we'll just fill with silence. */
  58118. framesRead = 0; /* Just for safety, but I don't think it's really needed. */
  58119. }
  58120. /* TODO: Minor optimization opportunity here. If no frames were read and the buffer is already filled with silence, no need to re-silence it. */
  58121. /* Any leftover frames need to silenced for safety. */
  58122. if (framesRead < framesToProcessIn) {
  58123. 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));
  58124. }
  58125. maxFramesReadIn = ma_max(maxFramesReadIn, framesRead);
  58126. }
  58127. /* This was a fresh load of input data so reset our consumption counter. */
  58128. pNodeBase->consumedFrameCountIn = 0;
  58129. /*
  58130. We don't want to keep processing if there's nothing to process, so set the number of cached
  58131. input frames to the maximum number we read from each attachment (the lesser will be padded
  58132. with silence). If we didn't read anything, this will be set to 0 and the entire buffer will
  58133. have been assigned to silence. This being equal to 0 is an important property for us because
  58134. it allows us to detect when NULL can be passed into the processing callback for the input
  58135. buffer for the purpose of continuous processing.
  58136. */
  58137. pNodeBase->cachedFrameCountIn = (ma_uint16)maxFramesReadIn;
  58138. } else {
  58139. /* We don't need to read anything, but we do need to prepare our input frame pointers. */
  58140. for (iInputBus = 0; iInputBus < inputBusCount; iInputBus += 1) {
  58141. ppFramesIn[iInputBus] = ma_node_get_cached_input_ptr(pNode, iInputBus) + (pNodeBase->consumedFrameCountIn * ma_node_get_input_channels(pNodeBase, iInputBus));
  58142. }
  58143. }
  58144. /*
  58145. At this point we have our input data so now we need to do some processing. Sneaky little
  58146. optimization here - we can set the pointer to the output buffer for this output bus so
  58147. that the final copy into the output buffer is done directly by onProcess().
  58148. */
  58149. if (pFramesOut != NULL) {
  58150. ppFramesOut[outputBusIndex] = ma_offset_pcm_frames_ptr_f32(pFramesOut, pNodeBase->cachedFrameCountOut, ma_node_get_output_channels(pNode, outputBusIndex));
  58151. }
  58152. /* Give the processing function the entire capacity of the output buffer. */
  58153. frameCountOut = (framesToProcessOut - pNodeBase->cachedFrameCountOut);
  58154. /*
  58155. We need to treat nodes with continuous processing a little differently. For these ones,
  58156. we always want to fire the callback with the requested number of frames, regardless of
  58157. pNodeBase->cachedFrameCountIn, which could be 0. Also, we want to check if we can pass
  58158. in NULL for the input buffer to the callback.
  58159. */
  58160. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_CONTINUOUS_PROCESSING) != 0) {
  58161. /* We're using continuous processing. Make sure we specify the whole frame count at all times. */
  58162. frameCountIn = framesToProcessIn; /* Give the processing function as much input data as we've got in the buffer, including any silenced padding from short reads. */
  58163. if ((pNodeBase->vtable->flags & MA_NODE_FLAG_ALLOW_NULL_INPUT) != 0 && pNodeBase->consumedFrameCountIn == 0 && pNodeBase->cachedFrameCountIn == 0) {
  58164. consumeNullInput = MA_TRUE;
  58165. } else {
  58166. consumeNullInput = MA_FALSE;
  58167. }
  58168. /*
  58169. Since we're using continuous processing we're always passing in a full frame count
  58170. regardless of how much input data was read. If this is greater than what we read as
  58171. input, we'll end up with an underflow. We instead need to make sure our cached frame
  58172. count is set to the number of frames we'll be passing to the data callback. Not
  58173. doing this will result in an underflow when we "consume" the cached data later on.
  58174. Note that this check needs to be done after the "consumeNullInput" check above because
  58175. we use the property of cachedFrameCountIn being 0 to determine whether or not we
  58176. should be passing in a null pointer to the processing callback for when the node is
  58177. configured with MA_NODE_FLAG_ALLOW_NULL_INPUT.
  58178. */
  58179. if (pNodeBase->cachedFrameCountIn < (ma_uint16)frameCountIn) {
  58180. pNodeBase->cachedFrameCountIn = (ma_uint16)frameCountIn;
  58181. }
  58182. } else {
  58183. frameCountIn = pNodeBase->cachedFrameCountIn; /* Give the processing function as much valid input data as we've got. */
  58184. consumeNullInput = MA_FALSE;
  58185. }
  58186. /*
  58187. Process data slightly differently depending on whether or not we're consuming NULL
  58188. input (checked just above).
  58189. */
  58190. if (consumeNullInput) {
  58191. ma_node_process_pcm_frames_internal(pNode, NULL, &frameCountIn, ppFramesOut, &frameCountOut);
  58192. } else {
  58193. /*
  58194. We want to skip processing if there's no input data, but we can only do that safely if
  58195. we know that there is no chance of any output frames being produced. If continuous
  58196. processing is being used, this won't be a problem because the input frame count will
  58197. always be non-0. However, if continuous processing is *not* enabled and input and output
  58198. data is processed at different rates, we still need to process that last input frame
  58199. because there could be a few excess output frames needing to be produced from cached
  58200. data. The `MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES` flag is used as the indicator for
  58201. determining whether or not we need to process the node even when there are no input
  58202. frames available right now.
  58203. */
  58204. if (frameCountIn > 0 || (pNodeBase->vtable->flags & MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES) != 0) {
  58205. 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. */
  58206. } else {
  58207. frameCountOut = 0; /* No data was processed. */
  58208. }
  58209. }
  58210. /*
  58211. Thanks to our sneaky optimization above we don't need to do any data copying directly into
  58212. the output buffer - the onProcess() callback just did that for us. We do, however, need to
  58213. apply the number of input and output frames that were processed. Note that due to continuous
  58214. processing above, we need to do explicit checks here. If we just consumed a NULL input
  58215. buffer it means that no actual input data was processed from the internal buffers and we
  58216. don't want to be modifying any counters.
  58217. */
  58218. if (consumeNullInput == MA_FALSE) {
  58219. pNodeBase->consumedFrameCountIn += (ma_uint16)frameCountIn;
  58220. pNodeBase->cachedFrameCountIn -= (ma_uint16)frameCountIn;
  58221. }
  58222. /* The cached output frame count is always equal to what we just read. */
  58223. pNodeBase->cachedFrameCountOut += (ma_uint16)frameCountOut;
  58224. /* 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. */
  58225. if (pNodeBase->cachedFrameCountOut == framesToProcessOut || (frameCountOut == 0 && frameCountIn == 0)) {
  58226. break;
  58227. }
  58228. }
  58229. } else {
  58230. /*
  58231. We're not needing to read anything from the input buffer so just read directly from our
  58232. already-processed data.
  58233. */
  58234. if (pFramesOut != NULL) {
  58235. 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));
  58236. }
  58237. }
  58238. /* The number of frames read is always equal to the number of cached output frames. */
  58239. totalFramesRead = pNodeBase->cachedFrameCountOut;
  58240. /* Now that we've read the data, make sure our read flag is set. */
  58241. ma_node_output_bus_set_has_read(&pNodeBase->pOutputBuses[outputBusIndex], MA_TRUE);
  58242. }
  58243. }
  58244. /* Apply volume, if necessary. */
  58245. ma_apply_volume_factor_f32(pFramesOut, totalFramesRead * ma_node_get_output_channels(pNodeBase, outputBusIndex), ma_node_output_bus_get_volume(&pNodeBase->pOutputBuses[outputBusIndex]));
  58246. /* Advance our local time forward. */
  58247. c89atomic_fetch_add_64(&pNodeBase->localTime, (ma_uint64)totalFramesRead);
  58248. *pFramesRead = totalFramesRead + timeOffsetBeg; /* Must include the silenced section at the start of the buffer. */
  58249. return result;
  58250. }
  58251. /* Data source node. */
  58252. MA_API ma_data_source_node_config ma_data_source_node_config_init(ma_data_source* pDataSource)
  58253. {
  58254. ma_data_source_node_config config;
  58255. MA_ZERO_OBJECT(&config);
  58256. config.nodeConfig = ma_node_config_init();
  58257. config.pDataSource = pDataSource;
  58258. return config;
  58259. }
  58260. static void ma_data_source_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58261. {
  58262. ma_data_source_node* pDataSourceNode = (ma_data_source_node*)pNode;
  58263. ma_format format;
  58264. ma_uint32 channels;
  58265. ma_uint32 frameCount;
  58266. ma_uint64 framesRead = 0;
  58267. MA_ASSERT(pDataSourceNode != NULL);
  58268. MA_ASSERT(pDataSourceNode->pDataSource != NULL);
  58269. MA_ASSERT(ma_node_get_input_bus_count(pDataSourceNode) == 0);
  58270. MA_ASSERT(ma_node_get_output_bus_count(pDataSourceNode) == 1);
  58271. /* We don't want to read from ppFramesIn at all. Instead we read from the data source. */
  58272. (void)ppFramesIn;
  58273. (void)pFrameCountIn;
  58274. frameCount = *pFrameCountOut;
  58275. /* miniaudio should never be calling this with a frame count of zero. */
  58276. MA_ASSERT(frameCount > 0);
  58277. if (ma_data_source_get_data_format(pDataSourceNode->pDataSource, &format, &channels, NULL, NULL, 0) == MA_SUCCESS) { /* <-- Don't care about sample rate here. */
  58278. /* The node graph system requires samples be in floating point format. This is checked in ma_data_source_node_init(). */
  58279. MA_ASSERT(format == ma_format_f32);
  58280. (void)format; /* Just to silence some static analysis tools. */
  58281. ma_data_source_read_pcm_frames(pDataSourceNode->pDataSource, ppFramesOut[0], frameCount, &framesRead);
  58282. }
  58283. *pFrameCountOut = (ma_uint32)framesRead;
  58284. }
  58285. static ma_node_vtable g_ma_data_source_node_vtable =
  58286. {
  58287. ma_data_source_node_process_pcm_frames,
  58288. NULL, /* onGetRequiredInputFrameCount */
  58289. 0, /* 0 input buses. */
  58290. 1, /* 1 output bus. */
  58291. 0
  58292. };
  58293. 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)
  58294. {
  58295. ma_result result;
  58296. ma_format format; /* For validating the format, which must be ma_format_f32. */
  58297. ma_uint32 channels; /* For specifying the channel count of the output bus. */
  58298. ma_node_config baseConfig;
  58299. if (pDataSourceNode == NULL) {
  58300. return MA_INVALID_ARGS;
  58301. }
  58302. MA_ZERO_OBJECT(pDataSourceNode);
  58303. if (pConfig == NULL) {
  58304. return MA_INVALID_ARGS;
  58305. }
  58306. 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. */
  58307. if (result != MA_SUCCESS) {
  58308. return result;
  58309. }
  58310. 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. */
  58311. if (format != ma_format_f32) {
  58312. return MA_INVALID_ARGS; /* Invalid format. */
  58313. }
  58314. /* The channel count is defined by the data source. If the caller has manually changed the channels we just ignore it. */
  58315. baseConfig = pConfig->nodeConfig;
  58316. baseConfig.vtable = &g_ma_data_source_node_vtable; /* Explicitly set the vtable here to prevent callers from setting it incorrectly. */
  58317. /*
  58318. The channel count is defined by the data source. It is invalid for the caller to manually set
  58319. the channel counts in the config. `ma_data_source_node_config_init()` will have defaulted the
  58320. channel count pointer to NULL which is how it must remain. If you trigger any of these asserts
  58321. it means you're explicitly setting the channel count. Instead, configure the output channel
  58322. count of your data source to be the necessary channel count.
  58323. */
  58324. if (baseConfig.pOutputChannels != NULL) {
  58325. return MA_INVALID_ARGS;
  58326. }
  58327. baseConfig.pOutputChannels = &channels;
  58328. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDataSourceNode->base);
  58329. if (result != MA_SUCCESS) {
  58330. return result;
  58331. }
  58332. pDataSourceNode->pDataSource = pConfig->pDataSource;
  58333. return MA_SUCCESS;
  58334. }
  58335. MA_API void ma_data_source_node_uninit(ma_data_source_node* pDataSourceNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58336. {
  58337. ma_node_uninit(&pDataSourceNode->base, pAllocationCallbacks);
  58338. }
  58339. MA_API ma_result ma_data_source_node_set_looping(ma_data_source_node* pDataSourceNode, ma_bool32 isLooping)
  58340. {
  58341. if (pDataSourceNode == NULL) {
  58342. return MA_INVALID_ARGS;
  58343. }
  58344. return ma_data_source_set_looping(pDataSourceNode->pDataSource, isLooping);
  58345. }
  58346. MA_API ma_bool32 ma_data_source_node_is_looping(ma_data_source_node* pDataSourceNode)
  58347. {
  58348. if (pDataSourceNode == NULL) {
  58349. return MA_FALSE;
  58350. }
  58351. return ma_data_source_is_looping(pDataSourceNode->pDataSource);
  58352. }
  58353. /* Splitter Node. */
  58354. MA_API ma_splitter_node_config ma_splitter_node_config_init(ma_uint32 channels)
  58355. {
  58356. ma_splitter_node_config config;
  58357. MA_ZERO_OBJECT(&config);
  58358. config.nodeConfig = ma_node_config_init();
  58359. config.channels = channels;
  58360. config.outputBusCount = 2;
  58361. return config;
  58362. }
  58363. static void ma_splitter_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58364. {
  58365. ma_node_base* pNodeBase = (ma_node_base*)pNode;
  58366. ma_uint32 iOutputBus;
  58367. ma_uint32 channels;
  58368. MA_ASSERT(pNodeBase != NULL);
  58369. MA_ASSERT(ma_node_get_input_bus_count(pNodeBase) == 1);
  58370. MA_ASSERT(ma_node_get_output_bus_count(pNodeBase) >= 2);
  58371. /* We don't need to consider the input frame count - it'll be the same as the output frame count and we process everything. */
  58372. (void)pFrameCountIn;
  58373. /* NOTE: This assumes the same number of channels for all inputs and outputs. This was checked in ma_splitter_node_init(). */
  58374. channels = ma_node_get_input_channels(pNodeBase, 0);
  58375. /* Splitting is just copying the first input bus and copying it over to each output bus. */
  58376. for (iOutputBus = 0; iOutputBus < ma_node_get_output_bus_count(pNodeBase); iOutputBus += 1) {
  58377. ma_copy_pcm_frames(ppFramesOut[iOutputBus], ppFramesIn[0], *pFrameCountOut, ma_format_f32, channels);
  58378. }
  58379. }
  58380. static ma_node_vtable g_ma_splitter_node_vtable =
  58381. {
  58382. ma_splitter_node_process_pcm_frames,
  58383. NULL, /* onGetRequiredInputFrameCount */
  58384. 1, /* 1 input bus. */
  58385. MA_NODE_BUS_COUNT_UNKNOWN, /* The output bus count is specified on a per-node basis. */
  58386. 0
  58387. };
  58388. 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)
  58389. {
  58390. ma_result result;
  58391. ma_node_config baseConfig;
  58392. ma_uint32 pInputChannels[1];
  58393. ma_uint32 pOutputChannels[MA_MAX_NODE_BUS_COUNT];
  58394. ma_uint32 iOutputBus;
  58395. if (pSplitterNode == NULL) {
  58396. return MA_INVALID_ARGS;
  58397. }
  58398. MA_ZERO_OBJECT(pSplitterNode);
  58399. if (pConfig == NULL) {
  58400. return MA_INVALID_ARGS;
  58401. }
  58402. if (pConfig->outputBusCount > MA_MAX_NODE_BUS_COUNT) {
  58403. return MA_INVALID_ARGS; /* Too many output buses. */
  58404. }
  58405. /* Splitters require the same number of channels between inputs and outputs. */
  58406. pInputChannels[0] = pConfig->channels;
  58407. for (iOutputBus = 0; iOutputBus < pConfig->outputBusCount; iOutputBus += 1) {
  58408. pOutputChannels[iOutputBus] = pConfig->channels;
  58409. }
  58410. baseConfig = pConfig->nodeConfig;
  58411. baseConfig.vtable = &g_ma_splitter_node_vtable;
  58412. baseConfig.pInputChannels = pInputChannels;
  58413. baseConfig.pOutputChannels = pOutputChannels;
  58414. baseConfig.outputBusCount = pConfig->outputBusCount;
  58415. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pSplitterNode->base);
  58416. if (result != MA_SUCCESS) {
  58417. return result; /* Failed to initialize the base node. */
  58418. }
  58419. return MA_SUCCESS;
  58420. }
  58421. MA_API void ma_splitter_node_uninit(ma_splitter_node* pSplitterNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58422. {
  58423. ma_node_uninit(pSplitterNode, pAllocationCallbacks);
  58424. }
  58425. /*
  58426. Biquad Node
  58427. */
  58428. 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)
  58429. {
  58430. ma_biquad_node_config config;
  58431. config.nodeConfig = ma_node_config_init();
  58432. config.biquad = ma_biquad_config_init(ma_format_f32, channels, b0, b1, b2, a0, a1, a2);
  58433. return config;
  58434. }
  58435. static void ma_biquad_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58436. {
  58437. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  58438. MA_ASSERT(pNode != NULL);
  58439. (void)pFrameCountIn;
  58440. ma_biquad_process_pcm_frames(&pLPFNode->biquad, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58441. }
  58442. static ma_node_vtable g_ma_biquad_node_vtable =
  58443. {
  58444. ma_biquad_node_process_pcm_frames,
  58445. NULL, /* onGetRequiredInputFrameCount */
  58446. 1, /* One input. */
  58447. 1, /* One output. */
  58448. 0 /* Default flags. */
  58449. };
  58450. 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)
  58451. {
  58452. ma_result result;
  58453. ma_node_config baseNodeConfig;
  58454. if (pNode == NULL) {
  58455. return MA_INVALID_ARGS;
  58456. }
  58457. MA_ZERO_OBJECT(pNode);
  58458. if (pConfig == NULL) {
  58459. return MA_INVALID_ARGS;
  58460. }
  58461. if (pConfig->biquad.format != ma_format_f32) {
  58462. return MA_INVALID_ARGS; /* The format must be f32. */
  58463. }
  58464. result = ma_biquad_init(&pConfig->biquad, pAllocationCallbacks, &pNode->biquad);
  58465. if (result != MA_SUCCESS) {
  58466. return result;
  58467. }
  58468. baseNodeConfig = ma_node_config_init();
  58469. baseNodeConfig.vtable = &g_ma_biquad_node_vtable;
  58470. baseNodeConfig.pInputChannels = &pConfig->biquad.channels;
  58471. baseNodeConfig.pOutputChannels = &pConfig->biquad.channels;
  58472. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58473. if (result != MA_SUCCESS) {
  58474. return result;
  58475. }
  58476. return result;
  58477. }
  58478. MA_API ma_result ma_biquad_node_reinit(const ma_biquad_config* pConfig, ma_biquad_node* pNode)
  58479. {
  58480. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  58481. MA_ASSERT(pNode != NULL);
  58482. return ma_biquad_reinit(pConfig, &pLPFNode->biquad);
  58483. }
  58484. MA_API void ma_biquad_node_uninit(ma_biquad_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58485. {
  58486. ma_biquad_node* pLPFNode = (ma_biquad_node*)pNode;
  58487. if (pNode == NULL) {
  58488. return;
  58489. }
  58490. ma_node_uninit(pNode, pAllocationCallbacks);
  58491. ma_biquad_uninit(&pLPFNode->biquad, pAllocationCallbacks);
  58492. }
  58493. /*
  58494. Low Pass Filter Node
  58495. */
  58496. MA_API ma_lpf_node_config ma_lpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  58497. {
  58498. ma_lpf_node_config config;
  58499. config.nodeConfig = ma_node_config_init();
  58500. config.lpf = ma_lpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  58501. return config;
  58502. }
  58503. static void ma_lpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58504. {
  58505. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  58506. MA_ASSERT(pNode != NULL);
  58507. (void)pFrameCountIn;
  58508. ma_lpf_process_pcm_frames(&pLPFNode->lpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58509. }
  58510. static ma_node_vtable g_ma_lpf_node_vtable =
  58511. {
  58512. ma_lpf_node_process_pcm_frames,
  58513. NULL, /* onGetRequiredInputFrameCount */
  58514. 1, /* One input. */
  58515. 1, /* One output. */
  58516. 0 /* Default flags. */
  58517. };
  58518. 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)
  58519. {
  58520. ma_result result;
  58521. ma_node_config baseNodeConfig;
  58522. if (pNode == NULL) {
  58523. return MA_INVALID_ARGS;
  58524. }
  58525. MA_ZERO_OBJECT(pNode);
  58526. if (pConfig == NULL) {
  58527. return MA_INVALID_ARGS;
  58528. }
  58529. if (pConfig->lpf.format != ma_format_f32) {
  58530. return MA_INVALID_ARGS; /* The format must be f32. */
  58531. }
  58532. result = ma_lpf_init(&pConfig->lpf, pAllocationCallbacks, &pNode->lpf);
  58533. if (result != MA_SUCCESS) {
  58534. return result;
  58535. }
  58536. baseNodeConfig = ma_node_config_init();
  58537. baseNodeConfig.vtable = &g_ma_lpf_node_vtable;
  58538. baseNodeConfig.pInputChannels = &pConfig->lpf.channels;
  58539. baseNodeConfig.pOutputChannels = &pConfig->lpf.channels;
  58540. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58541. if (result != MA_SUCCESS) {
  58542. return result;
  58543. }
  58544. return result;
  58545. }
  58546. MA_API ma_result ma_lpf_node_reinit(const ma_lpf_config* pConfig, ma_lpf_node* pNode)
  58547. {
  58548. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  58549. if (pNode == NULL) {
  58550. return MA_INVALID_ARGS;
  58551. }
  58552. return ma_lpf_reinit(pConfig, &pLPFNode->lpf);
  58553. }
  58554. MA_API void ma_lpf_node_uninit(ma_lpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58555. {
  58556. ma_lpf_node* pLPFNode = (ma_lpf_node*)pNode;
  58557. if (pNode == NULL) {
  58558. return;
  58559. }
  58560. ma_node_uninit(pNode, pAllocationCallbacks);
  58561. ma_lpf_uninit(&pLPFNode->lpf, pAllocationCallbacks);
  58562. }
  58563. /*
  58564. High Pass Filter Node
  58565. */
  58566. MA_API ma_hpf_node_config ma_hpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  58567. {
  58568. ma_hpf_node_config config;
  58569. config.nodeConfig = ma_node_config_init();
  58570. config.hpf = ma_hpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  58571. return config;
  58572. }
  58573. static void ma_hpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58574. {
  58575. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  58576. MA_ASSERT(pNode != NULL);
  58577. (void)pFrameCountIn;
  58578. ma_hpf_process_pcm_frames(&pHPFNode->hpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58579. }
  58580. static ma_node_vtable g_ma_hpf_node_vtable =
  58581. {
  58582. ma_hpf_node_process_pcm_frames,
  58583. NULL, /* onGetRequiredInputFrameCount */
  58584. 1, /* One input. */
  58585. 1, /* One output. */
  58586. 0 /* Default flags. */
  58587. };
  58588. 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)
  58589. {
  58590. ma_result result;
  58591. ma_node_config baseNodeConfig;
  58592. if (pNode == NULL) {
  58593. return MA_INVALID_ARGS;
  58594. }
  58595. MA_ZERO_OBJECT(pNode);
  58596. if (pConfig == NULL) {
  58597. return MA_INVALID_ARGS;
  58598. }
  58599. if (pConfig->hpf.format != ma_format_f32) {
  58600. return MA_INVALID_ARGS; /* The format must be f32. */
  58601. }
  58602. result = ma_hpf_init(&pConfig->hpf, pAllocationCallbacks, &pNode->hpf);
  58603. if (result != MA_SUCCESS) {
  58604. return result;
  58605. }
  58606. baseNodeConfig = ma_node_config_init();
  58607. baseNodeConfig.vtable = &g_ma_hpf_node_vtable;
  58608. baseNodeConfig.pInputChannels = &pConfig->hpf.channels;
  58609. baseNodeConfig.pOutputChannels = &pConfig->hpf.channels;
  58610. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58611. if (result != MA_SUCCESS) {
  58612. return result;
  58613. }
  58614. return result;
  58615. }
  58616. MA_API ma_result ma_hpf_node_reinit(const ma_hpf_config* pConfig, ma_hpf_node* pNode)
  58617. {
  58618. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  58619. if (pNode == NULL) {
  58620. return MA_INVALID_ARGS;
  58621. }
  58622. return ma_hpf_reinit(pConfig, &pHPFNode->hpf);
  58623. }
  58624. MA_API void ma_hpf_node_uninit(ma_hpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58625. {
  58626. ma_hpf_node* pHPFNode = (ma_hpf_node*)pNode;
  58627. if (pNode == NULL) {
  58628. return;
  58629. }
  58630. ma_node_uninit(pNode, pAllocationCallbacks);
  58631. ma_hpf_uninit(&pHPFNode->hpf, pAllocationCallbacks);
  58632. }
  58633. /*
  58634. Band Pass Filter Node
  58635. */
  58636. MA_API ma_bpf_node_config ma_bpf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double cutoffFrequency, ma_uint32 order)
  58637. {
  58638. ma_bpf_node_config config;
  58639. config.nodeConfig = ma_node_config_init();
  58640. config.bpf = ma_bpf_config_init(ma_format_f32, channels, sampleRate, cutoffFrequency, order);
  58641. return config;
  58642. }
  58643. static void ma_bpf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58644. {
  58645. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  58646. MA_ASSERT(pNode != NULL);
  58647. (void)pFrameCountIn;
  58648. ma_bpf_process_pcm_frames(&pBPFNode->bpf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58649. }
  58650. static ma_node_vtable g_ma_bpf_node_vtable =
  58651. {
  58652. ma_bpf_node_process_pcm_frames,
  58653. NULL, /* onGetRequiredInputFrameCount */
  58654. 1, /* One input. */
  58655. 1, /* One output. */
  58656. 0 /* Default flags. */
  58657. };
  58658. 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)
  58659. {
  58660. ma_result result;
  58661. ma_node_config baseNodeConfig;
  58662. if (pNode == NULL) {
  58663. return MA_INVALID_ARGS;
  58664. }
  58665. MA_ZERO_OBJECT(pNode);
  58666. if (pConfig == NULL) {
  58667. return MA_INVALID_ARGS;
  58668. }
  58669. if (pConfig->bpf.format != ma_format_f32) {
  58670. return MA_INVALID_ARGS; /* The format must be f32. */
  58671. }
  58672. result = ma_bpf_init(&pConfig->bpf, pAllocationCallbacks, &pNode->bpf);
  58673. if (result != MA_SUCCESS) {
  58674. return result;
  58675. }
  58676. baseNodeConfig = ma_node_config_init();
  58677. baseNodeConfig.vtable = &g_ma_bpf_node_vtable;
  58678. baseNodeConfig.pInputChannels = &pConfig->bpf.channels;
  58679. baseNodeConfig.pOutputChannels = &pConfig->bpf.channels;
  58680. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58681. if (result != MA_SUCCESS) {
  58682. return result;
  58683. }
  58684. return result;
  58685. }
  58686. MA_API ma_result ma_bpf_node_reinit(const ma_bpf_config* pConfig, ma_bpf_node* pNode)
  58687. {
  58688. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  58689. if (pNode == NULL) {
  58690. return MA_INVALID_ARGS;
  58691. }
  58692. return ma_bpf_reinit(pConfig, &pBPFNode->bpf);
  58693. }
  58694. MA_API void ma_bpf_node_uninit(ma_bpf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58695. {
  58696. ma_bpf_node* pBPFNode = (ma_bpf_node*)pNode;
  58697. if (pNode == NULL) {
  58698. return;
  58699. }
  58700. ma_node_uninit(pNode, pAllocationCallbacks);
  58701. ma_bpf_uninit(&pBPFNode->bpf, pAllocationCallbacks);
  58702. }
  58703. /*
  58704. Notching Filter Node
  58705. */
  58706. MA_API ma_notch_node_config ma_notch_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double q, double frequency)
  58707. {
  58708. ma_notch_node_config config;
  58709. config.nodeConfig = ma_node_config_init();
  58710. config.notch = ma_notch2_config_init(ma_format_f32, channels, sampleRate, q, frequency);
  58711. return config;
  58712. }
  58713. static void ma_notch_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58714. {
  58715. ma_notch_node* pBPFNode = (ma_notch_node*)pNode;
  58716. MA_ASSERT(pNode != NULL);
  58717. (void)pFrameCountIn;
  58718. ma_notch2_process_pcm_frames(&pBPFNode->notch, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58719. }
  58720. static ma_node_vtable g_ma_notch_node_vtable =
  58721. {
  58722. ma_notch_node_process_pcm_frames,
  58723. NULL, /* onGetRequiredInputFrameCount */
  58724. 1, /* One input. */
  58725. 1, /* One output. */
  58726. 0 /* Default flags. */
  58727. };
  58728. 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)
  58729. {
  58730. ma_result result;
  58731. ma_node_config baseNodeConfig;
  58732. if (pNode == NULL) {
  58733. return MA_INVALID_ARGS;
  58734. }
  58735. MA_ZERO_OBJECT(pNode);
  58736. if (pConfig == NULL) {
  58737. return MA_INVALID_ARGS;
  58738. }
  58739. if (pConfig->notch.format != ma_format_f32) {
  58740. return MA_INVALID_ARGS; /* The format must be f32. */
  58741. }
  58742. result = ma_notch2_init(&pConfig->notch, pAllocationCallbacks, &pNode->notch);
  58743. if (result != MA_SUCCESS) {
  58744. return result;
  58745. }
  58746. baseNodeConfig = ma_node_config_init();
  58747. baseNodeConfig.vtable = &g_ma_notch_node_vtable;
  58748. baseNodeConfig.pInputChannels = &pConfig->notch.channels;
  58749. baseNodeConfig.pOutputChannels = &pConfig->notch.channels;
  58750. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58751. if (result != MA_SUCCESS) {
  58752. return result;
  58753. }
  58754. return result;
  58755. }
  58756. MA_API ma_result ma_notch_node_reinit(const ma_notch_config* pConfig, ma_notch_node* pNode)
  58757. {
  58758. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  58759. if (pNode == NULL) {
  58760. return MA_INVALID_ARGS;
  58761. }
  58762. return ma_notch2_reinit(pConfig, &pNotchNode->notch);
  58763. }
  58764. MA_API void ma_notch_node_uninit(ma_notch_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58765. {
  58766. ma_notch_node* pNotchNode = (ma_notch_node*)pNode;
  58767. if (pNode == NULL) {
  58768. return;
  58769. }
  58770. ma_node_uninit(pNode, pAllocationCallbacks);
  58771. ma_notch2_uninit(&pNotchNode->notch, pAllocationCallbacks);
  58772. }
  58773. /*
  58774. Peaking Filter Node
  58775. */
  58776. MA_API ma_peak_node_config ma_peak_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  58777. {
  58778. ma_peak_node_config config;
  58779. config.nodeConfig = ma_node_config_init();
  58780. config.peak = ma_peak2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  58781. return config;
  58782. }
  58783. static void ma_peak_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58784. {
  58785. ma_peak_node* pBPFNode = (ma_peak_node*)pNode;
  58786. MA_ASSERT(pNode != NULL);
  58787. (void)pFrameCountIn;
  58788. ma_peak2_process_pcm_frames(&pBPFNode->peak, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58789. }
  58790. static ma_node_vtable g_ma_peak_node_vtable =
  58791. {
  58792. ma_peak_node_process_pcm_frames,
  58793. NULL, /* onGetRequiredInputFrameCount */
  58794. 1, /* One input. */
  58795. 1, /* One output. */
  58796. 0 /* Default flags. */
  58797. };
  58798. 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)
  58799. {
  58800. ma_result result;
  58801. ma_node_config baseNodeConfig;
  58802. if (pNode == NULL) {
  58803. return MA_INVALID_ARGS;
  58804. }
  58805. MA_ZERO_OBJECT(pNode);
  58806. if (pConfig == NULL) {
  58807. return MA_INVALID_ARGS;
  58808. }
  58809. if (pConfig->peak.format != ma_format_f32) {
  58810. return MA_INVALID_ARGS; /* The format must be f32. */
  58811. }
  58812. result = ma_peak2_init(&pConfig->peak, pAllocationCallbacks, &pNode->peak);
  58813. if (result != MA_SUCCESS) {
  58814. ma_node_uninit(pNode, pAllocationCallbacks);
  58815. return result;
  58816. }
  58817. baseNodeConfig = ma_node_config_init();
  58818. baseNodeConfig.vtable = &g_ma_peak_node_vtable;
  58819. baseNodeConfig.pInputChannels = &pConfig->peak.channels;
  58820. baseNodeConfig.pOutputChannels = &pConfig->peak.channels;
  58821. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58822. if (result != MA_SUCCESS) {
  58823. return result;
  58824. }
  58825. return result;
  58826. }
  58827. MA_API ma_result ma_peak_node_reinit(const ma_peak_config* pConfig, ma_peak_node* pNode)
  58828. {
  58829. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  58830. if (pNode == NULL) {
  58831. return MA_INVALID_ARGS;
  58832. }
  58833. return ma_peak2_reinit(pConfig, &pPeakNode->peak);
  58834. }
  58835. MA_API void ma_peak_node_uninit(ma_peak_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58836. {
  58837. ma_peak_node* pPeakNode = (ma_peak_node*)pNode;
  58838. if (pNode == NULL) {
  58839. return;
  58840. }
  58841. ma_node_uninit(pNode, pAllocationCallbacks);
  58842. ma_peak2_uninit(&pPeakNode->peak, pAllocationCallbacks);
  58843. }
  58844. /*
  58845. Low Shelf Filter Node
  58846. */
  58847. MA_API ma_loshelf_node_config ma_loshelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  58848. {
  58849. ma_loshelf_node_config config;
  58850. config.nodeConfig = ma_node_config_init();
  58851. config.loshelf = ma_loshelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  58852. return config;
  58853. }
  58854. static void ma_loshelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58855. {
  58856. ma_loshelf_node* pBPFNode = (ma_loshelf_node*)pNode;
  58857. MA_ASSERT(pNode != NULL);
  58858. (void)pFrameCountIn;
  58859. ma_loshelf2_process_pcm_frames(&pBPFNode->loshelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58860. }
  58861. static ma_node_vtable g_ma_loshelf_node_vtable =
  58862. {
  58863. ma_loshelf_node_process_pcm_frames,
  58864. NULL, /* onGetRequiredInputFrameCount */
  58865. 1, /* One input. */
  58866. 1, /* One output. */
  58867. 0 /* Default flags. */
  58868. };
  58869. 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)
  58870. {
  58871. ma_result result;
  58872. ma_node_config baseNodeConfig;
  58873. if (pNode == NULL) {
  58874. return MA_INVALID_ARGS;
  58875. }
  58876. MA_ZERO_OBJECT(pNode);
  58877. if (pConfig == NULL) {
  58878. return MA_INVALID_ARGS;
  58879. }
  58880. if (pConfig->loshelf.format != ma_format_f32) {
  58881. return MA_INVALID_ARGS; /* The format must be f32. */
  58882. }
  58883. result = ma_loshelf2_init(&pConfig->loshelf, pAllocationCallbacks, &pNode->loshelf);
  58884. if (result != MA_SUCCESS) {
  58885. return result;
  58886. }
  58887. baseNodeConfig = ma_node_config_init();
  58888. baseNodeConfig.vtable = &g_ma_loshelf_node_vtable;
  58889. baseNodeConfig.pInputChannels = &pConfig->loshelf.channels;
  58890. baseNodeConfig.pOutputChannels = &pConfig->loshelf.channels;
  58891. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58892. if (result != MA_SUCCESS) {
  58893. return result;
  58894. }
  58895. return result;
  58896. }
  58897. MA_API ma_result ma_loshelf_node_reinit(const ma_loshelf_config* pConfig, ma_loshelf_node* pNode)
  58898. {
  58899. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  58900. if (pNode == NULL) {
  58901. return MA_INVALID_ARGS;
  58902. }
  58903. return ma_loshelf2_reinit(pConfig, &pLoshelfNode->loshelf);
  58904. }
  58905. MA_API void ma_loshelf_node_uninit(ma_loshelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58906. {
  58907. ma_loshelf_node* pLoshelfNode = (ma_loshelf_node*)pNode;
  58908. if (pNode == NULL) {
  58909. return;
  58910. }
  58911. ma_node_uninit(pNode, pAllocationCallbacks);
  58912. ma_loshelf2_uninit(&pLoshelfNode->loshelf, pAllocationCallbacks);
  58913. }
  58914. /*
  58915. High Shelf Filter Node
  58916. */
  58917. MA_API ma_hishelf_node_config ma_hishelf_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, double gainDB, double q, double frequency)
  58918. {
  58919. ma_hishelf_node_config config;
  58920. config.nodeConfig = ma_node_config_init();
  58921. config.hishelf = ma_hishelf2_config_init(ma_format_f32, channels, sampleRate, gainDB, q, frequency);
  58922. return config;
  58923. }
  58924. static void ma_hishelf_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58925. {
  58926. ma_hishelf_node* pBPFNode = (ma_hishelf_node*)pNode;
  58927. MA_ASSERT(pNode != NULL);
  58928. (void)pFrameCountIn;
  58929. ma_hishelf2_process_pcm_frames(&pBPFNode->hishelf, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58930. }
  58931. static ma_node_vtable g_ma_hishelf_node_vtable =
  58932. {
  58933. ma_hishelf_node_process_pcm_frames,
  58934. NULL, /* onGetRequiredInputFrameCount */
  58935. 1, /* One input. */
  58936. 1, /* One output. */
  58937. 0 /* Default flags. */
  58938. };
  58939. 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)
  58940. {
  58941. ma_result result;
  58942. ma_node_config baseNodeConfig;
  58943. if (pNode == NULL) {
  58944. return MA_INVALID_ARGS;
  58945. }
  58946. MA_ZERO_OBJECT(pNode);
  58947. if (pConfig == NULL) {
  58948. return MA_INVALID_ARGS;
  58949. }
  58950. if (pConfig->hishelf.format != ma_format_f32) {
  58951. return MA_INVALID_ARGS; /* The format must be f32. */
  58952. }
  58953. result = ma_hishelf2_init(&pConfig->hishelf, pAllocationCallbacks, &pNode->hishelf);
  58954. if (result != MA_SUCCESS) {
  58955. return result;
  58956. }
  58957. baseNodeConfig = ma_node_config_init();
  58958. baseNodeConfig.vtable = &g_ma_hishelf_node_vtable;
  58959. baseNodeConfig.pInputChannels = &pConfig->hishelf.channels;
  58960. baseNodeConfig.pOutputChannels = &pConfig->hishelf.channels;
  58961. result = ma_node_init(pNodeGraph, &baseNodeConfig, pAllocationCallbacks, pNode);
  58962. if (result != MA_SUCCESS) {
  58963. return result;
  58964. }
  58965. return result;
  58966. }
  58967. MA_API ma_result ma_hishelf_node_reinit(const ma_hishelf_config* pConfig, ma_hishelf_node* pNode)
  58968. {
  58969. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  58970. if (pNode == NULL) {
  58971. return MA_INVALID_ARGS;
  58972. }
  58973. return ma_hishelf2_reinit(pConfig, &pHishelfNode->hishelf);
  58974. }
  58975. MA_API void ma_hishelf_node_uninit(ma_hishelf_node* pNode, const ma_allocation_callbacks* pAllocationCallbacks)
  58976. {
  58977. ma_hishelf_node* pHishelfNode = (ma_hishelf_node*)pNode;
  58978. if (pNode == NULL) {
  58979. return;
  58980. }
  58981. ma_node_uninit(pNode, pAllocationCallbacks);
  58982. ma_hishelf2_uninit(&pHishelfNode->hishelf, pAllocationCallbacks);
  58983. }
  58984. MA_API ma_delay_node_config ma_delay_node_config_init(ma_uint32 channels, ma_uint32 sampleRate, ma_uint32 delayInFrames, float decay)
  58985. {
  58986. ma_delay_node_config config;
  58987. config.nodeConfig = ma_node_config_init();
  58988. config.delay = ma_delay_config_init(channels, sampleRate, delayInFrames, decay);
  58989. return config;
  58990. }
  58991. static void ma_delay_node_process_pcm_frames(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  58992. {
  58993. ma_delay_node* pDelayNode = (ma_delay_node*)pNode;
  58994. (void)pFrameCountIn;
  58995. ma_delay_process_pcm_frames(&pDelayNode->delay, ppFramesOut[0], ppFramesIn[0], *pFrameCountOut);
  58996. }
  58997. static ma_node_vtable g_ma_delay_node_vtable =
  58998. {
  58999. ma_delay_node_process_pcm_frames,
  59000. NULL,
  59001. 1, /* 1 input channels. */
  59002. 1, /* 1 output channel. */
  59003. MA_NODE_FLAG_CONTINUOUS_PROCESSING /* Delay requires continuous processing to ensure the tail get's processed. */
  59004. };
  59005. 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)
  59006. {
  59007. ma_result result;
  59008. ma_node_config baseConfig;
  59009. if (pDelayNode == NULL) {
  59010. return MA_INVALID_ARGS;
  59011. }
  59012. MA_ZERO_OBJECT(pDelayNode);
  59013. result = ma_delay_init(&pConfig->delay, pAllocationCallbacks, &pDelayNode->delay);
  59014. if (result != MA_SUCCESS) {
  59015. return result;
  59016. }
  59017. baseConfig = pConfig->nodeConfig;
  59018. baseConfig.vtable = &g_ma_delay_node_vtable;
  59019. baseConfig.pInputChannels = &pConfig->delay.channels;
  59020. baseConfig.pOutputChannels = &pConfig->delay.channels;
  59021. result = ma_node_init(pNodeGraph, &baseConfig, pAllocationCallbacks, &pDelayNode->baseNode);
  59022. if (result != MA_SUCCESS) {
  59023. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  59024. return result;
  59025. }
  59026. return result;
  59027. }
  59028. MA_API void ma_delay_node_uninit(ma_delay_node* pDelayNode, const ma_allocation_callbacks* pAllocationCallbacks)
  59029. {
  59030. if (pDelayNode == NULL) {
  59031. return;
  59032. }
  59033. /* The base node is always uninitialized first. */
  59034. ma_node_uninit(pDelayNode, pAllocationCallbacks);
  59035. ma_delay_uninit(&pDelayNode->delay, pAllocationCallbacks);
  59036. }
  59037. MA_API void ma_delay_node_set_wet(ma_delay_node* pDelayNode, float value)
  59038. {
  59039. if (pDelayNode == NULL) {
  59040. return;
  59041. }
  59042. ma_delay_set_wet(&pDelayNode->delay, value);
  59043. }
  59044. MA_API float ma_delay_node_get_wet(const ma_delay_node* pDelayNode)
  59045. {
  59046. if (pDelayNode == NULL) {
  59047. return 0;
  59048. }
  59049. return ma_delay_get_wet(&pDelayNode->delay);
  59050. }
  59051. MA_API void ma_delay_node_set_dry(ma_delay_node* pDelayNode, float value)
  59052. {
  59053. if (pDelayNode == NULL) {
  59054. return;
  59055. }
  59056. ma_delay_set_dry(&pDelayNode->delay, value);
  59057. }
  59058. MA_API float ma_delay_node_get_dry(const ma_delay_node* pDelayNode)
  59059. {
  59060. if (pDelayNode == NULL) {
  59061. return 0;
  59062. }
  59063. return ma_delay_get_dry(&pDelayNode->delay);
  59064. }
  59065. MA_API void ma_delay_node_set_decay(ma_delay_node* pDelayNode, float value)
  59066. {
  59067. if (pDelayNode == NULL) {
  59068. return;
  59069. }
  59070. ma_delay_set_decay(&pDelayNode->delay, value);
  59071. }
  59072. MA_API float ma_delay_node_get_decay(const ma_delay_node* pDelayNode)
  59073. {
  59074. if (pDelayNode == NULL) {
  59075. return 0;
  59076. }
  59077. return ma_delay_get_decay(&pDelayNode->delay);
  59078. }
  59079. #endif /* MA_NO_NODE_GRAPH */
  59080. /* SECTION: miniaudio_engine.c */
  59081. #if !defined(MA_NO_ENGINE) && !defined(MA_NO_NODE_GRAPH)
  59082. /**************************************************************************************************************************************************************
  59083. Engine
  59084. **************************************************************************************************************************************************************/
  59085. #define MA_SEEK_TARGET_NONE (~(ma_uint64)0)
  59086. MA_API ma_engine_node_config ma_engine_node_config_init(ma_engine* pEngine, ma_engine_node_type type, ma_uint32 flags)
  59087. {
  59088. ma_engine_node_config config;
  59089. MA_ZERO_OBJECT(&config);
  59090. config.pEngine = pEngine;
  59091. config.type = type;
  59092. config.isPitchDisabled = (flags & MA_SOUND_FLAG_NO_PITCH) != 0;
  59093. config.isSpatializationDisabled = (flags & MA_SOUND_FLAG_NO_SPATIALIZATION) != 0;
  59094. config.monoExpansionMode = pEngine->monoExpansionMode;
  59095. return config;
  59096. }
  59097. static void ma_engine_node_update_pitch_if_required(ma_engine_node* pEngineNode)
  59098. {
  59099. ma_bool32 isUpdateRequired = MA_FALSE;
  59100. float newPitch;
  59101. MA_ASSERT(pEngineNode != NULL);
  59102. newPitch = c89atomic_load_explicit_f32(&pEngineNode->pitch, c89atomic_memory_order_acquire);
  59103. if (pEngineNode->oldPitch != newPitch) {
  59104. pEngineNode->oldPitch = newPitch;
  59105. isUpdateRequired = MA_TRUE;
  59106. }
  59107. if (pEngineNode->oldDopplerPitch != pEngineNode->spatializer.dopplerPitch) {
  59108. pEngineNode->oldDopplerPitch = pEngineNode->spatializer.dopplerPitch;
  59109. isUpdateRequired = MA_TRUE;
  59110. }
  59111. if (isUpdateRequired) {
  59112. float basePitch = (float)pEngineNode->sampleRate / ma_engine_get_sample_rate(pEngineNode->pEngine);
  59113. ma_linear_resampler_set_rate_ratio(&pEngineNode->resampler, basePitch * pEngineNode->oldPitch * pEngineNode->oldDopplerPitch);
  59114. }
  59115. }
  59116. static ma_bool32 ma_engine_node_is_pitching_enabled(const ma_engine_node* pEngineNode)
  59117. {
  59118. MA_ASSERT(pEngineNode != NULL);
  59119. /* Don't try to be clever by skiping resampling in the pitch=1 case or else you'll glitch when moving away from 1. */
  59120. return !c89atomic_load_explicit_32(&pEngineNode->isPitchDisabled, c89atomic_memory_order_acquire);
  59121. }
  59122. static ma_bool32 ma_engine_node_is_spatialization_enabled(const ma_engine_node* pEngineNode)
  59123. {
  59124. MA_ASSERT(pEngineNode != NULL);
  59125. return !c89atomic_load_explicit_32(&pEngineNode->isSpatializationDisabled, c89atomic_memory_order_acquire);
  59126. }
  59127. static ma_uint64 ma_engine_node_get_required_input_frame_count(const ma_engine_node* pEngineNode, ma_uint64 outputFrameCount)
  59128. {
  59129. ma_uint64 inputFrameCount = 0;
  59130. if (ma_engine_node_is_pitching_enabled(pEngineNode)) {
  59131. ma_result result = ma_linear_resampler_get_required_input_frame_count(&pEngineNode->resampler, outputFrameCount, &inputFrameCount);
  59132. if (result != MA_SUCCESS) {
  59133. inputFrameCount = 0;
  59134. }
  59135. } else {
  59136. inputFrameCount = outputFrameCount; /* No resampling, so 1:1. */
  59137. }
  59138. return inputFrameCount;
  59139. }
  59140. static void ma_engine_node_process_pcm_frames__general(ma_engine_node* pEngineNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59141. {
  59142. ma_uint32 frameCountIn;
  59143. ma_uint32 frameCountOut;
  59144. ma_uint32 totalFramesProcessedIn;
  59145. ma_uint32 totalFramesProcessedOut;
  59146. ma_uint32 channelsIn;
  59147. ma_uint32 channelsOut;
  59148. ma_bool32 isPitchingEnabled;
  59149. ma_bool32 isFadingEnabled;
  59150. ma_bool32 isSpatializationEnabled;
  59151. ma_bool32 isPanningEnabled;
  59152. frameCountIn = *pFrameCountIn;
  59153. frameCountOut = *pFrameCountOut;
  59154. channelsIn = ma_spatializer_get_input_channels(&pEngineNode->spatializer);
  59155. channelsOut = ma_spatializer_get_output_channels(&pEngineNode->spatializer);
  59156. totalFramesProcessedIn = 0;
  59157. totalFramesProcessedOut = 0;
  59158. isPitchingEnabled = ma_engine_node_is_pitching_enabled(pEngineNode);
  59159. isFadingEnabled = pEngineNode->fader.volumeBeg != 1 || pEngineNode->fader.volumeEnd != 1;
  59160. isSpatializationEnabled = ma_engine_node_is_spatialization_enabled(pEngineNode);
  59161. isPanningEnabled = pEngineNode->panner.pan != 0 && channelsOut != 1;
  59162. /* Keep going while we've still got data available for processing. */
  59163. while (totalFramesProcessedOut < frameCountOut) {
  59164. /*
  59165. We need to process in a specific order. We always do resampling first because it's likely
  59166. we're going to be increasing the channel count after spatialization. Also, I want to do
  59167. fading based on the output sample rate.
  59168. We'll first read into a buffer from the resampler. Then we'll do all processing that
  59169. operates on the on the input channel count. We'll then get the spatializer to output to
  59170. the output buffer and then do all effects from that point directly in the output buffer
  59171. in-place.
  59172. Note that we're always running the resampler. If we try to be clever and skip resampling
  59173. when the pitch is 1, we'll get a glitch when we move away from 1, back to 1, and then
  59174. away from 1 again. We'll want to implement any pitch=1 optimizations in the resampler
  59175. itself.
  59176. There's a small optimization here that we'll utilize since it might be a fairly common
  59177. case. When the input and output channel counts are the same, we'll read straight into the
  59178. output buffer from the resampler and do everything in-place.
  59179. */
  59180. const float* pRunningFramesIn;
  59181. float* pRunningFramesOut;
  59182. float* pWorkingBuffer; /* This is the buffer that we'll be processing frames in. This is in input channels. */
  59183. float temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE / sizeof(float)];
  59184. ma_uint32 tempCapInFrames = ma_countof(temp) / channelsIn;
  59185. ma_uint32 framesAvailableIn;
  59186. ma_uint32 framesAvailableOut;
  59187. ma_uint32 framesJustProcessedIn;
  59188. ma_uint32 framesJustProcessedOut;
  59189. ma_bool32 isWorkingBufferValid = MA_FALSE;
  59190. framesAvailableIn = frameCountIn - totalFramesProcessedIn;
  59191. framesAvailableOut = frameCountOut - totalFramesProcessedOut;
  59192. pRunningFramesIn = ma_offset_pcm_frames_const_ptr_f32(ppFramesIn[0], totalFramesProcessedIn, channelsIn);
  59193. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesProcessedOut, channelsOut);
  59194. if (channelsIn == channelsOut) {
  59195. /* Fast path. Channel counts are the same. No need for an intermediary input buffer. */
  59196. pWorkingBuffer = pRunningFramesOut;
  59197. } else {
  59198. /* Slow path. Channel counts are different. Need to use an intermediary input buffer. */
  59199. pWorkingBuffer = temp;
  59200. if (framesAvailableOut > tempCapInFrames) {
  59201. framesAvailableOut = tempCapInFrames;
  59202. }
  59203. }
  59204. /* First is resampler. */
  59205. if (isPitchingEnabled) {
  59206. ma_uint64 resampleFrameCountIn = framesAvailableIn;
  59207. ma_uint64 resampleFrameCountOut = framesAvailableOut;
  59208. ma_linear_resampler_process_pcm_frames(&pEngineNode->resampler, pRunningFramesIn, &resampleFrameCountIn, pWorkingBuffer, &resampleFrameCountOut);
  59209. isWorkingBufferValid = MA_TRUE;
  59210. framesJustProcessedIn = (ma_uint32)resampleFrameCountIn;
  59211. framesJustProcessedOut = (ma_uint32)resampleFrameCountOut;
  59212. } else {
  59213. framesJustProcessedIn = ma_min(framesAvailableIn, framesAvailableOut);
  59214. framesJustProcessedOut = framesJustProcessedIn; /* When no resampling is being performed, the number of output frames is the same as input frames. */
  59215. }
  59216. /* Fading. */
  59217. if (isFadingEnabled) {
  59218. if (isWorkingBufferValid) {
  59219. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pWorkingBuffer, framesJustProcessedOut); /* In-place processing. */
  59220. } else {
  59221. ma_fader_process_pcm_frames(&pEngineNode->fader, pWorkingBuffer, pRunningFramesIn, framesJustProcessedOut);
  59222. isWorkingBufferValid = MA_TRUE;
  59223. }
  59224. }
  59225. /*
  59226. If at this point we still haven't actually done anything with the working buffer we need
  59227. to just read straight from the input buffer.
  59228. */
  59229. if (isWorkingBufferValid == MA_FALSE) {
  59230. 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. */
  59231. }
  59232. /* Spatialization. */
  59233. if (isSpatializationEnabled) {
  59234. ma_uint32 iListener;
  59235. /*
  59236. When determining the listener to use, we first check to see if the sound is pinned to a
  59237. specific listener. If so, we use that. Otherwise we just use the closest listener.
  59238. */
  59239. if (pEngineNode->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pEngineNode->pinnedListenerIndex < ma_engine_get_listener_count(pEngineNode->pEngine)) {
  59240. iListener = pEngineNode->pinnedListenerIndex;
  59241. } else {
  59242. iListener = ma_engine_find_closest_listener(pEngineNode->pEngine, pEngineNode->spatializer.position.x, pEngineNode->spatializer.position.y, pEngineNode->spatializer.position.z);
  59243. }
  59244. ma_spatializer_process_pcm_frames(&pEngineNode->spatializer, &pEngineNode->pEngine->listeners[iListener], pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut);
  59245. } else {
  59246. /* No spatialization, but we still need to do channel conversion. */
  59247. if (channelsIn == channelsOut) {
  59248. /* No channel conversion required. Just copy straight to the output buffer. */
  59249. ma_copy_pcm_frames(pRunningFramesOut, pWorkingBuffer, framesJustProcessedOut, ma_format_f32, channelsOut);
  59250. } else {
  59251. /* Channel conversion required. TODO: Add support for channel maps here. */
  59252. ma_channel_map_apply_f32(pRunningFramesOut, NULL, channelsOut, pWorkingBuffer, NULL, channelsIn, framesJustProcessedOut, ma_channel_mix_mode_simple, pEngineNode->monoExpansionMode);
  59253. }
  59254. }
  59255. /* At this point we can guarantee that the output buffer contains valid data. We can process everything in place now. */
  59256. /* Panning. */
  59257. if (isPanningEnabled) {
  59258. ma_panner_process_pcm_frames(&pEngineNode->panner, pRunningFramesOut, pRunningFramesOut, framesJustProcessedOut); /* In-place processing. */
  59259. }
  59260. /* We're done for this chunk. */
  59261. totalFramesProcessedIn += framesJustProcessedIn;
  59262. totalFramesProcessedOut += framesJustProcessedOut;
  59263. /* 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. */
  59264. if (framesJustProcessedOut == 0) {
  59265. break;
  59266. }
  59267. }
  59268. /* At this point we're done processing. */
  59269. *pFrameCountIn = totalFramesProcessedIn;
  59270. *pFrameCountOut = totalFramesProcessedOut;
  59271. }
  59272. static void ma_engine_node_process_pcm_frames__sound(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59273. {
  59274. /* For sounds, we need to first read from the data source. Then we need to apply the engine effects (pan, pitch, fades, etc.). */
  59275. ma_result result = MA_SUCCESS;
  59276. ma_sound* pSound = (ma_sound*)pNode;
  59277. ma_uint32 frameCount = *pFrameCountOut;
  59278. ma_uint32 totalFramesRead = 0;
  59279. ma_format dataSourceFormat;
  59280. ma_uint32 dataSourceChannels;
  59281. ma_uint8 temp[MA_DATA_CONVERTER_STACK_BUFFER_SIZE];
  59282. ma_uint32 tempCapInFrames;
  59283. ma_uint64 seekTarget;
  59284. /* This is a data source node which means no input buses. */
  59285. (void)ppFramesIn;
  59286. (void)pFrameCountIn;
  59287. /* If we're marked at the end we need to stop the sound and do nothing. */
  59288. if (ma_sound_at_end(pSound)) {
  59289. ma_sound_stop(pSound);
  59290. *pFrameCountOut = 0;
  59291. return;
  59292. }
  59293. /* If we're seeking, do so now before reading. */
  59294. seekTarget = c89atomic_load_64(&pSound->seekTarget);
  59295. if (seekTarget != MA_SEEK_TARGET_NONE) {
  59296. ma_data_source_seek_to_pcm_frame(pSound->pDataSource, seekTarget);
  59297. /* Any time-dependant effects need to have their times updated. */
  59298. ma_node_set_time(pSound, seekTarget);
  59299. c89atomic_exchange_64(&pSound->seekTarget, MA_SEEK_TARGET_NONE);
  59300. }
  59301. /*
  59302. We want to update the pitch once. For sounds, this can be either at the start or at the end. If
  59303. we don't force this to only ever be updating once, we could end up in a situation where
  59304. retrieving the required input frame count ends up being different to what we actually retrieve.
  59305. What could happen is that the required input frame count is calculated, the pitch is update,
  59306. and then this processing function is called resulting in a different number of input frames
  59307. being processed. Do not call this in ma_engine_node_process_pcm_frames__general() or else
  59308. you'll hit the aforementioned bug.
  59309. */
  59310. ma_engine_node_update_pitch_if_required(&pSound->engineNode);
  59311. /*
  59312. For the convenience of the caller, we're doing to allow data sources to use non-floating-point formats and channel counts that differ
  59313. from the main engine.
  59314. */
  59315. result = ma_data_source_get_data_format(pSound->pDataSource, &dataSourceFormat, &dataSourceChannels, NULL, NULL, 0);
  59316. if (result == MA_SUCCESS) {
  59317. tempCapInFrames = sizeof(temp) / ma_get_bytes_per_frame(dataSourceFormat, dataSourceChannels);
  59318. /* Keep reading until we've read as much as was requested or we reach the end of the data source. */
  59319. while (totalFramesRead < frameCount) {
  59320. ma_uint32 framesRemaining = frameCount - totalFramesRead;
  59321. ma_uint32 framesToRead;
  59322. ma_uint64 framesJustRead;
  59323. ma_uint32 frameCountIn;
  59324. ma_uint32 frameCountOut;
  59325. const float* pRunningFramesIn;
  59326. float* pRunningFramesOut;
  59327. /*
  59328. The first thing we need to do is read into the temporary buffer. We can calculate exactly
  59329. how many input frames we'll need after resampling.
  59330. */
  59331. framesToRead = (ma_uint32)ma_engine_node_get_required_input_frame_count(&pSound->engineNode, framesRemaining);
  59332. if (framesToRead > tempCapInFrames) {
  59333. framesToRead = tempCapInFrames;
  59334. }
  59335. result = ma_data_source_read_pcm_frames(pSound->pDataSource, temp, framesToRead, &framesJustRead);
  59336. /* 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. */
  59337. if (result == MA_AT_END) {
  59338. c89atomic_exchange_32(&pSound->atEnd, MA_TRUE); /* This will be set to false in ma_sound_start(). */
  59339. }
  59340. pRunningFramesOut = ma_offset_pcm_frames_ptr_f32(ppFramesOut[0], totalFramesRead, ma_engine_get_channels(ma_sound_get_engine(pSound)));
  59341. frameCountIn = (ma_uint32)framesJustRead;
  59342. frameCountOut = framesRemaining;
  59343. /* Convert if necessary. */
  59344. if (dataSourceFormat == ma_format_f32) {
  59345. /* Fast path. No data conversion necessary. */
  59346. pRunningFramesIn = (float*)temp;
  59347. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  59348. } else {
  59349. /* 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. */
  59350. 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. */
  59351. ma_convert_pcm_frames_format(tempf32, ma_format_f32, temp, dataSourceFormat, framesJustRead, dataSourceChannels, ma_dither_mode_none);
  59352. /* Now that we have our samples in f32 format we can process like normal. */
  59353. pRunningFramesIn = tempf32;
  59354. ma_engine_node_process_pcm_frames__general(&pSound->engineNode, &pRunningFramesIn, &frameCountIn, &pRunningFramesOut, &frameCountOut);
  59355. }
  59356. /* We should have processed all of our input frames since we calculated the required number of input frames at the top. */
  59357. MA_ASSERT(frameCountIn == framesJustRead);
  59358. totalFramesRead += (ma_uint32)frameCountOut; /* Safe cast. */
  59359. if (result != MA_SUCCESS || ma_sound_at_end(pSound)) {
  59360. break; /* Might have reached the end. */
  59361. }
  59362. }
  59363. }
  59364. *pFrameCountOut = totalFramesRead;
  59365. }
  59366. static void ma_engine_node_process_pcm_frames__group(ma_node* pNode, const float** ppFramesIn, ma_uint32* pFrameCountIn, float** ppFramesOut, ma_uint32* pFrameCountOut)
  59367. {
  59368. /*
  59369. Make sure the pitch is updated before trying to read anything. It's important that this is done
  59370. only once and not in ma_engine_node_process_pcm_frames__general(). The reason for this is that
  59371. ma_engine_node_process_pcm_frames__general() will call ma_engine_node_get_required_input_frame_count(),
  59372. and if another thread modifies the pitch just after that call it can result in a glitch due to
  59373. the input rate changing.
  59374. */
  59375. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  59376. /* For groups, the input data has already been read and we just need to apply the effect. */
  59377. ma_engine_node_process_pcm_frames__general((ma_engine_node*)pNode, ppFramesIn, pFrameCountIn, ppFramesOut, pFrameCountOut);
  59378. }
  59379. static ma_result ma_engine_node_get_required_input_frame_count__group(ma_node* pNode, ma_uint32 outputFrameCount, ma_uint32* pInputFrameCount)
  59380. {
  59381. ma_uint64 inputFrameCount;
  59382. MA_ASSERT(pInputFrameCount != NULL);
  59383. /* Our pitch will affect this calculation. We need to update it. */
  59384. ma_engine_node_update_pitch_if_required((ma_engine_node*)pNode);
  59385. inputFrameCount = ma_engine_node_get_required_input_frame_count((ma_engine_node*)pNode, outputFrameCount);
  59386. if (inputFrameCount > 0xFFFFFFFF) {
  59387. inputFrameCount = 0xFFFFFFFF; /* Will never happen because miniaudio will only ever process in relatively small chunks. */
  59388. }
  59389. *pInputFrameCount = (ma_uint32)inputFrameCount;
  59390. return MA_SUCCESS;
  59391. }
  59392. static ma_node_vtable g_ma_engine_node_vtable__sound =
  59393. {
  59394. ma_engine_node_process_pcm_frames__sound,
  59395. NULL, /* onGetRequiredInputFrameCount */
  59396. 0, /* Sounds are data source nodes which means they have zero inputs (their input is drawn from the data source itself). */
  59397. 1, /* Sounds have one output bus. */
  59398. 0 /* Default flags. */
  59399. };
  59400. static ma_node_vtable g_ma_engine_node_vtable__group =
  59401. {
  59402. ma_engine_node_process_pcm_frames__group,
  59403. ma_engine_node_get_required_input_frame_count__group,
  59404. 1, /* Groups have one input bus. */
  59405. 1, /* Groups have one output bus. */
  59406. MA_NODE_FLAG_DIFFERENT_PROCESSING_RATES /* The engine node does resampling so should let miniaudio know about it. */
  59407. };
  59408. static ma_node_config ma_engine_node_base_node_config_init(const ma_engine_node_config* pConfig)
  59409. {
  59410. ma_node_config baseNodeConfig;
  59411. if (pConfig->type == ma_engine_node_type_sound) {
  59412. /* Sound. */
  59413. baseNodeConfig = ma_node_config_init();
  59414. baseNodeConfig.vtable = &g_ma_engine_node_vtable__sound;
  59415. baseNodeConfig.initialState = ma_node_state_stopped; /* Sounds are stopped by default. */
  59416. } else {
  59417. /* Group. */
  59418. baseNodeConfig = ma_node_config_init();
  59419. baseNodeConfig.vtable = &g_ma_engine_node_vtable__group;
  59420. baseNodeConfig.initialState = ma_node_state_started; /* Groups are started by default. */
  59421. }
  59422. return baseNodeConfig;
  59423. }
  59424. static ma_spatializer_config ma_engine_node_spatializer_config_init(const ma_node_config* pBaseNodeConfig)
  59425. {
  59426. return ma_spatializer_config_init(pBaseNodeConfig->pInputChannels[0], pBaseNodeConfig->pOutputChannels[0]);
  59427. }
  59428. typedef struct
  59429. {
  59430. size_t sizeInBytes;
  59431. size_t baseNodeOffset;
  59432. size_t resamplerOffset;
  59433. size_t spatializerOffset;
  59434. } ma_engine_node_heap_layout;
  59435. static ma_result ma_engine_node_get_heap_layout(const ma_engine_node_config* pConfig, ma_engine_node_heap_layout* pHeapLayout)
  59436. {
  59437. ma_result result;
  59438. size_t tempHeapSize;
  59439. ma_node_config baseNodeConfig;
  59440. ma_linear_resampler_config resamplerConfig;
  59441. ma_spatializer_config spatializerConfig;
  59442. ma_uint32 channelsIn;
  59443. ma_uint32 channelsOut;
  59444. MA_ASSERT(pHeapLayout);
  59445. MA_ZERO_OBJECT(pHeapLayout);
  59446. if (pConfig == NULL) {
  59447. return MA_INVALID_ARGS;
  59448. }
  59449. if (pConfig->pEngine == NULL) {
  59450. return MA_INVALID_ARGS; /* An engine must be specified. */
  59451. }
  59452. pHeapLayout->sizeInBytes = 0;
  59453. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  59454. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  59455. /* Base node. */
  59456. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  59457. baseNodeConfig.pInputChannels = &channelsIn;
  59458. baseNodeConfig.pOutputChannels = &channelsOut;
  59459. result = ma_node_get_heap_size(ma_engine_get_node_graph(pConfig->pEngine), &baseNodeConfig, &tempHeapSize);
  59460. if (result != MA_SUCCESS) {
  59461. return result; /* Failed to retrieve the size of the heap for the base node. */
  59462. }
  59463. pHeapLayout->baseNodeOffset = pHeapLayout->sizeInBytes;
  59464. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  59465. /* Resmapler. */
  59466. 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. */
  59467. resamplerConfig.lpfOrder = 0;
  59468. result = ma_linear_resampler_get_heap_size(&resamplerConfig, &tempHeapSize);
  59469. if (result != MA_SUCCESS) {
  59470. return result; /* Failed to retrieve the size of the heap for the resampler. */
  59471. }
  59472. pHeapLayout->resamplerOffset = pHeapLayout->sizeInBytes;
  59473. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  59474. /* Spatializer. */
  59475. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  59476. result = ma_spatializer_get_heap_size(&spatializerConfig, &tempHeapSize);
  59477. if (result != MA_SUCCESS) {
  59478. return result; /* Failed to retrieve the size of the heap for the spatializer. */
  59479. }
  59480. pHeapLayout->spatializerOffset = pHeapLayout->sizeInBytes;
  59481. pHeapLayout->sizeInBytes += ma_align_64(tempHeapSize);
  59482. return MA_SUCCESS;
  59483. }
  59484. MA_API ma_result ma_engine_node_get_heap_size(const ma_engine_node_config* pConfig, size_t* pHeapSizeInBytes)
  59485. {
  59486. ma_result result;
  59487. ma_engine_node_heap_layout heapLayout;
  59488. if (pHeapSizeInBytes == NULL) {
  59489. return MA_INVALID_ARGS;
  59490. }
  59491. *pHeapSizeInBytes = 0;
  59492. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  59493. if (result != MA_SUCCESS) {
  59494. return result;
  59495. }
  59496. *pHeapSizeInBytes = heapLayout.sizeInBytes;
  59497. return MA_SUCCESS;
  59498. }
  59499. MA_API ma_result ma_engine_node_init_preallocated(const ma_engine_node_config* pConfig, void* pHeap, ma_engine_node* pEngineNode)
  59500. {
  59501. ma_result result;
  59502. ma_engine_node_heap_layout heapLayout;
  59503. ma_node_config baseNodeConfig;
  59504. ma_linear_resampler_config resamplerConfig;
  59505. ma_fader_config faderConfig;
  59506. ma_spatializer_config spatializerConfig;
  59507. ma_panner_config pannerConfig;
  59508. ma_uint32 channelsIn;
  59509. ma_uint32 channelsOut;
  59510. if (pEngineNode == NULL) {
  59511. return MA_INVALID_ARGS;
  59512. }
  59513. MA_ZERO_OBJECT(pEngineNode);
  59514. result = ma_engine_node_get_heap_layout(pConfig, &heapLayout);
  59515. if (result != MA_SUCCESS) {
  59516. return result;
  59517. }
  59518. if (pConfig->pinnedListenerIndex != MA_LISTENER_INDEX_CLOSEST && pConfig->pinnedListenerIndex >= ma_engine_get_listener_count(pConfig->pEngine)) {
  59519. return MA_INVALID_ARGS; /* Invalid listener. */
  59520. }
  59521. pEngineNode->_pHeap = pHeap;
  59522. MA_ZERO_MEMORY(pHeap, heapLayout.sizeInBytes);
  59523. pEngineNode->pEngine = pConfig->pEngine;
  59524. pEngineNode->sampleRate = (pConfig->sampleRate > 0) ? pConfig->sampleRate : ma_engine_get_sample_rate(pEngineNode->pEngine);
  59525. pEngineNode->monoExpansionMode = pConfig->monoExpansionMode;
  59526. pEngineNode->pitch = 1;
  59527. pEngineNode->oldPitch = 1;
  59528. pEngineNode->oldDopplerPitch = 1;
  59529. pEngineNode->isPitchDisabled = pConfig->isPitchDisabled;
  59530. pEngineNode->isSpatializationDisabled = pConfig->isSpatializationDisabled;
  59531. pEngineNode->pinnedListenerIndex = pConfig->pinnedListenerIndex;
  59532. channelsIn = (pConfig->channelsIn != 0) ? pConfig->channelsIn : ma_engine_get_channels(pConfig->pEngine);
  59533. channelsOut = (pConfig->channelsOut != 0) ? pConfig->channelsOut : ma_engine_get_channels(pConfig->pEngine);
  59534. /* Base node. */
  59535. baseNodeConfig = ma_engine_node_base_node_config_init(pConfig);
  59536. baseNodeConfig.pInputChannels = &channelsIn;
  59537. baseNodeConfig.pOutputChannels = &channelsOut;
  59538. result = ma_node_init_preallocated(&pConfig->pEngine->nodeGraph, &baseNodeConfig, ma_offset_ptr(pHeap, heapLayout.baseNodeOffset), &pEngineNode->baseNode);
  59539. if (result != MA_SUCCESS) {
  59540. goto error0;
  59541. }
  59542. /*
  59543. We can now initialize the effects we need in order to implement the engine node. There's a
  59544. defined order of operations here, mainly centered around when we convert our channels from the
  59545. data source's native channel count to the engine's channel count. As a rule, we want to do as
  59546. much computation as possible before spatialization because there's a chance that will increase
  59547. the channel count, thereby increasing the amount of work needing to be done to process.
  59548. */
  59549. /* We'll always do resampling first. */
  59550. resamplerConfig = ma_linear_resampler_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], pEngineNode->sampleRate, ma_engine_get_sample_rate(pEngineNode->pEngine));
  59551. 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. */
  59552. result = ma_linear_resampler_init_preallocated(&resamplerConfig, ma_offset_ptr(pHeap, heapLayout.resamplerOffset), &pEngineNode->resampler);
  59553. if (result != MA_SUCCESS) {
  59554. goto error1;
  59555. }
  59556. /* After resampling will come the fader. */
  59557. faderConfig = ma_fader_config_init(ma_format_f32, baseNodeConfig.pInputChannels[0], ma_engine_get_sample_rate(pEngineNode->pEngine));
  59558. result = ma_fader_init(&faderConfig, &pEngineNode->fader);
  59559. if (result != MA_SUCCESS) {
  59560. goto error2;
  59561. }
  59562. /*
  59563. Spatialization comes next. We spatialize based ont he node's output channel count. It's up the caller to
  59564. ensure channels counts link up correctly in the node graph.
  59565. */
  59566. spatializerConfig = ma_engine_node_spatializer_config_init(&baseNodeConfig);
  59567. spatializerConfig.gainSmoothTimeInFrames = pEngineNode->pEngine->gainSmoothTimeInFrames;
  59568. result = ma_spatializer_init_preallocated(&spatializerConfig, ma_offset_ptr(pHeap, heapLayout.spatializerOffset), &pEngineNode->spatializer);
  59569. if (result != MA_SUCCESS) {
  59570. goto error2;
  59571. }
  59572. /*
  59573. After spatialization comes panning. We need to do this after spatialization because otherwise we wouldn't
  59574. be able to pan mono sounds.
  59575. */
  59576. pannerConfig = ma_panner_config_init(ma_format_f32, baseNodeConfig.pOutputChannels[0]);
  59577. result = ma_panner_init(&pannerConfig, &pEngineNode->panner);
  59578. if (result != MA_SUCCESS) {
  59579. goto error3;
  59580. }
  59581. return MA_SUCCESS;
  59582. /* No need for allocation callbacks here because we use a preallocated heap. */
  59583. error3: ma_spatializer_uninit(&pEngineNode->spatializer, NULL);
  59584. error2: ma_linear_resampler_uninit(&pEngineNode->resampler, NULL);
  59585. error1: ma_node_uninit(&pEngineNode->baseNode, NULL);
  59586. error0: return result;
  59587. }
  59588. MA_API ma_result ma_engine_node_init(const ma_engine_node_config* pConfig, const ma_allocation_callbacks* pAllocationCallbacks, ma_engine_node* pEngineNode)
  59589. {
  59590. ma_result result;
  59591. size_t heapSizeInBytes;
  59592. void* pHeap;
  59593. result = ma_engine_node_get_heap_size(pConfig, &heapSizeInBytes);
  59594. if (result != MA_SUCCESS) {
  59595. return result;
  59596. }
  59597. if (heapSizeInBytes > 0) {
  59598. pHeap = ma_malloc(heapSizeInBytes, pAllocationCallbacks);
  59599. if (pHeap == NULL) {
  59600. return MA_OUT_OF_MEMORY;
  59601. }
  59602. } else {
  59603. pHeap = NULL;
  59604. }
  59605. result = ma_engine_node_init_preallocated(pConfig, pHeap, pEngineNode);
  59606. if (result != MA_SUCCESS) {
  59607. ma_free(pHeap, pAllocationCallbacks);
  59608. return result;
  59609. }
  59610. pEngineNode->_ownsHeap = MA_TRUE;
  59611. return MA_SUCCESS;
  59612. }
  59613. MA_API void ma_engine_node_uninit(ma_engine_node* pEngineNode, const ma_allocation_callbacks* pAllocationCallbacks)
  59614. {
  59615. /*
  59616. The base node always needs to be uninitialized first to ensure it's detached from the graph completely before we
  59617. destroy anything that might be in the middle of being used by the processing function.
  59618. */
  59619. ma_node_uninit(&pEngineNode->baseNode, pAllocationCallbacks);
  59620. /* Now that the node has been uninitialized we can safely uninitialize the rest. */
  59621. ma_spatializer_uninit(&pEngineNode->spatializer, pAllocationCallbacks);
  59622. ma_linear_resampler_uninit(&pEngineNode->resampler, pAllocationCallbacks);
  59623. /* Free the heap last. */
  59624. if (pEngineNode->_ownsHeap) {
  59625. ma_free(pEngineNode->_pHeap, pAllocationCallbacks);
  59626. }
  59627. }
  59628. MA_API ma_sound_config ma_sound_config_init(void)
  59629. {
  59630. return ma_sound_config_init_2(NULL);
  59631. }
  59632. MA_API ma_sound_config ma_sound_config_init_2(ma_engine* pEngine)
  59633. {
  59634. ma_sound_config config;
  59635. MA_ZERO_OBJECT(&config);
  59636. if (pEngine != NULL) {
  59637. config.monoExpansionMode = pEngine->monoExpansionMode;
  59638. } else {
  59639. config.monoExpansionMode = ma_mono_expansion_mode_default;
  59640. }
  59641. config.rangeEndInPCMFrames = ~((ma_uint64)0);
  59642. config.loopPointEndInPCMFrames = ~((ma_uint64)0);
  59643. return config;
  59644. }
  59645. MA_API ma_sound_group_config ma_sound_group_config_init(void)
  59646. {
  59647. return ma_sound_group_config_init_2(NULL);
  59648. }
  59649. MA_API ma_sound_group_config ma_sound_group_config_init_2(ma_engine* pEngine)
  59650. {
  59651. ma_sound_group_config config;
  59652. MA_ZERO_OBJECT(&config);
  59653. if (pEngine != NULL) {
  59654. config.monoExpansionMode = pEngine->monoExpansionMode;
  59655. } else {
  59656. config.monoExpansionMode = ma_mono_expansion_mode_default;
  59657. }
  59658. return config;
  59659. }
  59660. MA_API ma_engine_config ma_engine_config_init(void)
  59661. {
  59662. ma_engine_config config;
  59663. MA_ZERO_OBJECT(&config);
  59664. config.listenerCount = 1; /* Always want at least one listener. */
  59665. config.monoExpansionMode = ma_mono_expansion_mode_default;
  59666. return config;
  59667. }
  59668. #if !defined(MA_NO_DEVICE_IO)
  59669. static void ma_engine_data_callback_internal(ma_device* pDevice, void* pFramesOut, const void* pFramesIn, ma_uint32 frameCount)
  59670. {
  59671. ma_engine* pEngine = (ma_engine*)pDevice->pUserData;
  59672. (void)pFramesIn;
  59673. /*
  59674. Experiment: Try processing a resource manager job if we're on the Emscripten build.
  59675. This serves two purposes:
  59676. 1) It ensures jobs are actually processed at some point since we cannot guarantee that the
  59677. caller is doing the right thing and calling ma_resource_manager_process_next_job(); and
  59678. 2) It's an attempt at working around an issue where processing jobs on the Emscripten main
  59679. loop doesn't work as well as it should. When trying to load sounds without the `DECODE`
  59680. flag or with the `ASYNC` flag, the sound data is just not able to be loaded in time
  59681. before the callback is processed. I think it's got something to do with the single-
  59682. threaded nature of Web, but I'm not entirely sure.
  59683. */
  59684. #if !defined(MA_NO_RESOURCE_MANAGER) && defined(MA_EMSCRIPTEN)
  59685. {
  59686. if (pEngine->pResourceManager != NULL) {
  59687. if ((pEngine->pResourceManager->config.flags & MA_RESOURCE_MANAGER_FLAG_NO_THREADING) != 0) {
  59688. ma_resource_manager_process_next_job(pEngine->pResourceManager);
  59689. }
  59690. }
  59691. }
  59692. #endif
  59693. ma_engine_read_pcm_frames(pEngine, pFramesOut, frameCount, NULL);
  59694. }
  59695. #endif
  59696. MA_API ma_result ma_engine_init(const ma_engine_config* pConfig, ma_engine* pEngine)
  59697. {
  59698. ma_result result;
  59699. ma_node_graph_config nodeGraphConfig;
  59700. ma_engine_config engineConfig;
  59701. ma_spatializer_listener_config listenerConfig;
  59702. ma_uint32 iListener;
  59703. if (pEngine == NULL) {
  59704. return MA_INVALID_ARGS;
  59705. }
  59706. MA_ZERO_OBJECT(pEngine);
  59707. /* The config is allowed to be NULL in which case we use defaults for everything. */
  59708. if (pConfig != NULL) {
  59709. engineConfig = *pConfig;
  59710. } else {
  59711. engineConfig = ma_engine_config_init();
  59712. }
  59713. pEngine->monoExpansionMode = engineConfig.monoExpansionMode;
  59714. ma_allocation_callbacks_init_copy(&pEngine->allocationCallbacks, &engineConfig.allocationCallbacks);
  59715. #if !defined(MA_NO_RESOURCE_MANAGER)
  59716. {
  59717. pEngine->pResourceManager = engineConfig.pResourceManager;
  59718. }
  59719. #endif
  59720. #if !defined(MA_NO_DEVICE_IO)
  59721. {
  59722. pEngine->pDevice = engineConfig.pDevice;
  59723. /* If we don't have a device, we need one. */
  59724. if (pEngine->pDevice == NULL && engineConfig.noDevice == MA_FALSE) {
  59725. ma_device_config deviceConfig;
  59726. pEngine->pDevice = (ma_device*)ma_malloc(sizeof(*pEngine->pDevice), &pEngine->allocationCallbacks);
  59727. if (pEngine->pDevice == NULL) {
  59728. return MA_OUT_OF_MEMORY;
  59729. }
  59730. deviceConfig = ma_device_config_init(ma_device_type_playback);
  59731. deviceConfig.playback.pDeviceID = engineConfig.pPlaybackDeviceID;
  59732. deviceConfig.playback.format = ma_format_f32;
  59733. deviceConfig.playback.channels = engineConfig.channels;
  59734. deviceConfig.sampleRate = engineConfig.sampleRate;
  59735. deviceConfig.dataCallback = ma_engine_data_callback_internal;
  59736. deviceConfig.pUserData = pEngine;
  59737. deviceConfig.notificationCallback = engineConfig.notificationCallback;
  59738. deviceConfig.periodSizeInFrames = engineConfig.periodSizeInFrames;
  59739. deviceConfig.periodSizeInMilliseconds = engineConfig.periodSizeInMilliseconds;
  59740. 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. */
  59741. deviceConfig.noClip = MA_TRUE; /* The engine will do clipping itself. */
  59742. if (engineConfig.pContext == NULL) {
  59743. ma_context_config contextConfig = ma_context_config_init();
  59744. contextConfig.allocationCallbacks = pEngine->allocationCallbacks;
  59745. contextConfig.pLog = engineConfig.pLog;
  59746. /* If the engine config does not specify a log, use the resource manager's if we have one. */
  59747. #ifndef MA_NO_RESOURCE_MANAGER
  59748. {
  59749. if (contextConfig.pLog == NULL && engineConfig.pResourceManager != NULL) {
  59750. contextConfig.pLog = ma_resource_manager_get_log(engineConfig.pResourceManager);
  59751. }
  59752. }
  59753. #endif
  59754. result = ma_device_init_ex(NULL, 0, &contextConfig, &deviceConfig, pEngine->pDevice);
  59755. } else {
  59756. result = ma_device_init(engineConfig.pContext, &deviceConfig, pEngine->pDevice);
  59757. }
  59758. if (result != MA_SUCCESS) {
  59759. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  59760. pEngine->pDevice = NULL;
  59761. return result;
  59762. }
  59763. pEngine->ownsDevice = MA_TRUE;
  59764. }
  59765. /* Update the channel count and sample rate of the engine config so we can reference it below. */
  59766. if (pEngine->pDevice != NULL) {
  59767. engineConfig.channels = pEngine->pDevice->playback.channels;
  59768. engineConfig.sampleRate = pEngine->pDevice->sampleRate;
  59769. }
  59770. }
  59771. #endif
  59772. if (engineConfig.channels == 0 || engineConfig.sampleRate == 0) {
  59773. return MA_INVALID_ARGS;
  59774. }
  59775. pEngine->sampleRate = engineConfig.sampleRate;
  59776. /* The engine always uses either the log that was passed into the config, or the context's log is available. */
  59777. if (engineConfig.pLog != NULL) {
  59778. pEngine->pLog = engineConfig.pLog;
  59779. } else {
  59780. #if !defined(MA_NO_DEVICE_IO)
  59781. {
  59782. pEngine->pLog = ma_device_get_log(pEngine->pDevice);
  59783. }
  59784. #else
  59785. {
  59786. pEngine->pLog = NULL;
  59787. }
  59788. #endif
  59789. }
  59790. /* The engine is a node graph. This needs to be initialized after we have the device so we can can determine the channel count. */
  59791. nodeGraphConfig = ma_node_graph_config_init(engineConfig.channels);
  59792. nodeGraphConfig.nodeCacheCapInFrames = (engineConfig.periodSizeInFrames > 0xFFFF) ? 0xFFFF : (ma_uint16)engineConfig.periodSizeInFrames;
  59793. result = ma_node_graph_init(&nodeGraphConfig, &pEngine->allocationCallbacks, &pEngine->nodeGraph);
  59794. if (result != MA_SUCCESS) {
  59795. goto on_error_1;
  59796. }
  59797. /* We need at least one listener. */
  59798. if (engineConfig.listenerCount == 0) {
  59799. engineConfig.listenerCount = 1;
  59800. }
  59801. if (engineConfig.listenerCount > MA_ENGINE_MAX_LISTENERS) {
  59802. result = MA_INVALID_ARGS; /* Too many listeners. */
  59803. goto on_error_1;
  59804. }
  59805. for (iListener = 0; iListener < engineConfig.listenerCount; iListener += 1) {
  59806. listenerConfig = ma_spatializer_listener_config_init(ma_node_graph_get_channels(&pEngine->nodeGraph));
  59807. /*
  59808. If we're using a device, use the device's channel map for the listener. Otherwise just use
  59809. miniaudio's default channel map.
  59810. */
  59811. #if !defined(MA_NO_DEVICE_IO)
  59812. {
  59813. if (pEngine->pDevice != NULL) {
  59814. /*
  59815. Temporarily disabled. There is a subtle bug here where front-left and front-right
  59816. will be used by the device's channel map, but this is not what we want to use for
  59817. spatialization. Instead we want to use side-left and side-right. I need to figure
  59818. out a better solution for this. For now, disabling the user of device channel maps.
  59819. */
  59820. /*listenerConfig.pChannelMapOut = pEngine->pDevice->playback.channelMap;*/
  59821. }
  59822. }
  59823. #endif
  59824. result = ma_spatializer_listener_init(&listenerConfig, &pEngine->allocationCallbacks, &pEngine->listeners[iListener]); /* TODO: Change this to a pre-allocated heap. */
  59825. if (result != MA_SUCCESS) {
  59826. goto on_error_2;
  59827. }
  59828. pEngine->listenerCount += 1;
  59829. }
  59830. /* Gain smoothing for spatialized sounds. */
  59831. pEngine->gainSmoothTimeInFrames = engineConfig.gainSmoothTimeInFrames;
  59832. if (pEngine->gainSmoothTimeInFrames == 0) {
  59833. ma_uint32 gainSmoothTimeInMilliseconds = engineConfig.gainSmoothTimeInMilliseconds;
  59834. if (gainSmoothTimeInMilliseconds == 0) {
  59835. gainSmoothTimeInMilliseconds = 8;
  59836. }
  59837. pEngine->gainSmoothTimeInFrames = (gainSmoothTimeInMilliseconds * ma_engine_get_sample_rate(pEngine)) / 1000; /* 8ms by default. */
  59838. }
  59839. /* We need a resource manager. */
  59840. #ifndef MA_NO_RESOURCE_MANAGER
  59841. {
  59842. if (pEngine->pResourceManager == NULL) {
  59843. ma_resource_manager_config resourceManagerConfig;
  59844. pEngine->pResourceManager = (ma_resource_manager*)ma_malloc(sizeof(*pEngine->pResourceManager), &pEngine->allocationCallbacks);
  59845. if (pEngine->pResourceManager == NULL) {
  59846. result = MA_OUT_OF_MEMORY;
  59847. goto on_error_2;
  59848. }
  59849. resourceManagerConfig = ma_resource_manager_config_init();
  59850. resourceManagerConfig.pLog = pEngine->pLog; /* Always use the engine's log for internally-managed resource managers. */
  59851. resourceManagerConfig.decodedFormat = ma_format_f32;
  59852. resourceManagerConfig.decodedChannels = 0; /* Leave the decoded channel count as 0 so we can get good spatialization. */
  59853. resourceManagerConfig.decodedSampleRate = ma_engine_get_sample_rate(pEngine);
  59854. ma_allocation_callbacks_init_copy(&resourceManagerConfig.allocationCallbacks, &pEngine->allocationCallbacks);
  59855. resourceManagerConfig.pVFS = engineConfig.pResourceManagerVFS;
  59856. /* The Emscripten build cannot use threads. */
  59857. #if defined(MA_EMSCRIPTEN)
  59858. {
  59859. resourceManagerConfig.jobThreadCount = 0;
  59860. resourceManagerConfig.flags |= MA_RESOURCE_MANAGER_FLAG_NO_THREADING;
  59861. }
  59862. #endif
  59863. result = ma_resource_manager_init(&resourceManagerConfig, pEngine->pResourceManager);
  59864. if (result != MA_SUCCESS) {
  59865. goto on_error_3;
  59866. }
  59867. pEngine->ownsResourceManager = MA_TRUE;
  59868. }
  59869. }
  59870. #endif
  59871. /* Setup some stuff for inlined sounds. That is sounds played with ma_engine_play_sound(). */
  59872. pEngine->inlinedSoundLock = 0;
  59873. pEngine->pInlinedSoundHead = NULL;
  59874. /* Start the engine if required. This should always be the last step. */
  59875. #if !defined(MA_NO_DEVICE_IO)
  59876. {
  59877. if (engineConfig.noAutoStart == MA_FALSE && pEngine->pDevice != NULL) {
  59878. result = ma_engine_start(pEngine);
  59879. if (result != MA_SUCCESS) {
  59880. goto on_error_4; /* Failed to start the engine. */
  59881. }
  59882. }
  59883. }
  59884. #endif
  59885. return MA_SUCCESS;
  59886. #if !defined(MA_NO_DEVICE_IO)
  59887. on_error_4:
  59888. #endif
  59889. #if !defined(MA_NO_RESOURCE_MANAGER)
  59890. on_error_3:
  59891. if (pEngine->ownsResourceManager) {
  59892. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  59893. }
  59894. #endif /* MA_NO_RESOURCE_MANAGER */
  59895. on_error_2:
  59896. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  59897. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  59898. }
  59899. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  59900. on_error_1:
  59901. #if !defined(MA_NO_DEVICE_IO)
  59902. {
  59903. if (pEngine->ownsDevice) {
  59904. ma_device_uninit(pEngine->pDevice);
  59905. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  59906. }
  59907. }
  59908. #endif
  59909. return result;
  59910. }
  59911. MA_API void ma_engine_uninit(ma_engine* pEngine)
  59912. {
  59913. ma_uint32 iListener;
  59914. if (pEngine == NULL) {
  59915. return;
  59916. }
  59917. /* The device must be uninitialized before the node graph to ensure the audio thread doesn't try accessing it. */
  59918. #if !defined(MA_NO_DEVICE_IO)
  59919. {
  59920. if (pEngine->ownsDevice) {
  59921. ma_device_uninit(pEngine->pDevice);
  59922. ma_free(pEngine->pDevice, &pEngine->allocationCallbacks);
  59923. } else {
  59924. if (pEngine->pDevice != NULL) {
  59925. ma_device_stop(pEngine->pDevice);
  59926. }
  59927. }
  59928. }
  59929. #endif
  59930. /*
  59931. All inlined sounds need to be deleted. I'm going to use a lock here just to future proof in case
  59932. I want to do some kind of garbage collection later on.
  59933. */
  59934. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  59935. {
  59936. for (;;) {
  59937. ma_sound_inlined* pSoundToDelete = pEngine->pInlinedSoundHead;
  59938. if (pSoundToDelete == NULL) {
  59939. break; /* Done. */
  59940. }
  59941. pEngine->pInlinedSoundHead = pSoundToDelete->pNext;
  59942. ma_sound_uninit(&pSoundToDelete->sound);
  59943. ma_free(pSoundToDelete, &pEngine->allocationCallbacks);
  59944. }
  59945. }
  59946. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  59947. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  59948. ma_spatializer_listener_uninit(&pEngine->listeners[iListener], &pEngine->allocationCallbacks);
  59949. }
  59950. /* Make sure the node graph is uninitialized after the audio thread has been shutdown to prevent accessing of the node graph after being uninitialized. */
  59951. ma_node_graph_uninit(&pEngine->nodeGraph, &pEngine->allocationCallbacks);
  59952. /* Uninitialize the resource manager last to ensure we don't have a thread still trying to access it. */
  59953. #ifndef MA_NO_RESOURCE_MANAGER
  59954. if (pEngine->ownsResourceManager) {
  59955. ma_resource_manager_uninit(pEngine->pResourceManager);
  59956. ma_free(pEngine->pResourceManager, &pEngine->allocationCallbacks);
  59957. }
  59958. #endif
  59959. }
  59960. MA_API ma_result ma_engine_read_pcm_frames(ma_engine* pEngine, void* pFramesOut, ma_uint64 frameCount, ma_uint64* pFramesRead)
  59961. {
  59962. return ma_node_graph_read_pcm_frames(&pEngine->nodeGraph, pFramesOut, frameCount, pFramesRead);
  59963. }
  59964. MA_API ma_node_graph* ma_engine_get_node_graph(ma_engine* pEngine)
  59965. {
  59966. if (pEngine == NULL) {
  59967. return NULL;
  59968. }
  59969. return &pEngine->nodeGraph;
  59970. }
  59971. #if !defined(MA_NO_RESOURCE_MANAGER)
  59972. MA_API ma_resource_manager* ma_engine_get_resource_manager(ma_engine* pEngine)
  59973. {
  59974. if (pEngine == NULL) {
  59975. return NULL;
  59976. }
  59977. #if !defined(MA_NO_RESOURCE_MANAGER)
  59978. {
  59979. return pEngine->pResourceManager;
  59980. }
  59981. #else
  59982. {
  59983. return NULL;
  59984. }
  59985. #endif
  59986. }
  59987. #endif
  59988. MA_API ma_device* ma_engine_get_device(ma_engine* pEngine)
  59989. {
  59990. if (pEngine == NULL) {
  59991. return NULL;
  59992. }
  59993. #if !defined(MA_NO_DEVICE_IO)
  59994. {
  59995. return pEngine->pDevice;
  59996. }
  59997. #else
  59998. {
  59999. return NULL;
  60000. }
  60001. #endif
  60002. }
  60003. MA_API ma_log* ma_engine_get_log(ma_engine* pEngine)
  60004. {
  60005. if (pEngine == NULL) {
  60006. return NULL;
  60007. }
  60008. if (pEngine->pLog != NULL) {
  60009. return pEngine->pLog;
  60010. } else {
  60011. #if !defined(MA_NO_DEVICE_IO)
  60012. {
  60013. return ma_device_get_log(ma_engine_get_device(pEngine));
  60014. }
  60015. #else
  60016. {
  60017. return NULL;
  60018. }
  60019. #endif
  60020. }
  60021. }
  60022. MA_API ma_node* ma_engine_get_endpoint(ma_engine* pEngine)
  60023. {
  60024. return ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  60025. }
  60026. MA_API ma_uint64 ma_engine_get_time(const ma_engine* pEngine)
  60027. {
  60028. return ma_node_graph_get_time(&pEngine->nodeGraph);
  60029. }
  60030. MA_API ma_result ma_engine_set_time(ma_engine* pEngine, ma_uint64 globalTime)
  60031. {
  60032. return ma_node_graph_set_time(&pEngine->nodeGraph, globalTime);
  60033. }
  60034. MA_API ma_uint32 ma_engine_get_channels(const ma_engine* pEngine)
  60035. {
  60036. return ma_node_graph_get_channels(&pEngine->nodeGraph);
  60037. }
  60038. MA_API ma_uint32 ma_engine_get_sample_rate(const ma_engine* pEngine)
  60039. {
  60040. if (pEngine == NULL) {
  60041. return 0;
  60042. }
  60043. return pEngine->sampleRate;
  60044. }
  60045. MA_API ma_result ma_engine_start(ma_engine* pEngine)
  60046. {
  60047. ma_result result;
  60048. if (pEngine == NULL) {
  60049. return MA_INVALID_ARGS;
  60050. }
  60051. #if !defined(MA_NO_DEVICE_IO)
  60052. {
  60053. if (pEngine->pDevice != NULL) {
  60054. result = ma_device_start(pEngine->pDevice);
  60055. } else {
  60056. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "starting" the engine. */
  60057. }
  60058. }
  60059. #else
  60060. {
  60061. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "starting" the engine. */
  60062. }
  60063. #endif
  60064. if (result != MA_SUCCESS) {
  60065. return result;
  60066. }
  60067. return MA_SUCCESS;
  60068. }
  60069. MA_API ma_result ma_engine_stop(ma_engine* pEngine)
  60070. {
  60071. ma_result result;
  60072. if (pEngine == NULL) {
  60073. return MA_INVALID_ARGS;
  60074. }
  60075. #if !defined(MA_NO_DEVICE_IO)
  60076. {
  60077. if (pEngine->pDevice != NULL) {
  60078. result = ma_device_stop(pEngine->pDevice);
  60079. } else {
  60080. result = MA_INVALID_OPERATION; /* The engine is running without a device which means there's no real notion of "stopping" the engine. */
  60081. }
  60082. }
  60083. #else
  60084. {
  60085. result = MA_INVALID_OPERATION; /* Device IO is disabled, so there's no real notion of "stopping" the engine. */
  60086. }
  60087. #endif
  60088. if (result != MA_SUCCESS) {
  60089. return result;
  60090. }
  60091. return MA_SUCCESS;
  60092. }
  60093. MA_API ma_result ma_engine_set_volume(ma_engine* pEngine, float volume)
  60094. {
  60095. if (pEngine == NULL) {
  60096. return MA_INVALID_ARGS;
  60097. }
  60098. return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, volume);
  60099. }
  60100. MA_API ma_result ma_engine_set_gain_db(ma_engine* pEngine, float gainDB)
  60101. {
  60102. if (pEngine == NULL) {
  60103. return MA_INVALID_ARGS;
  60104. }
  60105. return ma_node_set_output_bus_volume(ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0, ma_volume_db_to_linear(gainDB));
  60106. }
  60107. MA_API ma_uint32 ma_engine_get_listener_count(const ma_engine* pEngine)
  60108. {
  60109. if (pEngine == NULL) {
  60110. return 0;
  60111. }
  60112. return pEngine->listenerCount;
  60113. }
  60114. MA_API ma_uint32 ma_engine_find_closest_listener(const ma_engine* pEngine, float absolutePosX, float absolutePosY, float absolutePosZ)
  60115. {
  60116. ma_uint32 iListener;
  60117. ma_uint32 iListenerClosest;
  60118. float closestLen2 = MA_FLT_MAX;
  60119. if (pEngine == NULL || pEngine->listenerCount == 1) {
  60120. return 0;
  60121. }
  60122. iListenerClosest = 0;
  60123. for (iListener = 0; iListener < pEngine->listenerCount; iListener += 1) {
  60124. if (ma_engine_listener_is_enabled(pEngine, iListener)) {
  60125. float len2 = ma_vec3f_len2(ma_vec3f_sub(pEngine->listeners[iListener].position, ma_vec3f_init_3f(absolutePosX, absolutePosY, absolutePosZ)));
  60126. if (closestLen2 > len2) {
  60127. closestLen2 = len2;
  60128. iListenerClosest = iListener;
  60129. }
  60130. }
  60131. }
  60132. MA_ASSERT(iListenerClosest < 255);
  60133. return iListenerClosest;
  60134. }
  60135. MA_API void ma_engine_listener_set_position(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  60136. {
  60137. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60138. return;
  60139. }
  60140. ma_spatializer_listener_set_position(&pEngine->listeners[listenerIndex], x, y, z);
  60141. }
  60142. MA_API ma_vec3f ma_engine_listener_get_position(const ma_engine* pEngine, ma_uint32 listenerIndex)
  60143. {
  60144. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60145. return ma_vec3f_init_3f(0, 0, 0);
  60146. }
  60147. return ma_spatializer_listener_get_position(&pEngine->listeners[listenerIndex]);
  60148. }
  60149. MA_API void ma_engine_listener_set_direction(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  60150. {
  60151. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60152. return;
  60153. }
  60154. ma_spatializer_listener_set_direction(&pEngine->listeners[listenerIndex], x, y, z);
  60155. }
  60156. MA_API ma_vec3f ma_engine_listener_get_direction(const ma_engine* pEngine, ma_uint32 listenerIndex)
  60157. {
  60158. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60159. return ma_vec3f_init_3f(0, 0, -1);
  60160. }
  60161. return ma_spatializer_listener_get_direction(&pEngine->listeners[listenerIndex]);
  60162. }
  60163. MA_API void ma_engine_listener_set_velocity(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  60164. {
  60165. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60166. return;
  60167. }
  60168. ma_spatializer_listener_set_velocity(&pEngine->listeners[listenerIndex], x, y, z);
  60169. }
  60170. MA_API ma_vec3f ma_engine_listener_get_velocity(const ma_engine* pEngine, ma_uint32 listenerIndex)
  60171. {
  60172. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60173. return ma_vec3f_init_3f(0, 0, 0);
  60174. }
  60175. return ma_spatializer_listener_get_velocity(&pEngine->listeners[listenerIndex]);
  60176. }
  60177. MA_API void ma_engine_listener_set_cone(ma_engine* pEngine, ma_uint32 listenerIndex, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  60178. {
  60179. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60180. return;
  60181. }
  60182. ma_spatializer_listener_set_cone(&pEngine->listeners[listenerIndex], innerAngleInRadians, outerAngleInRadians, outerGain);
  60183. }
  60184. MA_API void ma_engine_listener_get_cone(const ma_engine* pEngine, ma_uint32 listenerIndex, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  60185. {
  60186. if (pInnerAngleInRadians != NULL) {
  60187. *pInnerAngleInRadians = 0;
  60188. }
  60189. if (pOuterAngleInRadians != NULL) {
  60190. *pOuterAngleInRadians = 0;
  60191. }
  60192. if (pOuterGain != NULL) {
  60193. *pOuterGain = 0;
  60194. }
  60195. ma_spatializer_listener_get_cone(&pEngine->listeners[listenerIndex], pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  60196. }
  60197. MA_API void ma_engine_listener_set_world_up(ma_engine* pEngine, ma_uint32 listenerIndex, float x, float y, float z)
  60198. {
  60199. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60200. return;
  60201. }
  60202. ma_spatializer_listener_set_world_up(&pEngine->listeners[listenerIndex], x, y, z);
  60203. }
  60204. MA_API ma_vec3f ma_engine_listener_get_world_up(const ma_engine* pEngine, ma_uint32 listenerIndex)
  60205. {
  60206. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60207. return ma_vec3f_init_3f(0, 1, 0);
  60208. }
  60209. return ma_spatializer_listener_get_world_up(&pEngine->listeners[listenerIndex]);
  60210. }
  60211. MA_API void ma_engine_listener_set_enabled(ma_engine* pEngine, ma_uint32 listenerIndex, ma_bool32 isEnabled)
  60212. {
  60213. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60214. return;
  60215. }
  60216. ma_spatializer_listener_set_enabled(&pEngine->listeners[listenerIndex], isEnabled);
  60217. }
  60218. MA_API ma_bool32 ma_engine_listener_is_enabled(const ma_engine* pEngine, ma_uint32 listenerIndex)
  60219. {
  60220. if (pEngine == NULL || listenerIndex >= pEngine->listenerCount) {
  60221. return MA_FALSE;
  60222. }
  60223. return ma_spatializer_listener_is_enabled(&pEngine->listeners[listenerIndex]);
  60224. }
  60225. #ifndef MA_NO_RESOURCE_MANAGER
  60226. MA_API ma_result ma_engine_play_sound_ex(ma_engine* pEngine, const char* pFilePath, ma_node* pNode, ma_uint32 nodeInputBusIndex)
  60227. {
  60228. ma_result result = MA_SUCCESS;
  60229. ma_sound_inlined* pSound = NULL;
  60230. ma_sound_inlined* pNextSound = NULL;
  60231. if (pEngine == NULL || pFilePath == NULL) {
  60232. return MA_INVALID_ARGS;
  60233. }
  60234. /* Attach to the endpoint node if nothing is specicied. */
  60235. if (pNode == NULL) {
  60236. pNode = ma_node_graph_get_endpoint(&pEngine->nodeGraph);
  60237. nodeInputBusIndex = 0;
  60238. }
  60239. /*
  60240. We want to check if we can recycle an already-allocated inlined sound. Since this is just a
  60241. helper I'm not *too* concerned about performance here and I'm happy to use a lock to keep
  60242. the implementation simple. Maybe this can be optimized later if there's enough demand, but
  60243. if this function is being used it probably means the caller doesn't really care too much.
  60244. What we do is check the atEnd flag. When this is true, we can recycle the sound. Otherwise
  60245. we just keep iterating. If we reach the end without finding a sound to recycle we just
  60246. allocate a new one. This doesn't scale well for a massive number of sounds being played
  60247. simultaneously as we don't ever actually free the sound objects. Some kind of garbage
  60248. collection routine might be valuable for this which I'll think about.
  60249. */
  60250. ma_spinlock_lock(&pEngine->inlinedSoundLock);
  60251. {
  60252. ma_uint32 soundFlags = 0;
  60253. for (pNextSound = pEngine->pInlinedSoundHead; pNextSound != NULL; pNextSound = pNextSound->pNext) {
  60254. if (ma_sound_at_end(&pNextSound->sound)) {
  60255. /*
  60256. The sound is at the end which means it's available for recycling. All we need to do
  60257. is uninitialize it and reinitialize it. All we're doing is recycling memory.
  60258. */
  60259. pSound = pNextSound;
  60260. c89atomic_fetch_sub_32(&pEngine->inlinedSoundCount, 1);
  60261. break;
  60262. }
  60263. }
  60264. if (pSound != NULL) {
  60265. /*
  60266. We actually want to detach the sound from the list here. The reason is because we want the sound
  60267. to be in a consistent state at the non-recycled case to simplify the logic below.
  60268. */
  60269. if (pEngine->pInlinedSoundHead == pSound) {
  60270. pEngine->pInlinedSoundHead = pSound->pNext;
  60271. }
  60272. if (pSound->pPrev != NULL) {
  60273. pSound->pPrev->pNext = pSound->pNext;
  60274. }
  60275. if (pSound->pNext != NULL) {
  60276. pSound->pNext->pPrev = pSound->pPrev;
  60277. }
  60278. /* Now the previous sound needs to be uninitialized. */
  60279. ma_sound_uninit(&pNextSound->sound);
  60280. } else {
  60281. /* No sound available for recycling. Allocate one now. */
  60282. pSound = (ma_sound_inlined*)ma_malloc(sizeof(*pSound), &pEngine->allocationCallbacks);
  60283. }
  60284. if (pSound != NULL) { /* Safety check for the allocation above. */
  60285. /*
  60286. At this point we should have memory allocated for the inlined sound. We just need
  60287. to initialize it like a normal sound now.
  60288. */
  60289. 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. */
  60290. 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. */
  60291. soundFlags |= MA_SOUND_FLAG_NO_PITCH; /* Pitching isn't usable with inlined sounds, so disable it to save on speed. */
  60292. 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. */
  60293. result = ma_sound_init_from_file(pEngine, pFilePath, soundFlags, NULL, NULL, &pSound->sound);
  60294. if (result == MA_SUCCESS) {
  60295. /* Now attach the sound to the graph. */
  60296. result = ma_node_attach_output_bus(pSound, 0, pNode, nodeInputBusIndex);
  60297. if (result == MA_SUCCESS) {
  60298. /* 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. */
  60299. pSound->pNext = pEngine->pInlinedSoundHead;
  60300. pSound->pPrev = NULL;
  60301. pEngine->pInlinedSoundHead = pSound; /* <-- This is what attaches the sound to the list. */
  60302. if (pSound->pNext != NULL) {
  60303. pSound->pNext->pPrev = pSound;
  60304. }
  60305. } else {
  60306. ma_free(pSound, &pEngine->allocationCallbacks);
  60307. }
  60308. } else {
  60309. ma_free(pSound, &pEngine->allocationCallbacks);
  60310. }
  60311. } else {
  60312. result = MA_OUT_OF_MEMORY;
  60313. }
  60314. }
  60315. ma_spinlock_unlock(&pEngine->inlinedSoundLock);
  60316. if (result != MA_SUCCESS) {
  60317. return result;
  60318. }
  60319. /* Finally we can start playing the sound. */
  60320. result = ma_sound_start(&pSound->sound);
  60321. if (result != MA_SUCCESS) {
  60322. /* Failed to start the sound. We need to mark it for recycling and return an error. */
  60323. c89atomic_exchange_32(&pSound->sound.atEnd, MA_TRUE);
  60324. return result;
  60325. }
  60326. c89atomic_fetch_add_32(&pEngine->inlinedSoundCount, 1);
  60327. return result;
  60328. }
  60329. MA_API ma_result ma_engine_play_sound(ma_engine* pEngine, const char* pFilePath, ma_sound_group* pGroup)
  60330. {
  60331. return ma_engine_play_sound_ex(pEngine, pFilePath, pGroup, 0);
  60332. }
  60333. #endif
  60334. static ma_result ma_sound_preinit(ma_engine* pEngine, ma_sound* pSound)
  60335. {
  60336. if (pSound == NULL) {
  60337. return MA_INVALID_ARGS;
  60338. }
  60339. MA_ZERO_OBJECT(pSound);
  60340. pSound->seekTarget = MA_SEEK_TARGET_NONE;
  60341. if (pEngine == NULL) {
  60342. return MA_INVALID_ARGS;
  60343. }
  60344. return MA_SUCCESS;
  60345. }
  60346. static ma_result ma_sound_init_from_data_source_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  60347. {
  60348. ma_result result;
  60349. ma_engine_node_config engineNodeConfig;
  60350. ma_engine_node_type type; /* Will be set to ma_engine_node_type_group if no data source is specified. */
  60351. /* Do not clear pSound to zero here - that's done at a higher level with ma_sound_preinit(). */
  60352. MA_ASSERT(pEngine != NULL);
  60353. MA_ASSERT(pSound != NULL);
  60354. if (pConfig == NULL) {
  60355. return MA_INVALID_ARGS;
  60356. }
  60357. pSound->pDataSource = pConfig->pDataSource;
  60358. if (pConfig->pDataSource != NULL) {
  60359. type = ma_engine_node_type_sound;
  60360. } else {
  60361. type = ma_engine_node_type_group;
  60362. }
  60363. /*
  60364. Sounds are engine nodes. Before we can initialize this we need to determine the channel count.
  60365. If we can't do this we need to abort. It's up to the caller to ensure they're using a data
  60366. source that provides this information upfront.
  60367. */
  60368. engineNodeConfig = ma_engine_node_config_init(pEngine, type, pConfig->flags);
  60369. engineNodeConfig.channelsIn = pConfig->channelsIn;
  60370. engineNodeConfig.channelsOut = pConfig->channelsOut;
  60371. engineNodeConfig.monoExpansionMode = pConfig->monoExpansionMode;
  60372. /* If we're loading from a data source the input channel count needs to be the data source's native channel count. */
  60373. if (pConfig->pDataSource != NULL) {
  60374. result = ma_data_source_get_data_format(pConfig->pDataSource, NULL, &engineNodeConfig.channelsIn, &engineNodeConfig.sampleRate, NULL, 0);
  60375. if (result != MA_SUCCESS) {
  60376. return result; /* Failed to retrieve the channel count. */
  60377. }
  60378. if (engineNodeConfig.channelsIn == 0) {
  60379. return MA_INVALID_OPERATION; /* Invalid channel count. */
  60380. }
  60381. if (engineNodeConfig.channelsOut == MA_SOUND_SOURCE_CHANNEL_COUNT) {
  60382. engineNodeConfig.channelsOut = engineNodeConfig.channelsIn;
  60383. }
  60384. }
  60385. /* Getting here means we should have a valid channel count and we can initialize the engine node. */
  60386. result = ma_engine_node_init(&engineNodeConfig, &pEngine->allocationCallbacks, &pSound->engineNode);
  60387. if (result != MA_SUCCESS) {
  60388. return result;
  60389. }
  60390. /* If no attachment is specified, attach the sound straight to the endpoint. */
  60391. if (pConfig->pInitialAttachment == NULL) {
  60392. /* No group. Attach straight to the endpoint by default, unless the caller has requested that it not. */
  60393. if ((pConfig->flags & MA_SOUND_FLAG_NO_DEFAULT_ATTACHMENT) == 0) {
  60394. result = ma_node_attach_output_bus(pSound, 0, ma_node_graph_get_endpoint(&pEngine->nodeGraph), 0);
  60395. }
  60396. } else {
  60397. /* 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. */
  60398. result = ma_node_attach_output_bus(pSound, 0, pConfig->pInitialAttachment, pConfig->initialAttachmentInputBusIndex);
  60399. }
  60400. if (result != MA_SUCCESS) {
  60401. ma_engine_node_uninit(&pSound->engineNode, &pEngine->allocationCallbacks);
  60402. return result;
  60403. }
  60404. /* Apply initial range and looping state to the data source if applicable. */
  60405. if (pConfig->rangeBegInPCMFrames != 0 || pConfig->rangeEndInPCMFrames != ~((ma_uint64)0)) {
  60406. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->rangeBegInPCMFrames, pConfig->rangeEndInPCMFrames);
  60407. }
  60408. if (pConfig->loopPointBegInPCMFrames != 0 || pConfig->loopPointEndInPCMFrames != ~((ma_uint64)0)) {
  60409. ma_data_source_set_range_in_pcm_frames(ma_sound_get_data_source(pSound), pConfig->loopPointBegInPCMFrames, pConfig->loopPointEndInPCMFrames);
  60410. }
  60411. ma_sound_set_looping(pSound, pConfig->isLooping);
  60412. return MA_SUCCESS;
  60413. }
  60414. #ifndef MA_NO_RESOURCE_MANAGER
  60415. MA_API ma_result ma_sound_init_from_file_internal(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  60416. {
  60417. ma_result result = MA_SUCCESS;
  60418. ma_uint32 flags;
  60419. ma_sound_config config;
  60420. ma_resource_manager_pipeline_notifications notifications;
  60421. /*
  60422. The engine requires knowledge of the channel count of the underlying data source before it can
  60423. initialize the sound. Therefore, we need to make the resource manager wait until initialization
  60424. of the underlying data source to be initialized so we can get access to the channel count. To
  60425. do this, the MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT is forced.
  60426. Because we're initializing the data source before the sound, there's a chance the notification
  60427. will get triggered before this function returns. This is OK, so long as the caller is aware of
  60428. it and can avoid accessing the sound from within the notification.
  60429. */
  60430. flags = pConfig->flags | MA_RESOURCE_MANAGER_DATA_SOURCE_FLAG_WAIT_INIT;
  60431. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  60432. if (pSound->pResourceManagerDataSource == NULL) {
  60433. return MA_OUT_OF_MEMORY;
  60434. }
  60435. notifications = ma_resource_manager_pipeline_notifications_init();
  60436. notifications.done.pFence = pConfig->pDoneFence;
  60437. /*
  60438. We must wrap everything around the fence if one was specified. This ensures ma_fence_wait() does
  60439. not return prematurely before the sound has finished initializing.
  60440. */
  60441. if (notifications.done.pFence) { ma_fence_acquire(notifications.done.pFence); }
  60442. {
  60443. ma_resource_manager_data_source_config resourceManagerDataSourceConfig = ma_resource_manager_data_source_config_init();
  60444. resourceManagerDataSourceConfig.pFilePath = pConfig->pFilePath;
  60445. resourceManagerDataSourceConfig.pFilePathW = pConfig->pFilePathW;
  60446. resourceManagerDataSourceConfig.flags = flags;
  60447. resourceManagerDataSourceConfig.pNotifications = &notifications;
  60448. resourceManagerDataSourceConfig.initialSeekPointInPCMFrames = pConfig->initialSeekPointInPCMFrames;
  60449. resourceManagerDataSourceConfig.rangeBegInPCMFrames = pConfig->rangeBegInPCMFrames;
  60450. resourceManagerDataSourceConfig.rangeEndInPCMFrames = pConfig->rangeEndInPCMFrames;
  60451. resourceManagerDataSourceConfig.loopPointBegInPCMFrames = pConfig->loopPointBegInPCMFrames;
  60452. resourceManagerDataSourceConfig.loopPointEndInPCMFrames = pConfig->loopPointEndInPCMFrames;
  60453. resourceManagerDataSourceConfig.isLooping = pConfig->isLooping;
  60454. result = ma_resource_manager_data_source_init_ex(pEngine->pResourceManager, &resourceManagerDataSourceConfig, pSound->pResourceManagerDataSource);
  60455. if (result != MA_SUCCESS) {
  60456. goto done;
  60457. }
  60458. pSound->ownsDataSource = MA_TRUE; /* <-- Important. Not setting this will result in the resource manager data source never getting uninitialized. */
  60459. /* We need to use a slightly customized version of the config so we'll need to make a copy. */
  60460. config = *pConfig;
  60461. config.pFilePath = NULL;
  60462. config.pFilePathW = NULL;
  60463. config.pDataSource = pSound->pResourceManagerDataSource;
  60464. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  60465. if (result != MA_SUCCESS) {
  60466. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  60467. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  60468. MA_ZERO_OBJECT(pSound);
  60469. goto done;
  60470. }
  60471. }
  60472. done:
  60473. if (notifications.done.pFence) { ma_fence_release(notifications.done.pFence); }
  60474. return result;
  60475. }
  60476. 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)
  60477. {
  60478. ma_sound_config config = ma_sound_config_init_2(pEngine);
  60479. config.pFilePath = pFilePath;
  60480. config.flags = flags;
  60481. config.pInitialAttachment = pGroup;
  60482. config.pDoneFence = pDoneFence;
  60483. return ma_sound_init_ex(pEngine, &config, pSound);
  60484. }
  60485. 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)
  60486. {
  60487. ma_sound_config config = ma_sound_config_init_2(pEngine);
  60488. config.pFilePathW = pFilePath;
  60489. config.flags = flags;
  60490. config.pInitialAttachment = pGroup;
  60491. config.pDoneFence = pDoneFence;
  60492. return ma_sound_init_ex(pEngine, &config, pSound);
  60493. }
  60494. 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)
  60495. {
  60496. ma_result result;
  60497. ma_sound_config config;
  60498. result = ma_sound_preinit(pEngine, pSound);
  60499. if (result != MA_SUCCESS) {
  60500. return result;
  60501. }
  60502. if (pExistingSound == NULL) {
  60503. return MA_INVALID_ARGS;
  60504. }
  60505. /* Cloning only works for data buffers (not streams) that are loaded from the resource manager. */
  60506. if (pExistingSound->pResourceManagerDataSource == NULL) {
  60507. return MA_INVALID_OPERATION;
  60508. }
  60509. /*
  60510. We need to make a clone of the data source. If the data source is not a data buffer (i.e. a stream)
  60511. the this will fail.
  60512. */
  60513. pSound->pResourceManagerDataSource = (ma_resource_manager_data_source*)ma_malloc(sizeof(*pSound->pResourceManagerDataSource), &pEngine->allocationCallbacks);
  60514. if (pSound->pResourceManagerDataSource == NULL) {
  60515. return MA_OUT_OF_MEMORY;
  60516. }
  60517. result = ma_resource_manager_data_source_init_copy(pEngine->pResourceManager, pExistingSound->pResourceManagerDataSource, pSound->pResourceManagerDataSource);
  60518. if (result != MA_SUCCESS) {
  60519. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  60520. return result;
  60521. }
  60522. config = ma_sound_config_init_2(pEngine);
  60523. config.pDataSource = pSound->pResourceManagerDataSource;
  60524. config.flags = flags;
  60525. config.pInitialAttachment = pGroup;
  60526. config.monoExpansionMode = pExistingSound->engineNode.monoExpansionMode;
  60527. result = ma_sound_init_from_data_source_internal(pEngine, &config, pSound);
  60528. if (result != MA_SUCCESS) {
  60529. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  60530. ma_free(pSound->pResourceManagerDataSource, &pEngine->allocationCallbacks);
  60531. MA_ZERO_OBJECT(pSound);
  60532. return result;
  60533. }
  60534. return MA_SUCCESS;
  60535. }
  60536. #endif
  60537. 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)
  60538. {
  60539. ma_sound_config config = ma_sound_config_init_2(pEngine);
  60540. config.pDataSource = pDataSource;
  60541. config.flags = flags;
  60542. config.pInitialAttachment = pGroup;
  60543. return ma_sound_init_ex(pEngine, &config, pSound);
  60544. }
  60545. MA_API ma_result ma_sound_init_ex(ma_engine* pEngine, const ma_sound_config* pConfig, ma_sound* pSound)
  60546. {
  60547. ma_result result;
  60548. result = ma_sound_preinit(pEngine, pSound);
  60549. if (result != MA_SUCCESS) {
  60550. return result;
  60551. }
  60552. if (pConfig == NULL) {
  60553. return MA_INVALID_ARGS;
  60554. }
  60555. /* We need to load the sound differently depending on whether or not we're loading from a file. */
  60556. #ifndef MA_NO_RESOURCE_MANAGER
  60557. if (pConfig->pFilePath != NULL || pConfig->pFilePathW != NULL) {
  60558. return ma_sound_init_from_file_internal(pEngine, pConfig, pSound);
  60559. } else
  60560. #endif
  60561. {
  60562. /*
  60563. Getting here means we're not loading from a file. We may be loading from an already-initialized
  60564. data source, or none at all. If we aren't specifying any data source, we'll be initializing the
  60565. the equivalent to a group. ma_data_source_init_from_data_source_internal() will deal with this
  60566. for us, so no special treatment required here.
  60567. */
  60568. return ma_sound_init_from_data_source_internal(pEngine, pConfig, pSound);
  60569. }
  60570. }
  60571. MA_API void ma_sound_uninit(ma_sound* pSound)
  60572. {
  60573. if (pSound == NULL) {
  60574. return;
  60575. }
  60576. /*
  60577. Always uninitialize the node first. This ensures it's detached from the graph and does not return until it has done
  60578. so which makes thread safety beyond this point trivial.
  60579. */
  60580. ma_engine_node_uninit(&pSound->engineNode, &pSound->engineNode.pEngine->allocationCallbacks);
  60581. /* 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. */
  60582. #ifndef MA_NO_RESOURCE_MANAGER
  60583. if (pSound->ownsDataSource) {
  60584. ma_resource_manager_data_source_uninit(pSound->pResourceManagerDataSource);
  60585. ma_free(pSound->pResourceManagerDataSource, &pSound->engineNode.pEngine->allocationCallbacks);
  60586. pSound->pDataSource = NULL;
  60587. }
  60588. #else
  60589. MA_ASSERT(pSound->ownsDataSource == MA_FALSE);
  60590. #endif
  60591. }
  60592. MA_API ma_engine* ma_sound_get_engine(const ma_sound* pSound)
  60593. {
  60594. if (pSound == NULL) {
  60595. return NULL;
  60596. }
  60597. return pSound->engineNode.pEngine;
  60598. }
  60599. MA_API ma_data_source* ma_sound_get_data_source(const ma_sound* pSound)
  60600. {
  60601. if (pSound == NULL) {
  60602. return NULL;
  60603. }
  60604. return pSound->pDataSource;
  60605. }
  60606. MA_API ma_result ma_sound_start(ma_sound* pSound)
  60607. {
  60608. if (pSound == NULL) {
  60609. return MA_INVALID_ARGS;
  60610. }
  60611. /* If the sound is already playing, do nothing. */
  60612. if (ma_sound_is_playing(pSound)) {
  60613. return MA_SUCCESS;
  60614. }
  60615. /* If the sound is at the end it means we want to start from the start again. */
  60616. if (ma_sound_at_end(pSound)) {
  60617. ma_result result = ma_data_source_seek_to_pcm_frame(pSound->pDataSource, 0);
  60618. if (result != MA_SUCCESS && result != MA_NOT_IMPLEMENTED) {
  60619. return result; /* Failed to seek back to the start. */
  60620. }
  60621. /* Make sure we clear the end indicator. */
  60622. c89atomic_exchange_32(&pSound->atEnd, MA_FALSE);
  60623. }
  60624. /* Make sure the sound is started. If there's a start delay, the sound won't actually start until the start time is reached. */
  60625. ma_node_set_state(pSound, ma_node_state_started);
  60626. return MA_SUCCESS;
  60627. }
  60628. MA_API ma_result ma_sound_stop(ma_sound* pSound)
  60629. {
  60630. if (pSound == NULL) {
  60631. return MA_INVALID_ARGS;
  60632. }
  60633. /* This will stop the sound immediately. Use ma_sound_set_stop_time() to stop the sound at a specific time. */
  60634. ma_node_set_state(pSound, ma_node_state_stopped);
  60635. return MA_SUCCESS;
  60636. }
  60637. MA_API void ma_sound_set_volume(ma_sound* pSound, float volume)
  60638. {
  60639. if (pSound == NULL) {
  60640. return;
  60641. }
  60642. /* The volume is controlled via the output bus. */
  60643. ma_node_set_output_bus_volume(pSound, 0, volume);
  60644. }
  60645. MA_API float ma_sound_get_volume(const ma_sound* pSound)
  60646. {
  60647. if (pSound == NULL) {
  60648. return 0;
  60649. }
  60650. return ma_node_get_output_bus_volume(pSound, 0);
  60651. }
  60652. MA_API void ma_sound_set_pan(ma_sound* pSound, float pan)
  60653. {
  60654. if (pSound == NULL) {
  60655. return;
  60656. }
  60657. ma_panner_set_pan(&pSound->engineNode.panner, pan);
  60658. }
  60659. MA_API float ma_sound_get_pan(const ma_sound* pSound)
  60660. {
  60661. if (pSound == NULL) {
  60662. return 0;
  60663. }
  60664. return ma_panner_get_pan(&pSound->engineNode.panner);
  60665. }
  60666. MA_API void ma_sound_set_pan_mode(ma_sound* pSound, ma_pan_mode panMode)
  60667. {
  60668. if (pSound == NULL) {
  60669. return;
  60670. }
  60671. ma_panner_set_mode(&pSound->engineNode.panner, panMode);
  60672. }
  60673. MA_API ma_pan_mode ma_sound_get_pan_mode(const ma_sound* pSound)
  60674. {
  60675. if (pSound == NULL) {
  60676. return ma_pan_mode_balance;
  60677. }
  60678. return ma_panner_get_mode(&pSound->engineNode.panner);
  60679. }
  60680. MA_API void ma_sound_set_pitch(ma_sound* pSound, float pitch)
  60681. {
  60682. if (pSound == NULL) {
  60683. return;
  60684. }
  60685. if (pitch <= 0) {
  60686. return;
  60687. }
  60688. c89atomic_exchange_explicit_f32(&pSound->engineNode.pitch, pitch, c89atomic_memory_order_release);
  60689. }
  60690. MA_API float ma_sound_get_pitch(const ma_sound* pSound)
  60691. {
  60692. if (pSound == NULL) {
  60693. return 0;
  60694. }
  60695. return c89atomic_load_f32(&pSound->engineNode.pitch); /* Naughty const-cast for this. */
  60696. }
  60697. MA_API void ma_sound_set_spatialization_enabled(ma_sound* pSound, ma_bool32 enabled)
  60698. {
  60699. if (pSound == NULL) {
  60700. return;
  60701. }
  60702. c89atomic_exchange_explicit_32(&pSound->engineNode.isSpatializationDisabled, !enabled, c89atomic_memory_order_release);
  60703. }
  60704. MA_API ma_bool32 ma_sound_is_spatialization_enabled(const ma_sound* pSound)
  60705. {
  60706. if (pSound == NULL) {
  60707. return MA_FALSE;
  60708. }
  60709. return ma_engine_node_is_spatialization_enabled(&pSound->engineNode);
  60710. }
  60711. MA_API void ma_sound_set_pinned_listener_index(ma_sound* pSound, ma_uint32 listenerIndex)
  60712. {
  60713. if (pSound == NULL || listenerIndex >= ma_engine_get_listener_count(ma_sound_get_engine(pSound))) {
  60714. return;
  60715. }
  60716. c89atomic_exchange_explicit_32(&pSound->engineNode.pinnedListenerIndex, listenerIndex, c89atomic_memory_order_release);
  60717. }
  60718. MA_API ma_uint32 ma_sound_get_pinned_listener_index(const ma_sound* pSound)
  60719. {
  60720. if (pSound == NULL) {
  60721. return MA_LISTENER_INDEX_CLOSEST;
  60722. }
  60723. return c89atomic_load_explicit_32(&pSound->engineNode.pinnedListenerIndex, c89atomic_memory_order_acquire);
  60724. }
  60725. MA_API ma_uint32 ma_sound_get_listener_index(const ma_sound* pSound)
  60726. {
  60727. ma_uint32 listenerIndex;
  60728. if (pSound == NULL) {
  60729. return 0;
  60730. }
  60731. listenerIndex = ma_sound_get_pinned_listener_index(pSound);
  60732. if (listenerIndex == MA_LISTENER_INDEX_CLOSEST) {
  60733. ma_vec3f position = ma_sound_get_position(pSound);
  60734. return ma_engine_find_closest_listener(ma_sound_get_engine(pSound), position.x, position.y, position.z);
  60735. }
  60736. return listenerIndex;
  60737. }
  60738. MA_API ma_vec3f ma_sound_get_direction_to_listener(const ma_sound* pSound)
  60739. {
  60740. ma_vec3f relativePos;
  60741. ma_engine* pEngine;
  60742. if (pSound == NULL) {
  60743. return ma_vec3f_init_3f(0, 0, -1);
  60744. }
  60745. pEngine = ma_sound_get_engine(pSound);
  60746. if (pEngine == NULL) {
  60747. return ma_vec3f_init_3f(0, 0, -1);
  60748. }
  60749. ma_spatializer_get_relative_position_and_direction(&pSound->engineNode.spatializer, &pEngine->listeners[ma_sound_get_listener_index(pSound)], &relativePos, NULL);
  60750. return ma_vec3f_normalize(ma_vec3f_neg(relativePos));
  60751. }
  60752. MA_API void ma_sound_set_position(ma_sound* pSound, float x, float y, float z)
  60753. {
  60754. if (pSound == NULL) {
  60755. return;
  60756. }
  60757. ma_spatializer_set_position(&pSound->engineNode.spatializer, x, y, z);
  60758. }
  60759. MA_API ma_vec3f ma_sound_get_position(const ma_sound* pSound)
  60760. {
  60761. if (pSound == NULL) {
  60762. return ma_vec3f_init_3f(0, 0, 0);
  60763. }
  60764. return ma_spatializer_get_position(&pSound->engineNode.spatializer);
  60765. }
  60766. MA_API void ma_sound_set_direction(ma_sound* pSound, float x, float y, float z)
  60767. {
  60768. if (pSound == NULL) {
  60769. return;
  60770. }
  60771. ma_spatializer_set_direction(&pSound->engineNode.spatializer, x, y, z);
  60772. }
  60773. MA_API ma_vec3f ma_sound_get_direction(const ma_sound* pSound)
  60774. {
  60775. if (pSound == NULL) {
  60776. return ma_vec3f_init_3f(0, 0, 0);
  60777. }
  60778. return ma_spatializer_get_direction(&pSound->engineNode.spatializer);
  60779. }
  60780. MA_API void ma_sound_set_velocity(ma_sound* pSound, float x, float y, float z)
  60781. {
  60782. if (pSound == NULL) {
  60783. return;
  60784. }
  60785. ma_spatializer_set_velocity(&pSound->engineNode.spatializer, x, y, z);
  60786. }
  60787. MA_API ma_vec3f ma_sound_get_velocity(const ma_sound* pSound)
  60788. {
  60789. if (pSound == NULL) {
  60790. return ma_vec3f_init_3f(0, 0, 0);
  60791. }
  60792. return ma_spatializer_get_velocity(&pSound->engineNode.spatializer);
  60793. }
  60794. MA_API void ma_sound_set_attenuation_model(ma_sound* pSound, ma_attenuation_model attenuationModel)
  60795. {
  60796. if (pSound == NULL) {
  60797. return;
  60798. }
  60799. ma_spatializer_set_attenuation_model(&pSound->engineNode.spatializer, attenuationModel);
  60800. }
  60801. MA_API ma_attenuation_model ma_sound_get_attenuation_model(const ma_sound* pSound)
  60802. {
  60803. if (pSound == NULL) {
  60804. return ma_attenuation_model_none;
  60805. }
  60806. return ma_spatializer_get_attenuation_model(&pSound->engineNode.spatializer);
  60807. }
  60808. MA_API void ma_sound_set_positioning(ma_sound* pSound, ma_positioning positioning)
  60809. {
  60810. if (pSound == NULL) {
  60811. return;
  60812. }
  60813. ma_spatializer_set_positioning(&pSound->engineNode.spatializer, positioning);
  60814. }
  60815. MA_API ma_positioning ma_sound_get_positioning(const ma_sound* pSound)
  60816. {
  60817. if (pSound == NULL) {
  60818. return ma_positioning_absolute;
  60819. }
  60820. return ma_spatializer_get_positioning(&pSound->engineNode.spatializer);
  60821. }
  60822. MA_API void ma_sound_set_rolloff(ma_sound* pSound, float rolloff)
  60823. {
  60824. if (pSound == NULL) {
  60825. return;
  60826. }
  60827. ma_spatializer_set_rolloff(&pSound->engineNode.spatializer, rolloff);
  60828. }
  60829. MA_API float ma_sound_get_rolloff(const ma_sound* pSound)
  60830. {
  60831. if (pSound == NULL) {
  60832. return 0;
  60833. }
  60834. return ma_spatializer_get_rolloff(&pSound->engineNode.spatializer);
  60835. }
  60836. MA_API void ma_sound_set_min_gain(ma_sound* pSound, float minGain)
  60837. {
  60838. if (pSound == NULL) {
  60839. return;
  60840. }
  60841. ma_spatializer_set_min_gain(&pSound->engineNode.spatializer, minGain);
  60842. }
  60843. MA_API float ma_sound_get_min_gain(const ma_sound* pSound)
  60844. {
  60845. if (pSound == NULL) {
  60846. return 0;
  60847. }
  60848. return ma_spatializer_get_min_gain(&pSound->engineNode.spatializer);
  60849. }
  60850. MA_API void ma_sound_set_max_gain(ma_sound* pSound, float maxGain)
  60851. {
  60852. if (pSound == NULL) {
  60853. return;
  60854. }
  60855. ma_spatializer_set_max_gain(&pSound->engineNode.spatializer, maxGain);
  60856. }
  60857. MA_API float ma_sound_get_max_gain(const ma_sound* pSound)
  60858. {
  60859. if (pSound == NULL) {
  60860. return 0;
  60861. }
  60862. return ma_spatializer_get_max_gain(&pSound->engineNode.spatializer);
  60863. }
  60864. MA_API void ma_sound_set_min_distance(ma_sound* pSound, float minDistance)
  60865. {
  60866. if (pSound == NULL) {
  60867. return;
  60868. }
  60869. ma_spatializer_set_min_distance(&pSound->engineNode.spatializer, minDistance);
  60870. }
  60871. MA_API float ma_sound_get_min_distance(const ma_sound* pSound)
  60872. {
  60873. if (pSound == NULL) {
  60874. return 0;
  60875. }
  60876. return ma_spatializer_get_min_distance(&pSound->engineNode.spatializer);
  60877. }
  60878. MA_API void ma_sound_set_max_distance(ma_sound* pSound, float maxDistance)
  60879. {
  60880. if (pSound == NULL) {
  60881. return;
  60882. }
  60883. ma_spatializer_set_max_distance(&pSound->engineNode.spatializer, maxDistance);
  60884. }
  60885. MA_API float ma_sound_get_max_distance(const ma_sound* pSound)
  60886. {
  60887. if (pSound == NULL) {
  60888. return 0;
  60889. }
  60890. return ma_spatializer_get_max_distance(&pSound->engineNode.spatializer);
  60891. }
  60892. MA_API void ma_sound_set_cone(ma_sound* pSound, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  60893. {
  60894. if (pSound == NULL) {
  60895. return;
  60896. }
  60897. ma_spatializer_set_cone(&pSound->engineNode.spatializer, innerAngleInRadians, outerAngleInRadians, outerGain);
  60898. }
  60899. MA_API void ma_sound_get_cone(const ma_sound* pSound, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  60900. {
  60901. if (pInnerAngleInRadians != NULL) {
  60902. *pInnerAngleInRadians = 0;
  60903. }
  60904. if (pOuterAngleInRadians != NULL) {
  60905. *pOuterAngleInRadians = 0;
  60906. }
  60907. if (pOuterGain != NULL) {
  60908. *pOuterGain = 0;
  60909. }
  60910. ma_spatializer_get_cone(&pSound->engineNode.spatializer, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  60911. }
  60912. MA_API void ma_sound_set_doppler_factor(ma_sound* pSound, float dopplerFactor)
  60913. {
  60914. if (pSound == NULL) {
  60915. return;
  60916. }
  60917. ma_spatializer_set_doppler_factor(&pSound->engineNode.spatializer, dopplerFactor);
  60918. }
  60919. MA_API float ma_sound_get_doppler_factor(const ma_sound* pSound)
  60920. {
  60921. if (pSound == NULL) {
  60922. return 0;
  60923. }
  60924. return ma_spatializer_get_doppler_factor(&pSound->engineNode.spatializer);
  60925. }
  60926. MA_API void ma_sound_set_directional_attenuation_factor(ma_sound* pSound, float directionalAttenuationFactor)
  60927. {
  60928. if (pSound == NULL) {
  60929. return;
  60930. }
  60931. ma_spatializer_set_directional_attenuation_factor(&pSound->engineNode.spatializer, directionalAttenuationFactor);
  60932. }
  60933. MA_API float ma_sound_get_directional_attenuation_factor(const ma_sound* pSound)
  60934. {
  60935. if (pSound == NULL) {
  60936. return 1;
  60937. }
  60938. return ma_spatializer_get_directional_attenuation_factor(&pSound->engineNode.spatializer);
  60939. }
  60940. MA_API void ma_sound_set_fade_in_pcm_frames(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  60941. {
  60942. if (pSound == NULL) {
  60943. return;
  60944. }
  60945. ma_fader_set_fade(&pSound->engineNode.fader, volumeBeg, volumeEnd, fadeLengthInFrames);
  60946. }
  60947. MA_API void ma_sound_set_fade_in_milliseconds(ma_sound* pSound, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  60948. {
  60949. if (pSound == NULL) {
  60950. return;
  60951. }
  60952. ma_sound_set_fade_in_pcm_frames(pSound, volumeBeg, volumeEnd, (fadeLengthInMilliseconds * pSound->engineNode.fader.config.sampleRate) / 1000);
  60953. }
  60954. MA_API float ma_sound_get_current_fade_volume(ma_sound* pSound)
  60955. {
  60956. if (pSound == NULL) {
  60957. return MA_INVALID_ARGS;
  60958. }
  60959. return ma_fader_get_current_volume(&pSound->engineNode.fader);
  60960. }
  60961. MA_API void ma_sound_set_start_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  60962. {
  60963. if (pSound == NULL) {
  60964. return;
  60965. }
  60966. ma_node_set_state_time(pSound, ma_node_state_started, absoluteGlobalTimeInFrames);
  60967. }
  60968. MA_API void ma_sound_set_start_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  60969. {
  60970. if (pSound == NULL) {
  60971. return;
  60972. }
  60973. ma_sound_set_start_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  60974. }
  60975. MA_API void ma_sound_set_stop_time_in_pcm_frames(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInFrames)
  60976. {
  60977. if (pSound == NULL) {
  60978. return;
  60979. }
  60980. ma_node_set_state_time(pSound, ma_node_state_stopped, absoluteGlobalTimeInFrames);
  60981. }
  60982. MA_API void ma_sound_set_stop_time_in_milliseconds(ma_sound* pSound, ma_uint64 absoluteGlobalTimeInMilliseconds)
  60983. {
  60984. if (pSound == NULL) {
  60985. return;
  60986. }
  60987. ma_sound_set_stop_time_in_pcm_frames(pSound, absoluteGlobalTimeInMilliseconds * ma_engine_get_sample_rate(ma_sound_get_engine(pSound)) / 1000);
  60988. }
  60989. MA_API ma_bool32 ma_sound_is_playing(const ma_sound* pSound)
  60990. {
  60991. if (pSound == NULL) {
  60992. return MA_FALSE;
  60993. }
  60994. return ma_node_get_state_by_time(pSound, ma_engine_get_time(ma_sound_get_engine(pSound))) == ma_node_state_started;
  60995. }
  60996. MA_API ma_uint64 ma_sound_get_time_in_pcm_frames(const ma_sound* pSound)
  60997. {
  60998. if (pSound == NULL) {
  60999. return 0;
  61000. }
  61001. return ma_node_get_time(pSound);
  61002. }
  61003. MA_API void ma_sound_set_looping(ma_sound* pSound, ma_bool32 isLooping)
  61004. {
  61005. if (pSound == NULL) {
  61006. return;
  61007. }
  61008. /* Looping is only a valid concept if the sound is backed by a data source. */
  61009. if (pSound->pDataSource == NULL) {
  61010. return;
  61011. }
  61012. /* The looping state needs to be applied to the data source in order for any looping to actually happen. */
  61013. ma_data_source_set_looping(pSound->pDataSource, isLooping);
  61014. }
  61015. MA_API ma_bool32 ma_sound_is_looping(const ma_sound* pSound)
  61016. {
  61017. if (pSound == NULL) {
  61018. return MA_FALSE;
  61019. }
  61020. /* There is no notion of looping for sounds that are not backed by a data source. */
  61021. if (pSound->pDataSource == NULL) {
  61022. return MA_FALSE;
  61023. }
  61024. return ma_data_source_is_looping(pSound->pDataSource);
  61025. }
  61026. MA_API ma_bool32 ma_sound_at_end(const ma_sound* pSound)
  61027. {
  61028. if (pSound == NULL) {
  61029. return MA_FALSE;
  61030. }
  61031. /* There is no notion of an end of a sound if it's not backed by a data source. */
  61032. if (pSound->pDataSource == NULL) {
  61033. return MA_FALSE;
  61034. }
  61035. return c89atomic_load_32(&pSound->atEnd);
  61036. }
  61037. MA_API ma_result ma_sound_seek_to_pcm_frame(ma_sound* pSound, ma_uint64 frameIndex)
  61038. {
  61039. if (pSound == NULL) {
  61040. return MA_INVALID_ARGS;
  61041. }
  61042. /* Seeking is only valid for sounds that are backed by a data source. */
  61043. if (pSound->pDataSource == NULL) {
  61044. return MA_INVALID_OPERATION;
  61045. }
  61046. /* 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. */
  61047. c89atomic_exchange_64(&pSound->seekTarget, frameIndex);
  61048. return MA_SUCCESS;
  61049. }
  61050. 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)
  61051. {
  61052. if (pSound == NULL) {
  61053. return MA_INVALID_ARGS;
  61054. }
  61055. /* The data format is retrieved directly from the data source if the sound is backed by one. Otherwise we pull it from the node. */
  61056. if (pSound->pDataSource == NULL) {
  61057. ma_uint32 channels;
  61058. if (pFormat != NULL) {
  61059. *pFormat = ma_format_f32;
  61060. }
  61061. channels = ma_node_get_input_channels(&pSound->engineNode, 0);
  61062. if (pChannels != NULL) {
  61063. *pChannels = channels;
  61064. }
  61065. if (pSampleRate != NULL) {
  61066. *pSampleRate = pSound->engineNode.resampler.config.sampleRateIn;
  61067. }
  61068. if (pChannelMap != NULL) {
  61069. ma_channel_map_init_standard(ma_standard_channel_map_default, pChannelMap, channelMapCap, channels);
  61070. }
  61071. return MA_SUCCESS;
  61072. } else {
  61073. return ma_data_source_get_data_format(pSound->pDataSource, pFormat, pChannels, pSampleRate, pChannelMap, channelMapCap);
  61074. }
  61075. }
  61076. MA_API ma_result ma_sound_get_cursor_in_pcm_frames(ma_sound* pSound, ma_uint64* pCursor)
  61077. {
  61078. if (pSound == NULL) {
  61079. return MA_INVALID_ARGS;
  61080. }
  61081. /* The notion of a cursor is only valid for sounds that are backed by a data source. */
  61082. if (pSound->pDataSource == NULL) {
  61083. return MA_INVALID_OPERATION;
  61084. }
  61085. return ma_data_source_get_cursor_in_pcm_frames(pSound->pDataSource, pCursor);
  61086. }
  61087. MA_API ma_result ma_sound_get_length_in_pcm_frames(ma_sound* pSound, ma_uint64* pLength)
  61088. {
  61089. if (pSound == NULL) {
  61090. return MA_INVALID_ARGS;
  61091. }
  61092. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  61093. if (pSound->pDataSource == NULL) {
  61094. return MA_INVALID_OPERATION;
  61095. }
  61096. return ma_data_source_get_length_in_pcm_frames(pSound->pDataSource, pLength);
  61097. }
  61098. MA_API ma_result ma_sound_get_cursor_in_seconds(ma_sound* pSound, float* pCursor)
  61099. {
  61100. if (pSound == NULL) {
  61101. return MA_INVALID_ARGS;
  61102. }
  61103. /* The notion of a cursor is only valid for sounds that are backed by a data source. */
  61104. if (pSound->pDataSource == NULL) {
  61105. return MA_INVALID_OPERATION;
  61106. }
  61107. return ma_data_source_get_cursor_in_seconds(pSound->pDataSource, pCursor);
  61108. }
  61109. MA_API ma_result ma_sound_get_length_in_seconds(ma_sound* pSound, float* pLength)
  61110. {
  61111. if (pSound == NULL) {
  61112. return MA_INVALID_ARGS;
  61113. }
  61114. /* The notion of a sound length is only valid for sounds that are backed by a data source. */
  61115. if (pSound->pDataSource == NULL) {
  61116. return MA_INVALID_OPERATION;
  61117. }
  61118. return ma_data_source_get_length_in_seconds(pSound->pDataSource, pLength);
  61119. }
  61120. MA_API ma_result ma_sound_group_init(ma_engine* pEngine, ma_uint32 flags, ma_sound_group* pParentGroup, ma_sound_group* pGroup)
  61121. {
  61122. ma_sound_group_config config = ma_sound_group_config_init_2(pEngine);
  61123. config.flags = flags;
  61124. config.pInitialAttachment = pParentGroup;
  61125. return ma_sound_group_init_ex(pEngine, &config, pGroup);
  61126. }
  61127. MA_API ma_result ma_sound_group_init_ex(ma_engine* pEngine, const ma_sound_group_config* pConfig, ma_sound_group* pGroup)
  61128. {
  61129. ma_sound_config soundConfig;
  61130. if (pGroup == NULL) {
  61131. return MA_INVALID_ARGS;
  61132. }
  61133. MA_ZERO_OBJECT(pGroup);
  61134. if (pConfig == NULL) {
  61135. return MA_INVALID_ARGS;
  61136. }
  61137. /* A sound group is just a sound without a data source. */
  61138. soundConfig = *pConfig;
  61139. soundConfig.pFilePath = NULL;
  61140. soundConfig.pFilePathW = NULL;
  61141. soundConfig.pDataSource = NULL;
  61142. /*
  61143. Groups need to have spatialization disabled by default because I think it'll be pretty rare
  61144. that programs will want to spatialize groups (but not unheard of). Certainly it feels like
  61145. disabling this by default feels like the right option. Spatialization can be enabled with a
  61146. call to ma_sound_group_set_spatialization_enabled().
  61147. */
  61148. soundConfig.flags |= MA_SOUND_FLAG_NO_SPATIALIZATION;
  61149. return ma_sound_init_ex(pEngine, &soundConfig, pGroup);
  61150. }
  61151. MA_API void ma_sound_group_uninit(ma_sound_group* pGroup)
  61152. {
  61153. ma_sound_uninit(pGroup);
  61154. }
  61155. MA_API ma_engine* ma_sound_group_get_engine(const ma_sound_group* pGroup)
  61156. {
  61157. return ma_sound_get_engine(pGroup);
  61158. }
  61159. MA_API ma_result ma_sound_group_start(ma_sound_group* pGroup)
  61160. {
  61161. return ma_sound_start(pGroup);
  61162. }
  61163. MA_API ma_result ma_sound_group_stop(ma_sound_group* pGroup)
  61164. {
  61165. return ma_sound_stop(pGroup);
  61166. }
  61167. MA_API void ma_sound_group_set_volume(ma_sound_group* pGroup, float volume)
  61168. {
  61169. ma_sound_set_volume(pGroup, volume);
  61170. }
  61171. MA_API float ma_sound_group_get_volume(const ma_sound_group* pGroup)
  61172. {
  61173. return ma_sound_get_volume(pGroup);
  61174. }
  61175. MA_API void ma_sound_group_set_pan(ma_sound_group* pGroup, float pan)
  61176. {
  61177. ma_sound_set_pan(pGroup, pan);
  61178. }
  61179. MA_API float ma_sound_group_get_pan(const ma_sound_group* pGroup)
  61180. {
  61181. return ma_sound_get_pan(pGroup);
  61182. }
  61183. MA_API void ma_sound_group_set_pan_mode(ma_sound_group* pGroup, ma_pan_mode panMode)
  61184. {
  61185. ma_sound_set_pan_mode(pGroup, panMode);
  61186. }
  61187. MA_API ma_pan_mode ma_sound_group_get_pan_mode(const ma_sound_group* pGroup)
  61188. {
  61189. return ma_sound_get_pan_mode(pGroup);
  61190. }
  61191. MA_API void ma_sound_group_set_pitch(ma_sound_group* pGroup, float pitch)
  61192. {
  61193. ma_sound_set_pitch(pGroup, pitch);
  61194. }
  61195. MA_API float ma_sound_group_get_pitch(const ma_sound_group* pGroup)
  61196. {
  61197. return ma_sound_get_pitch(pGroup);
  61198. }
  61199. MA_API void ma_sound_group_set_spatialization_enabled(ma_sound_group* pGroup, ma_bool32 enabled)
  61200. {
  61201. ma_sound_set_spatialization_enabled(pGroup, enabled);
  61202. }
  61203. MA_API ma_bool32 ma_sound_group_is_spatialization_enabled(const ma_sound_group* pGroup)
  61204. {
  61205. return ma_sound_is_spatialization_enabled(pGroup);
  61206. }
  61207. MA_API void ma_sound_group_set_pinned_listener_index(ma_sound_group* pGroup, ma_uint32 listenerIndex)
  61208. {
  61209. ma_sound_set_pinned_listener_index(pGroup, listenerIndex);
  61210. }
  61211. MA_API ma_uint32 ma_sound_group_get_pinned_listener_index(const ma_sound_group* pGroup)
  61212. {
  61213. return ma_sound_get_pinned_listener_index(pGroup);
  61214. }
  61215. MA_API ma_uint32 ma_sound_group_get_listener_index(const ma_sound_group* pGroup)
  61216. {
  61217. return ma_sound_get_listener_index(pGroup);
  61218. }
  61219. MA_API ma_vec3f ma_sound_group_get_direction_to_listener(const ma_sound_group* pGroup)
  61220. {
  61221. return ma_sound_get_direction_to_listener(pGroup);
  61222. }
  61223. MA_API void ma_sound_group_set_position(ma_sound_group* pGroup, float x, float y, float z)
  61224. {
  61225. ma_sound_set_position(pGroup, x, y, z);
  61226. }
  61227. MA_API ma_vec3f ma_sound_group_get_position(const ma_sound_group* pGroup)
  61228. {
  61229. return ma_sound_get_position(pGroup);
  61230. }
  61231. MA_API void ma_sound_group_set_direction(ma_sound_group* pGroup, float x, float y, float z)
  61232. {
  61233. ma_sound_set_direction(pGroup, x, y, z);
  61234. }
  61235. MA_API ma_vec3f ma_sound_group_get_direction(const ma_sound_group* pGroup)
  61236. {
  61237. return ma_sound_get_direction(pGroup);
  61238. }
  61239. MA_API void ma_sound_group_set_velocity(ma_sound_group* pGroup, float x, float y, float z)
  61240. {
  61241. ma_sound_set_velocity(pGroup, x, y, z);
  61242. }
  61243. MA_API ma_vec3f ma_sound_group_get_velocity(const ma_sound_group* pGroup)
  61244. {
  61245. return ma_sound_get_velocity(pGroup);
  61246. }
  61247. MA_API void ma_sound_group_set_attenuation_model(ma_sound_group* pGroup, ma_attenuation_model attenuationModel)
  61248. {
  61249. ma_sound_set_attenuation_model(pGroup, attenuationModel);
  61250. }
  61251. MA_API ma_attenuation_model ma_sound_group_get_attenuation_model(const ma_sound_group* pGroup)
  61252. {
  61253. return ma_sound_get_attenuation_model(pGroup);
  61254. }
  61255. MA_API void ma_sound_group_set_positioning(ma_sound_group* pGroup, ma_positioning positioning)
  61256. {
  61257. ma_sound_set_positioning(pGroup, positioning);
  61258. }
  61259. MA_API ma_positioning ma_sound_group_get_positioning(const ma_sound_group* pGroup)
  61260. {
  61261. return ma_sound_get_positioning(pGroup);
  61262. }
  61263. MA_API void ma_sound_group_set_rolloff(ma_sound_group* pGroup, float rolloff)
  61264. {
  61265. ma_sound_set_rolloff(pGroup, rolloff);
  61266. }
  61267. MA_API float ma_sound_group_get_rolloff(const ma_sound_group* pGroup)
  61268. {
  61269. return ma_sound_get_rolloff(pGroup);
  61270. }
  61271. MA_API void ma_sound_group_set_min_gain(ma_sound_group* pGroup, float minGain)
  61272. {
  61273. ma_sound_set_min_gain(pGroup, minGain);
  61274. }
  61275. MA_API float ma_sound_group_get_min_gain(const ma_sound_group* pGroup)
  61276. {
  61277. return ma_sound_get_min_gain(pGroup);
  61278. }
  61279. MA_API void ma_sound_group_set_max_gain(ma_sound_group* pGroup, float maxGain)
  61280. {
  61281. ma_sound_set_max_gain(pGroup, maxGain);
  61282. }
  61283. MA_API float ma_sound_group_get_max_gain(const ma_sound_group* pGroup)
  61284. {
  61285. return ma_sound_get_max_gain(pGroup);
  61286. }
  61287. MA_API void ma_sound_group_set_min_distance(ma_sound_group* pGroup, float minDistance)
  61288. {
  61289. ma_sound_set_min_distance(pGroup, minDistance);
  61290. }
  61291. MA_API float ma_sound_group_get_min_distance(const ma_sound_group* pGroup)
  61292. {
  61293. return ma_sound_get_min_distance(pGroup);
  61294. }
  61295. MA_API void ma_sound_group_set_max_distance(ma_sound_group* pGroup, float maxDistance)
  61296. {
  61297. ma_sound_set_max_distance(pGroup, maxDistance);
  61298. }
  61299. MA_API float ma_sound_group_get_max_distance(const ma_sound_group* pGroup)
  61300. {
  61301. return ma_sound_get_max_distance(pGroup);
  61302. }
  61303. MA_API void ma_sound_group_set_cone(ma_sound_group* pGroup, float innerAngleInRadians, float outerAngleInRadians, float outerGain)
  61304. {
  61305. ma_sound_set_cone(pGroup, innerAngleInRadians, outerAngleInRadians, outerGain);
  61306. }
  61307. MA_API void ma_sound_group_get_cone(const ma_sound_group* pGroup, float* pInnerAngleInRadians, float* pOuterAngleInRadians, float* pOuterGain)
  61308. {
  61309. ma_sound_get_cone(pGroup, pInnerAngleInRadians, pOuterAngleInRadians, pOuterGain);
  61310. }
  61311. MA_API void ma_sound_group_set_doppler_factor(ma_sound_group* pGroup, float dopplerFactor)
  61312. {
  61313. ma_sound_set_doppler_factor(pGroup, dopplerFactor);
  61314. }
  61315. MA_API float ma_sound_group_get_doppler_factor(const ma_sound_group* pGroup)
  61316. {
  61317. return ma_sound_get_doppler_factor(pGroup);
  61318. }
  61319. MA_API void ma_sound_group_set_directional_attenuation_factor(ma_sound_group* pGroup, float directionalAttenuationFactor)
  61320. {
  61321. ma_sound_set_directional_attenuation_factor(pGroup, directionalAttenuationFactor);
  61322. }
  61323. MA_API float ma_sound_group_get_directional_attenuation_factor(const ma_sound_group* pGroup)
  61324. {
  61325. return ma_sound_get_directional_attenuation_factor(pGroup);
  61326. }
  61327. MA_API void ma_sound_group_set_fade_in_pcm_frames(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInFrames)
  61328. {
  61329. ma_sound_set_fade_in_pcm_frames(pGroup, volumeBeg, volumeEnd, fadeLengthInFrames);
  61330. }
  61331. MA_API void ma_sound_group_set_fade_in_milliseconds(ma_sound_group* pGroup, float volumeBeg, float volumeEnd, ma_uint64 fadeLengthInMilliseconds)
  61332. {
  61333. ma_sound_set_fade_in_milliseconds(pGroup, volumeBeg, volumeEnd, fadeLengthInMilliseconds);
  61334. }
  61335. MA_API float ma_sound_group_get_current_fade_volume(ma_sound_group* pGroup)
  61336. {
  61337. return ma_sound_get_current_fade_volume(pGroup);
  61338. }
  61339. MA_API void ma_sound_group_set_start_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  61340. {
  61341. ma_sound_set_start_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  61342. }
  61343. MA_API void ma_sound_group_set_start_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  61344. {
  61345. ma_sound_set_start_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  61346. }
  61347. MA_API void ma_sound_group_set_stop_time_in_pcm_frames(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInFrames)
  61348. {
  61349. ma_sound_set_stop_time_in_pcm_frames(pGroup, absoluteGlobalTimeInFrames);
  61350. }
  61351. MA_API void ma_sound_group_set_stop_time_in_milliseconds(ma_sound_group* pGroup, ma_uint64 absoluteGlobalTimeInMilliseconds)
  61352. {
  61353. ma_sound_set_stop_time_in_milliseconds(pGroup, absoluteGlobalTimeInMilliseconds);
  61354. }
  61355. MA_API ma_bool32 ma_sound_group_is_playing(const ma_sound_group* pGroup)
  61356. {
  61357. return ma_sound_is_playing(pGroup);
  61358. }
  61359. MA_API ma_uint64 ma_sound_group_get_time_in_pcm_frames(const ma_sound_group* pGroup)
  61360. {
  61361. return ma_sound_get_time_in_pcm_frames(pGroup);
  61362. }
  61363. #endif /* MA_NO_ENGINE */
  61364. /* END SECTION: miniaudio_engine.c */
  61365. /**************************************************************************************************************************************************************
  61366. ***************************************************************************************************************************************************************
  61367. Auto Generated
  61368. ==============
  61369. All code below is auto-generated from a tool. This mostly consists of decoding backend implementations such as dr_wav, dr_flac, etc. If you find a bug in the
  61370. code below please report the bug to the respective repository for the relevant project (probably dr_libs).
  61371. ***************************************************************************************************************************************************************
  61372. **************************************************************************************************************************************************************/
  61373. #if !defined(MA_NO_WAV) && (!defined(MA_NO_DECODING) || !defined(MA_NO_ENCODING))
  61374. #if !defined(DR_WAV_IMPLEMENTATION) && !defined(DRWAV_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  61375. /* dr_wav_c begin */
  61376. #ifndef dr_wav_c
  61377. #define dr_wav_c
  61378. #ifdef __MRC__
  61379. #pragma options opt off
  61380. #endif
  61381. #include <stdlib.h>
  61382. #include <string.h>
  61383. #include <limits.h>
  61384. #ifndef DR_WAV_NO_STDIO
  61385. #include <stdio.h>
  61386. #ifndef DR_WAV_NO_WCHAR
  61387. #include <wchar.h>
  61388. #endif
  61389. #endif
  61390. #ifndef DRWAV_ASSERT
  61391. #include <assert.h>
  61392. #define DRWAV_ASSERT(expression) assert(expression)
  61393. #endif
  61394. #ifndef DRWAV_MALLOC
  61395. #define DRWAV_MALLOC(sz) malloc((sz))
  61396. #endif
  61397. #ifndef DRWAV_REALLOC
  61398. #define DRWAV_REALLOC(p, sz) realloc((p), (sz))
  61399. #endif
  61400. #ifndef DRWAV_FREE
  61401. #define DRWAV_FREE(p) free((p))
  61402. #endif
  61403. #ifndef DRWAV_COPY_MEMORY
  61404. #define DRWAV_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  61405. #endif
  61406. #ifndef DRWAV_ZERO_MEMORY
  61407. #define DRWAV_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  61408. #endif
  61409. #ifndef DRWAV_ZERO_OBJECT
  61410. #define DRWAV_ZERO_OBJECT(p) DRWAV_ZERO_MEMORY((p), sizeof(*p))
  61411. #endif
  61412. #define drwav_countof(x) (sizeof(x) / sizeof(x[0]))
  61413. #define drwav_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  61414. #define drwav_min(a, b) (((a) < (b)) ? (a) : (b))
  61415. #define drwav_max(a, b) (((a) > (b)) ? (a) : (b))
  61416. #define drwav_clamp(x, lo, hi) (drwav_max((lo), drwav_min((hi), (x))))
  61417. #define drwav_offset_ptr(p, offset) (((drwav_uint8*)(p)) + (offset))
  61418. #define DRWAV_MAX_SIMD_VECTOR_SIZE 64
  61419. #if defined(__x86_64__) || defined(_M_X64)
  61420. #define DRWAV_X64
  61421. #elif defined(__i386) || defined(_M_IX86)
  61422. #define DRWAV_X86
  61423. #elif defined(__arm__) || defined(_M_ARM)
  61424. #define DRWAV_ARM
  61425. #endif
  61426. #ifdef _MSC_VER
  61427. #define DRWAV_INLINE __forceinline
  61428. #elif defined(__GNUC__)
  61429. #if defined(__STRICT_ANSI__)
  61430. #define DRWAV_GNUC_INLINE_HINT __inline__
  61431. #else
  61432. #define DRWAV_GNUC_INLINE_HINT inline
  61433. #endif
  61434. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  61435. #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT __attribute__((always_inline))
  61436. #else
  61437. #define DRWAV_INLINE DRWAV_GNUC_INLINE_HINT
  61438. #endif
  61439. #elif defined(__WATCOMC__)
  61440. #define DRWAV_INLINE __inline
  61441. #else
  61442. #define DRWAV_INLINE
  61443. #endif
  61444. #if defined(SIZE_MAX)
  61445. #define DRWAV_SIZE_MAX SIZE_MAX
  61446. #else
  61447. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  61448. #define DRWAV_SIZE_MAX ((drwav_uint64)0xFFFFFFFFFFFFFFFF)
  61449. #else
  61450. #define DRWAV_SIZE_MAX 0xFFFFFFFF
  61451. #endif
  61452. #endif
  61453. #if defined(_MSC_VER) && _MSC_VER >= 1400
  61454. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  61455. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  61456. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  61457. #elif defined(__clang__)
  61458. #if defined(__has_builtin)
  61459. #if __has_builtin(__builtin_bswap16)
  61460. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  61461. #endif
  61462. #if __has_builtin(__builtin_bswap32)
  61463. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  61464. #endif
  61465. #if __has_builtin(__builtin_bswap64)
  61466. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  61467. #endif
  61468. #endif
  61469. #elif defined(__GNUC__)
  61470. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  61471. #define DRWAV_HAS_BYTESWAP32_INTRINSIC
  61472. #define DRWAV_HAS_BYTESWAP64_INTRINSIC
  61473. #endif
  61474. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  61475. #define DRWAV_HAS_BYTESWAP16_INTRINSIC
  61476. #endif
  61477. #endif
  61478. DRWAV_API void drwav_version(drwav_uint32* pMajor, drwav_uint32* pMinor, drwav_uint32* pRevision)
  61479. {
  61480. if (pMajor) {
  61481. *pMajor = DRWAV_VERSION_MAJOR;
  61482. }
  61483. if (pMinor) {
  61484. *pMinor = DRWAV_VERSION_MINOR;
  61485. }
  61486. if (pRevision) {
  61487. *pRevision = DRWAV_VERSION_REVISION;
  61488. }
  61489. }
  61490. DRWAV_API const char* drwav_version_string(void)
  61491. {
  61492. return DRWAV_VERSION_STRING;
  61493. }
  61494. #ifndef DRWAV_MAX_SAMPLE_RATE
  61495. #define DRWAV_MAX_SAMPLE_RATE 384000
  61496. #endif
  61497. #ifndef DRWAV_MAX_CHANNELS
  61498. #define DRWAV_MAX_CHANNELS 256
  61499. #endif
  61500. #ifndef DRWAV_MAX_BITS_PER_SAMPLE
  61501. #define DRWAV_MAX_BITS_PER_SAMPLE 64
  61502. #endif
  61503. static const drwav_uint8 drwavGUID_W64_RIFF[16] = {0x72,0x69,0x66,0x66, 0x2E,0x91, 0xCF,0x11, 0xA5,0xD6, 0x28,0xDB,0x04,0xC1,0x00,0x00};
  61504. static const drwav_uint8 drwavGUID_W64_WAVE[16] = {0x77,0x61,0x76,0x65, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  61505. static const drwav_uint8 drwavGUID_W64_FMT [16] = {0x66,0x6D,0x74,0x20, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  61506. static const drwav_uint8 drwavGUID_W64_FACT[16] = {0x66,0x61,0x63,0x74, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  61507. static const drwav_uint8 drwavGUID_W64_DATA[16] = {0x64,0x61,0x74,0x61, 0xF3,0xAC, 0xD3,0x11, 0x8C,0xD1, 0x00,0xC0,0x4F,0x8E,0xDB,0x8A};
  61508. static DRWAV_INLINE int drwav__is_little_endian(void)
  61509. {
  61510. #if defined(DRWAV_X86) || defined(DRWAV_X64)
  61511. return DRWAV_TRUE;
  61512. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  61513. return DRWAV_TRUE;
  61514. #else
  61515. int n = 1;
  61516. return (*(char*)&n) == 1;
  61517. #endif
  61518. }
  61519. static DRWAV_INLINE void drwav_bytes_to_guid(const drwav_uint8* data, drwav_uint8* guid)
  61520. {
  61521. int i;
  61522. for (i = 0; i < 16; ++i) {
  61523. guid[i] = data[i];
  61524. }
  61525. }
  61526. static DRWAV_INLINE drwav_uint16 drwav__bswap16(drwav_uint16 n)
  61527. {
  61528. #ifdef DRWAV_HAS_BYTESWAP16_INTRINSIC
  61529. #if defined(_MSC_VER)
  61530. return _byteswap_ushort(n);
  61531. #elif defined(__GNUC__) || defined(__clang__)
  61532. return __builtin_bswap16(n);
  61533. #else
  61534. #error "This compiler does not support the byte swap intrinsic."
  61535. #endif
  61536. #else
  61537. return ((n & 0xFF00) >> 8) |
  61538. ((n & 0x00FF) << 8);
  61539. #endif
  61540. }
  61541. static DRWAV_INLINE drwav_uint32 drwav__bswap32(drwav_uint32 n)
  61542. {
  61543. #ifdef DRWAV_HAS_BYTESWAP32_INTRINSIC
  61544. #if defined(_MSC_VER)
  61545. return _byteswap_ulong(n);
  61546. #elif defined(__GNUC__) || defined(__clang__)
  61547. #if defined(DRWAV_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRWAV_64BIT)
  61548. drwav_uint32 r;
  61549. __asm__ __volatile__ (
  61550. #if defined(DRWAV_64BIT)
  61551. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  61552. #else
  61553. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  61554. #endif
  61555. );
  61556. return r;
  61557. #else
  61558. return __builtin_bswap32(n);
  61559. #endif
  61560. #else
  61561. #error "This compiler does not support the byte swap intrinsic."
  61562. #endif
  61563. #else
  61564. return ((n & 0xFF000000) >> 24) |
  61565. ((n & 0x00FF0000) >> 8) |
  61566. ((n & 0x0000FF00) << 8) |
  61567. ((n & 0x000000FF) << 24);
  61568. #endif
  61569. }
  61570. static DRWAV_INLINE drwav_uint64 drwav__bswap64(drwav_uint64 n)
  61571. {
  61572. #ifdef DRWAV_HAS_BYTESWAP64_INTRINSIC
  61573. #if defined(_MSC_VER)
  61574. return _byteswap_uint64(n);
  61575. #elif defined(__GNUC__) || defined(__clang__)
  61576. return __builtin_bswap64(n);
  61577. #else
  61578. #error "This compiler does not support the byte swap intrinsic."
  61579. #endif
  61580. #else
  61581. return ((n & ((drwav_uint64)0xFF000000 << 32)) >> 56) |
  61582. ((n & ((drwav_uint64)0x00FF0000 << 32)) >> 40) |
  61583. ((n & ((drwav_uint64)0x0000FF00 << 32)) >> 24) |
  61584. ((n & ((drwav_uint64)0x000000FF << 32)) >> 8) |
  61585. ((n & ((drwav_uint64)0xFF000000 )) << 8) |
  61586. ((n & ((drwav_uint64)0x00FF0000 )) << 24) |
  61587. ((n & ((drwav_uint64)0x0000FF00 )) << 40) |
  61588. ((n & ((drwav_uint64)0x000000FF )) << 56);
  61589. #endif
  61590. }
  61591. static DRWAV_INLINE drwav_int16 drwav__bswap_s16(drwav_int16 n)
  61592. {
  61593. return (drwav_int16)drwav__bswap16((drwav_uint16)n);
  61594. }
  61595. static DRWAV_INLINE void drwav__bswap_samples_s16(drwav_int16* pSamples, drwav_uint64 sampleCount)
  61596. {
  61597. drwav_uint64 iSample;
  61598. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  61599. pSamples[iSample] = drwav__bswap_s16(pSamples[iSample]);
  61600. }
  61601. }
  61602. static DRWAV_INLINE void drwav__bswap_s24(drwav_uint8* p)
  61603. {
  61604. drwav_uint8 t;
  61605. t = p[0];
  61606. p[0] = p[2];
  61607. p[2] = t;
  61608. }
  61609. static DRWAV_INLINE void drwav__bswap_samples_s24(drwav_uint8* pSamples, drwav_uint64 sampleCount)
  61610. {
  61611. drwav_uint64 iSample;
  61612. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  61613. drwav_uint8* pSample = pSamples + (iSample*3);
  61614. drwav__bswap_s24(pSample);
  61615. }
  61616. }
  61617. static DRWAV_INLINE drwav_int32 drwav__bswap_s32(drwav_int32 n)
  61618. {
  61619. return (drwav_int32)drwav__bswap32((drwav_uint32)n);
  61620. }
  61621. static DRWAV_INLINE void drwav__bswap_samples_s32(drwav_int32* pSamples, drwav_uint64 sampleCount)
  61622. {
  61623. drwav_uint64 iSample;
  61624. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  61625. pSamples[iSample] = drwav__bswap_s32(pSamples[iSample]);
  61626. }
  61627. }
  61628. static DRWAV_INLINE float drwav__bswap_f32(float n)
  61629. {
  61630. union {
  61631. drwav_uint32 i;
  61632. float f;
  61633. } x;
  61634. x.f = n;
  61635. x.i = drwav__bswap32(x.i);
  61636. return x.f;
  61637. }
  61638. static DRWAV_INLINE void drwav__bswap_samples_f32(float* pSamples, drwav_uint64 sampleCount)
  61639. {
  61640. drwav_uint64 iSample;
  61641. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  61642. pSamples[iSample] = drwav__bswap_f32(pSamples[iSample]);
  61643. }
  61644. }
  61645. static DRWAV_INLINE double drwav__bswap_f64(double n)
  61646. {
  61647. union {
  61648. drwav_uint64 i;
  61649. double f;
  61650. } x;
  61651. x.f = n;
  61652. x.i = drwav__bswap64(x.i);
  61653. return x.f;
  61654. }
  61655. static DRWAV_INLINE void drwav__bswap_samples_f64(double* pSamples, drwav_uint64 sampleCount)
  61656. {
  61657. drwav_uint64 iSample;
  61658. for (iSample = 0; iSample < sampleCount; iSample += 1) {
  61659. pSamples[iSample] = drwav__bswap_f64(pSamples[iSample]);
  61660. }
  61661. }
  61662. static DRWAV_INLINE void drwav__bswap_samples_pcm(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample)
  61663. {
  61664. switch (bytesPerSample)
  61665. {
  61666. case 1:
  61667. {
  61668. } break;
  61669. case 2:
  61670. {
  61671. drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount);
  61672. } break;
  61673. case 3:
  61674. {
  61675. drwav__bswap_samples_s24((drwav_uint8*)pSamples, sampleCount);
  61676. } break;
  61677. case 4:
  61678. {
  61679. drwav__bswap_samples_s32((drwav_int32*)pSamples, sampleCount);
  61680. } break;
  61681. default:
  61682. {
  61683. DRWAV_ASSERT(DRWAV_FALSE);
  61684. } break;
  61685. }
  61686. }
  61687. static DRWAV_INLINE void drwav__bswap_samples_ieee(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample)
  61688. {
  61689. switch (bytesPerSample)
  61690. {
  61691. #if 0
  61692. case 2:
  61693. {
  61694. drwav__bswap_samples_f16((drwav_float16*)pSamples, sampleCount);
  61695. } break;
  61696. #endif
  61697. case 4:
  61698. {
  61699. drwav__bswap_samples_f32((float*)pSamples, sampleCount);
  61700. } break;
  61701. case 8:
  61702. {
  61703. drwav__bswap_samples_f64((double*)pSamples, sampleCount);
  61704. } break;
  61705. default:
  61706. {
  61707. DRWAV_ASSERT(DRWAV_FALSE);
  61708. } break;
  61709. }
  61710. }
  61711. static DRWAV_INLINE void drwav__bswap_samples(void* pSamples, drwav_uint64 sampleCount, drwav_uint32 bytesPerSample, drwav_uint16 format)
  61712. {
  61713. switch (format)
  61714. {
  61715. case DR_WAVE_FORMAT_PCM:
  61716. {
  61717. drwav__bswap_samples_pcm(pSamples, sampleCount, bytesPerSample);
  61718. } break;
  61719. case DR_WAVE_FORMAT_IEEE_FLOAT:
  61720. {
  61721. drwav__bswap_samples_ieee(pSamples, sampleCount, bytesPerSample);
  61722. } break;
  61723. case DR_WAVE_FORMAT_ALAW:
  61724. case DR_WAVE_FORMAT_MULAW:
  61725. {
  61726. drwav__bswap_samples_s16((drwav_int16*)pSamples, sampleCount);
  61727. } break;
  61728. case DR_WAVE_FORMAT_ADPCM:
  61729. case DR_WAVE_FORMAT_DVI_ADPCM:
  61730. default:
  61731. {
  61732. DRWAV_ASSERT(DRWAV_FALSE);
  61733. } break;
  61734. }
  61735. }
  61736. DRWAV_PRIVATE void* drwav__malloc_default(size_t sz, void* pUserData)
  61737. {
  61738. (void)pUserData;
  61739. return DRWAV_MALLOC(sz);
  61740. }
  61741. DRWAV_PRIVATE void* drwav__realloc_default(void* p, size_t sz, void* pUserData)
  61742. {
  61743. (void)pUserData;
  61744. return DRWAV_REALLOC(p, sz);
  61745. }
  61746. DRWAV_PRIVATE void drwav__free_default(void* p, void* pUserData)
  61747. {
  61748. (void)pUserData;
  61749. DRWAV_FREE(p);
  61750. }
  61751. DRWAV_PRIVATE void* drwav__malloc_from_callbacks(size_t sz, const drwav_allocation_callbacks* pAllocationCallbacks)
  61752. {
  61753. if (pAllocationCallbacks == NULL) {
  61754. return NULL;
  61755. }
  61756. if (pAllocationCallbacks->onMalloc != NULL) {
  61757. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  61758. }
  61759. if (pAllocationCallbacks->onRealloc != NULL) {
  61760. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  61761. }
  61762. return NULL;
  61763. }
  61764. DRWAV_PRIVATE void* drwav__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drwav_allocation_callbacks* pAllocationCallbacks)
  61765. {
  61766. if (pAllocationCallbacks == NULL) {
  61767. return NULL;
  61768. }
  61769. if (pAllocationCallbacks->onRealloc != NULL) {
  61770. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  61771. }
  61772. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  61773. void* p2;
  61774. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  61775. if (p2 == NULL) {
  61776. return NULL;
  61777. }
  61778. if (p != NULL) {
  61779. DRWAV_COPY_MEMORY(p2, p, szOld);
  61780. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  61781. }
  61782. return p2;
  61783. }
  61784. return NULL;
  61785. }
  61786. DRWAV_PRIVATE void drwav__free_from_callbacks(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
  61787. {
  61788. if (p == NULL || pAllocationCallbacks == NULL) {
  61789. return;
  61790. }
  61791. if (pAllocationCallbacks->onFree != NULL) {
  61792. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  61793. }
  61794. }
  61795. DRWAV_PRIVATE drwav_allocation_callbacks drwav_copy_allocation_callbacks_or_defaults(const drwav_allocation_callbacks* pAllocationCallbacks)
  61796. {
  61797. if (pAllocationCallbacks != NULL) {
  61798. return *pAllocationCallbacks;
  61799. } else {
  61800. drwav_allocation_callbacks allocationCallbacks;
  61801. allocationCallbacks.pUserData = NULL;
  61802. allocationCallbacks.onMalloc = drwav__malloc_default;
  61803. allocationCallbacks.onRealloc = drwav__realloc_default;
  61804. allocationCallbacks.onFree = drwav__free_default;
  61805. return allocationCallbacks;
  61806. }
  61807. }
  61808. static DRWAV_INLINE drwav_bool32 drwav__is_compressed_format_tag(drwav_uint16 formatTag)
  61809. {
  61810. return
  61811. formatTag == DR_WAVE_FORMAT_ADPCM ||
  61812. formatTag == DR_WAVE_FORMAT_DVI_ADPCM;
  61813. }
  61814. DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_riff(drwav_uint64 chunkSize)
  61815. {
  61816. return (unsigned int)(chunkSize % 2);
  61817. }
  61818. DRWAV_PRIVATE unsigned int drwav__chunk_padding_size_w64(drwav_uint64 chunkSize)
  61819. {
  61820. return (unsigned int)(chunkSize % 8);
  61821. }
  61822. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  61823. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 samplesToRead, drwav_int16* pBufferOut);
  61824. DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount);
  61825. DRWAV_PRIVATE drwav_result drwav__read_chunk_header(drwav_read_proc onRead, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_chunk_header* pHeaderOut)
  61826. {
  61827. if (container == drwav_container_riff || container == drwav_container_rf64) {
  61828. drwav_uint8 sizeInBytes[4];
  61829. if (onRead(pUserData, pHeaderOut->id.fourcc, 4) != 4) {
  61830. return DRWAV_AT_END;
  61831. }
  61832. if (onRead(pUserData, sizeInBytes, 4) != 4) {
  61833. return DRWAV_INVALID_FILE;
  61834. }
  61835. pHeaderOut->sizeInBytes = drwav_bytes_to_u32(sizeInBytes);
  61836. pHeaderOut->paddingSize = drwav__chunk_padding_size_riff(pHeaderOut->sizeInBytes);
  61837. *pRunningBytesReadOut += 8;
  61838. } else {
  61839. drwav_uint8 sizeInBytes[8];
  61840. if (onRead(pUserData, pHeaderOut->id.guid, 16) != 16) {
  61841. return DRWAV_AT_END;
  61842. }
  61843. if (onRead(pUserData, sizeInBytes, 8) != 8) {
  61844. return DRWAV_INVALID_FILE;
  61845. }
  61846. pHeaderOut->sizeInBytes = drwav_bytes_to_u64(sizeInBytes) - 24;
  61847. pHeaderOut->paddingSize = drwav__chunk_padding_size_w64(pHeaderOut->sizeInBytes);
  61848. *pRunningBytesReadOut += 24;
  61849. }
  61850. return DRWAV_SUCCESS;
  61851. }
  61852. DRWAV_PRIVATE drwav_bool32 drwav__seek_forward(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  61853. {
  61854. drwav_uint64 bytesRemainingToSeek = offset;
  61855. while (bytesRemainingToSeek > 0) {
  61856. if (bytesRemainingToSeek > 0x7FFFFFFF) {
  61857. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  61858. return DRWAV_FALSE;
  61859. }
  61860. bytesRemainingToSeek -= 0x7FFFFFFF;
  61861. } else {
  61862. if (!onSeek(pUserData, (int)bytesRemainingToSeek, drwav_seek_origin_current)) {
  61863. return DRWAV_FALSE;
  61864. }
  61865. bytesRemainingToSeek = 0;
  61866. }
  61867. }
  61868. return DRWAV_TRUE;
  61869. }
  61870. DRWAV_PRIVATE drwav_bool32 drwav__seek_from_start(drwav_seek_proc onSeek, drwav_uint64 offset, void* pUserData)
  61871. {
  61872. if (offset <= 0x7FFFFFFF) {
  61873. return onSeek(pUserData, (int)offset, drwav_seek_origin_start);
  61874. }
  61875. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_start)) {
  61876. return DRWAV_FALSE;
  61877. }
  61878. offset -= 0x7FFFFFFF;
  61879. for (;;) {
  61880. if (offset <= 0x7FFFFFFF) {
  61881. return onSeek(pUserData, (int)offset, drwav_seek_origin_current);
  61882. }
  61883. if (!onSeek(pUserData, 0x7FFFFFFF, drwav_seek_origin_current)) {
  61884. return DRWAV_FALSE;
  61885. }
  61886. offset -= 0x7FFFFFFF;
  61887. }
  61888. }
  61889. DRWAV_PRIVATE drwav_bool32 drwav__read_fmt(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_container container, drwav_uint64* pRunningBytesReadOut, drwav_fmt* fmtOut)
  61890. {
  61891. drwav_chunk_header header;
  61892. drwav_uint8 fmt[16];
  61893. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  61894. return DRWAV_FALSE;
  61895. }
  61896. while (((container == drwav_container_riff || container == drwav_container_rf64) && !drwav_fourcc_equal(header.id.fourcc, "fmt ")) || (container == drwav_container_w64 && !drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT))) {
  61897. if (!drwav__seek_forward(onSeek, header.sizeInBytes + header.paddingSize, pUserData)) {
  61898. return DRWAV_FALSE;
  61899. }
  61900. *pRunningBytesReadOut += header.sizeInBytes + header.paddingSize;
  61901. if (drwav__read_chunk_header(onRead, pUserData, container, pRunningBytesReadOut, &header) != DRWAV_SUCCESS) {
  61902. return DRWAV_FALSE;
  61903. }
  61904. }
  61905. if (container == drwav_container_riff || container == drwav_container_rf64) {
  61906. if (!drwav_fourcc_equal(header.id.fourcc, "fmt ")) {
  61907. return DRWAV_FALSE;
  61908. }
  61909. } else {
  61910. if (!drwav_guid_equal(header.id.guid, drwavGUID_W64_FMT)) {
  61911. return DRWAV_FALSE;
  61912. }
  61913. }
  61914. if (onRead(pUserData, fmt, sizeof(fmt)) != sizeof(fmt)) {
  61915. return DRWAV_FALSE;
  61916. }
  61917. *pRunningBytesReadOut += sizeof(fmt);
  61918. fmtOut->formatTag = drwav_bytes_to_u16(fmt + 0);
  61919. fmtOut->channels = drwav_bytes_to_u16(fmt + 2);
  61920. fmtOut->sampleRate = drwav_bytes_to_u32(fmt + 4);
  61921. fmtOut->avgBytesPerSec = drwav_bytes_to_u32(fmt + 8);
  61922. fmtOut->blockAlign = drwav_bytes_to_u16(fmt + 12);
  61923. fmtOut->bitsPerSample = drwav_bytes_to_u16(fmt + 14);
  61924. fmtOut->extendedSize = 0;
  61925. fmtOut->validBitsPerSample = 0;
  61926. fmtOut->channelMask = 0;
  61927. DRWAV_ZERO_MEMORY(fmtOut->subFormat, sizeof(fmtOut->subFormat));
  61928. if (header.sizeInBytes > 16) {
  61929. drwav_uint8 fmt_cbSize[2];
  61930. int bytesReadSoFar = 0;
  61931. if (onRead(pUserData, fmt_cbSize, sizeof(fmt_cbSize)) != sizeof(fmt_cbSize)) {
  61932. return DRWAV_FALSE;
  61933. }
  61934. *pRunningBytesReadOut += sizeof(fmt_cbSize);
  61935. bytesReadSoFar = 18;
  61936. fmtOut->extendedSize = drwav_bytes_to_u16(fmt_cbSize);
  61937. if (fmtOut->extendedSize > 0) {
  61938. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  61939. if (fmtOut->extendedSize != 22) {
  61940. return DRWAV_FALSE;
  61941. }
  61942. }
  61943. if (fmtOut->formatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  61944. drwav_uint8 fmtext[22];
  61945. if (onRead(pUserData, fmtext, fmtOut->extendedSize) != fmtOut->extendedSize) {
  61946. return DRWAV_FALSE;
  61947. }
  61948. fmtOut->validBitsPerSample = drwav_bytes_to_u16(fmtext + 0);
  61949. fmtOut->channelMask = drwav_bytes_to_u32(fmtext + 2);
  61950. drwav_bytes_to_guid(fmtext + 6, fmtOut->subFormat);
  61951. } else {
  61952. if (!onSeek(pUserData, fmtOut->extendedSize, drwav_seek_origin_current)) {
  61953. return DRWAV_FALSE;
  61954. }
  61955. }
  61956. *pRunningBytesReadOut += fmtOut->extendedSize;
  61957. bytesReadSoFar += fmtOut->extendedSize;
  61958. }
  61959. if (!onSeek(pUserData, (int)(header.sizeInBytes - bytesReadSoFar), drwav_seek_origin_current)) {
  61960. return DRWAV_FALSE;
  61961. }
  61962. *pRunningBytesReadOut += (header.sizeInBytes - bytesReadSoFar);
  61963. }
  61964. if (header.paddingSize > 0) {
  61965. if (!onSeek(pUserData, header.paddingSize, drwav_seek_origin_current)) {
  61966. return DRWAV_FALSE;
  61967. }
  61968. *pRunningBytesReadOut += header.paddingSize;
  61969. }
  61970. return DRWAV_TRUE;
  61971. }
  61972. DRWAV_PRIVATE size_t drwav__on_read(drwav_read_proc onRead, void* pUserData, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
  61973. {
  61974. size_t bytesRead;
  61975. DRWAV_ASSERT(onRead != NULL);
  61976. DRWAV_ASSERT(pCursor != NULL);
  61977. bytesRead = onRead(pUserData, pBufferOut, bytesToRead);
  61978. *pCursor += bytesRead;
  61979. return bytesRead;
  61980. }
  61981. #if 0
  61982. DRWAV_PRIVATE drwav_bool32 drwav__on_seek(drwav_seek_proc onSeek, void* pUserData, int offset, drwav_seek_origin origin, drwav_uint64* pCursor)
  61983. {
  61984. DRWAV_ASSERT(onSeek != NULL);
  61985. DRWAV_ASSERT(pCursor != NULL);
  61986. if (!onSeek(pUserData, offset, origin)) {
  61987. return DRWAV_FALSE;
  61988. }
  61989. if (origin == drwav_seek_origin_start) {
  61990. *pCursor = offset;
  61991. } else {
  61992. *pCursor += offset;
  61993. }
  61994. return DRWAV_TRUE;
  61995. }
  61996. #endif
  61997. #define DRWAV_SMPL_BYTES 36
  61998. #define DRWAV_SMPL_LOOP_BYTES 24
  61999. #define DRWAV_INST_BYTES 7
  62000. #define DRWAV_ACID_BYTES 24
  62001. #define DRWAV_CUE_BYTES 4
  62002. #define DRWAV_BEXT_BYTES 602
  62003. #define DRWAV_BEXT_DESCRIPTION_BYTES 256
  62004. #define DRWAV_BEXT_ORIGINATOR_NAME_BYTES 32
  62005. #define DRWAV_BEXT_ORIGINATOR_REF_BYTES 32
  62006. #define DRWAV_BEXT_RESERVED_BYTES 180
  62007. #define DRWAV_BEXT_UMID_BYTES 64
  62008. #define DRWAV_CUE_POINT_BYTES 24
  62009. #define DRWAV_LIST_LABEL_OR_NOTE_BYTES 4
  62010. #define DRWAV_LIST_LABELLED_TEXT_BYTES 20
  62011. #define DRWAV_METADATA_ALIGNMENT 8
  62012. typedef enum
  62013. {
  62014. drwav__metadata_parser_stage_count,
  62015. drwav__metadata_parser_stage_read
  62016. } drwav__metadata_parser_stage;
  62017. typedef struct
  62018. {
  62019. drwav_read_proc onRead;
  62020. drwav_seek_proc onSeek;
  62021. void *pReadSeekUserData;
  62022. drwav__metadata_parser_stage stage;
  62023. drwav_metadata *pMetadata;
  62024. drwav_uint32 metadataCount;
  62025. drwav_uint8 *pData;
  62026. drwav_uint8 *pDataCursor;
  62027. drwav_uint64 metadataCursor;
  62028. drwav_uint64 extraCapacity;
  62029. } drwav__metadata_parser;
  62030. DRWAV_PRIVATE size_t drwav__metadata_memory_capacity(drwav__metadata_parser* pParser)
  62031. {
  62032. drwav_uint64 cap = sizeof(drwav_metadata) * (drwav_uint64)pParser->metadataCount + pParser->extraCapacity;
  62033. if (cap > DRWAV_SIZE_MAX) {
  62034. return 0;
  62035. }
  62036. return (size_t)cap;
  62037. }
  62038. DRWAV_PRIVATE drwav_uint8* drwav__metadata_get_memory(drwav__metadata_parser* pParser, size_t size, size_t align)
  62039. {
  62040. drwav_uint8* pResult;
  62041. if (align) {
  62042. drwav_uintptr modulo = (drwav_uintptr)pParser->pDataCursor % align;
  62043. if (modulo != 0) {
  62044. pParser->pDataCursor += align - modulo;
  62045. }
  62046. }
  62047. pResult = pParser->pDataCursor;
  62048. DRWAV_ASSERT((pResult + size) <= (pParser->pData + drwav__metadata_memory_capacity(pParser)));
  62049. pParser->pDataCursor += size;
  62050. return pResult;
  62051. }
  62052. DRWAV_PRIVATE void drwav__metadata_request_extra_memory_for_stage_2(drwav__metadata_parser* pParser, size_t bytes, size_t align)
  62053. {
  62054. size_t extra = bytes + (align ? (align - 1) : 0);
  62055. pParser->extraCapacity += extra;
  62056. }
  62057. DRWAV_PRIVATE drwav_result drwav__metadata_alloc(drwav__metadata_parser* pParser, drwav_allocation_callbacks* pAllocationCallbacks)
  62058. {
  62059. if (pParser->extraCapacity != 0 || pParser->metadataCount != 0) {
  62060. pAllocationCallbacks->onFree(pParser->pData, pAllocationCallbacks->pUserData);
  62061. pParser->pData = (drwav_uint8*)pAllocationCallbacks->onMalloc(drwav__metadata_memory_capacity(pParser), pAllocationCallbacks->pUserData);
  62062. pParser->pDataCursor = pParser->pData;
  62063. if (pParser->pData == NULL) {
  62064. return DRWAV_OUT_OF_MEMORY;
  62065. }
  62066. pParser->pMetadata = (drwav_metadata*)drwav__metadata_get_memory(pParser, sizeof(drwav_metadata) * pParser->metadataCount, 1);
  62067. pParser->metadataCursor = 0;
  62068. }
  62069. return DRWAV_SUCCESS;
  62070. }
  62071. DRWAV_PRIVATE size_t drwav__metadata_parser_read(drwav__metadata_parser* pParser, void* pBufferOut, size_t bytesToRead, drwav_uint64* pCursor)
  62072. {
  62073. if (pCursor != NULL) {
  62074. return drwav__on_read(pParser->onRead, pParser->pReadSeekUserData, pBufferOut, bytesToRead, pCursor);
  62075. } else {
  62076. return pParser->onRead(pParser->pReadSeekUserData, pBufferOut, bytesToRead);
  62077. }
  62078. }
  62079. DRWAV_PRIVATE drwav_uint64 drwav__read_smpl_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
  62080. {
  62081. drwav_uint8 smplHeaderData[DRWAV_SMPL_BYTES];
  62082. drwav_uint64 totalBytesRead = 0;
  62083. size_t bytesJustRead = drwav__metadata_parser_read(pParser, smplHeaderData, sizeof(smplHeaderData), &totalBytesRead);
  62084. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62085. DRWAV_ASSERT(pChunkHeader != NULL);
  62086. if (bytesJustRead == sizeof(smplHeaderData)) {
  62087. drwav_uint32 iSampleLoop;
  62088. pMetadata->type = drwav_metadata_type_smpl;
  62089. pMetadata->data.smpl.manufacturerId = drwav_bytes_to_u32(smplHeaderData + 0);
  62090. pMetadata->data.smpl.productId = drwav_bytes_to_u32(smplHeaderData + 4);
  62091. pMetadata->data.smpl.samplePeriodNanoseconds = drwav_bytes_to_u32(smplHeaderData + 8);
  62092. pMetadata->data.smpl.midiUnityNote = drwav_bytes_to_u32(smplHeaderData + 12);
  62093. pMetadata->data.smpl.midiPitchFraction = drwav_bytes_to_u32(smplHeaderData + 16);
  62094. pMetadata->data.smpl.smpteFormat = drwav_bytes_to_u32(smplHeaderData + 20);
  62095. pMetadata->data.smpl.smpteOffset = drwav_bytes_to_u32(smplHeaderData + 24);
  62096. pMetadata->data.smpl.sampleLoopCount = drwav_bytes_to_u32(smplHeaderData + 28);
  62097. pMetadata->data.smpl.samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(smplHeaderData + 32);
  62098. if (pMetadata->data.smpl.sampleLoopCount == (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES) {
  62099. pMetadata->data.smpl.pLoops = (drwav_smpl_loop*)drwav__metadata_get_memory(pParser, sizeof(drwav_smpl_loop) * pMetadata->data.smpl.sampleLoopCount, DRWAV_METADATA_ALIGNMENT);
  62100. for (iSampleLoop = 0; iSampleLoop < pMetadata->data.smpl.sampleLoopCount; ++iSampleLoop) {
  62101. drwav_uint8 smplLoopData[DRWAV_SMPL_LOOP_BYTES];
  62102. bytesJustRead = drwav__metadata_parser_read(pParser, smplLoopData, sizeof(smplLoopData), &totalBytesRead);
  62103. if (bytesJustRead == sizeof(smplLoopData)) {
  62104. pMetadata->data.smpl.pLoops[iSampleLoop].cuePointId = drwav_bytes_to_u32(smplLoopData + 0);
  62105. pMetadata->data.smpl.pLoops[iSampleLoop].type = drwav_bytes_to_u32(smplLoopData + 4);
  62106. pMetadata->data.smpl.pLoops[iSampleLoop].firstSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 8);
  62107. pMetadata->data.smpl.pLoops[iSampleLoop].lastSampleByteOffset = drwav_bytes_to_u32(smplLoopData + 12);
  62108. pMetadata->data.smpl.pLoops[iSampleLoop].sampleFraction = drwav_bytes_to_u32(smplLoopData + 16);
  62109. pMetadata->data.smpl.pLoops[iSampleLoop].playCount = drwav_bytes_to_u32(smplLoopData + 20);
  62110. } else {
  62111. break;
  62112. }
  62113. }
  62114. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  62115. pMetadata->data.smpl.pSamplerSpecificData = drwav__metadata_get_memory(pParser, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, 1);
  62116. DRWAV_ASSERT(pMetadata->data.smpl.pSamplerSpecificData != NULL);
  62117. drwav__metadata_parser_read(pParser, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes, &totalBytesRead);
  62118. }
  62119. }
  62120. }
  62121. return totalBytesRead;
  62122. }
  62123. DRWAV_PRIVATE drwav_uint64 drwav__read_cue_to_metadata_obj(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata* pMetadata)
  62124. {
  62125. drwav_uint8 cueHeaderSectionData[DRWAV_CUE_BYTES];
  62126. drwav_uint64 totalBytesRead = 0;
  62127. size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueHeaderSectionData, sizeof(cueHeaderSectionData), &totalBytesRead);
  62128. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62129. if (bytesJustRead == sizeof(cueHeaderSectionData)) {
  62130. pMetadata->type = drwav_metadata_type_cue;
  62131. pMetadata->data.cue.cuePointCount = drwav_bytes_to_u32(cueHeaderSectionData);
  62132. if (pMetadata->data.cue.cuePointCount == (pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES) {
  62133. pMetadata->data.cue.pCuePoints = (drwav_cue_point*)drwav__metadata_get_memory(pParser, sizeof(drwav_cue_point) * pMetadata->data.cue.cuePointCount, DRWAV_METADATA_ALIGNMENT);
  62134. DRWAV_ASSERT(pMetadata->data.cue.pCuePoints != NULL);
  62135. if (pMetadata->data.cue.cuePointCount > 0) {
  62136. drwav_uint32 iCuePoint;
  62137. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  62138. drwav_uint8 cuePointData[DRWAV_CUE_POINT_BYTES];
  62139. bytesJustRead = drwav__metadata_parser_read(pParser, cuePointData, sizeof(cuePointData), &totalBytesRead);
  62140. if (bytesJustRead == sizeof(cuePointData)) {
  62141. pMetadata->data.cue.pCuePoints[iCuePoint].id = drwav_bytes_to_u32(cuePointData + 0);
  62142. pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition = drwav_bytes_to_u32(cuePointData + 4);
  62143. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[0] = cuePointData[8];
  62144. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[1] = cuePointData[9];
  62145. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[2] = cuePointData[10];
  62146. pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId[3] = cuePointData[11];
  62147. pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart = drwav_bytes_to_u32(cuePointData + 12);
  62148. pMetadata->data.cue.pCuePoints[iCuePoint].blockStart = drwav_bytes_to_u32(cuePointData + 16);
  62149. pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset = drwav_bytes_to_u32(cuePointData + 20);
  62150. } else {
  62151. break;
  62152. }
  62153. }
  62154. }
  62155. }
  62156. }
  62157. return totalBytesRead;
  62158. }
  62159. DRWAV_PRIVATE drwav_uint64 drwav__read_inst_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
  62160. {
  62161. drwav_uint8 instData[DRWAV_INST_BYTES];
  62162. drwav_uint64 bytesRead = drwav__metadata_parser_read(pParser, instData, sizeof(instData), NULL);
  62163. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62164. if (bytesRead == sizeof(instData)) {
  62165. pMetadata->type = drwav_metadata_type_inst;
  62166. pMetadata->data.inst.midiUnityNote = (drwav_int8)instData[0];
  62167. pMetadata->data.inst.fineTuneCents = (drwav_int8)instData[1];
  62168. pMetadata->data.inst.gainDecibels = (drwav_int8)instData[2];
  62169. pMetadata->data.inst.lowNote = (drwav_int8)instData[3];
  62170. pMetadata->data.inst.highNote = (drwav_int8)instData[4];
  62171. pMetadata->data.inst.lowVelocity = (drwav_int8)instData[5];
  62172. pMetadata->data.inst.highVelocity = (drwav_int8)instData[6];
  62173. }
  62174. return bytesRead;
  62175. }
  62176. DRWAV_PRIVATE drwav_uint64 drwav__read_acid_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata)
  62177. {
  62178. drwav_uint8 acidData[DRWAV_ACID_BYTES];
  62179. drwav_uint64 bytesRead = drwav__metadata_parser_read(pParser, acidData, sizeof(acidData), NULL);
  62180. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62181. if (bytesRead == sizeof(acidData)) {
  62182. pMetadata->type = drwav_metadata_type_acid;
  62183. pMetadata->data.acid.flags = drwav_bytes_to_u32(acidData + 0);
  62184. pMetadata->data.acid.midiUnityNote = drwav_bytes_to_u16(acidData + 4);
  62185. pMetadata->data.acid.reserved1 = drwav_bytes_to_u16(acidData + 6);
  62186. pMetadata->data.acid.reserved2 = drwav_bytes_to_f32(acidData + 8);
  62187. pMetadata->data.acid.numBeats = drwav_bytes_to_u32(acidData + 12);
  62188. pMetadata->data.acid.meterDenominator = drwav_bytes_to_u16(acidData + 16);
  62189. pMetadata->data.acid.meterNumerator = drwav_bytes_to_u16(acidData + 18);
  62190. pMetadata->data.acid.tempo = drwav_bytes_to_f32(acidData + 20);
  62191. }
  62192. return bytesRead;
  62193. }
  62194. DRWAV_PRIVATE size_t drwav__strlen(const char* str)
  62195. {
  62196. size_t result = 0;
  62197. while (*str++) {
  62198. result += 1;
  62199. }
  62200. return result;
  62201. }
  62202. DRWAV_PRIVATE size_t drwav__strlen_clamped(const char* str, size_t maxToRead)
  62203. {
  62204. size_t result = 0;
  62205. while (*str++ && result < maxToRead) {
  62206. result += 1;
  62207. }
  62208. return result;
  62209. }
  62210. DRWAV_PRIVATE char* drwav__metadata_copy_string(drwav__metadata_parser* pParser, const char* str, size_t maxToRead)
  62211. {
  62212. size_t len = drwav__strlen_clamped(str, maxToRead);
  62213. if (len) {
  62214. char* result = (char*)drwav__metadata_get_memory(pParser, len + 1, 1);
  62215. DRWAV_ASSERT(result != NULL);
  62216. DRWAV_COPY_MEMORY(result, str, len);
  62217. result[len] = '\0';
  62218. return result;
  62219. } else {
  62220. return NULL;
  62221. }
  62222. }
  62223. typedef struct
  62224. {
  62225. const void* pBuffer;
  62226. size_t sizeInBytes;
  62227. size_t cursor;
  62228. } drwav_buffer_reader;
  62229. DRWAV_PRIVATE drwav_result drwav_buffer_reader_init(const void* pBuffer, size_t sizeInBytes, drwav_buffer_reader* pReader)
  62230. {
  62231. DRWAV_ASSERT(pBuffer != NULL);
  62232. DRWAV_ASSERT(pReader != NULL);
  62233. DRWAV_ZERO_OBJECT(pReader);
  62234. pReader->pBuffer = pBuffer;
  62235. pReader->sizeInBytes = sizeInBytes;
  62236. pReader->cursor = 0;
  62237. return DRWAV_SUCCESS;
  62238. }
  62239. DRWAV_PRIVATE const void* drwav_buffer_reader_ptr(const drwav_buffer_reader* pReader)
  62240. {
  62241. DRWAV_ASSERT(pReader != NULL);
  62242. return drwav_offset_ptr(pReader->pBuffer, pReader->cursor);
  62243. }
  62244. DRWAV_PRIVATE drwav_result drwav_buffer_reader_seek(drwav_buffer_reader* pReader, size_t bytesToSeek)
  62245. {
  62246. DRWAV_ASSERT(pReader != NULL);
  62247. if (pReader->cursor + bytesToSeek > pReader->sizeInBytes) {
  62248. return DRWAV_BAD_SEEK;
  62249. }
  62250. pReader->cursor += bytesToSeek;
  62251. return DRWAV_SUCCESS;
  62252. }
  62253. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read(drwav_buffer_reader* pReader, void* pDst, size_t bytesToRead, size_t* pBytesRead)
  62254. {
  62255. drwav_result result = DRWAV_SUCCESS;
  62256. size_t bytesRemaining;
  62257. DRWAV_ASSERT(pReader != NULL);
  62258. if (pBytesRead != NULL) {
  62259. *pBytesRead = 0;
  62260. }
  62261. bytesRemaining = (pReader->sizeInBytes - pReader->cursor);
  62262. if (bytesToRead > bytesRemaining) {
  62263. bytesToRead = bytesRemaining;
  62264. }
  62265. if (pDst == NULL) {
  62266. result = drwav_buffer_reader_seek(pReader, bytesToRead);
  62267. } else {
  62268. DRWAV_COPY_MEMORY(pDst, drwav_buffer_reader_ptr(pReader), bytesToRead);
  62269. pReader->cursor += bytesToRead;
  62270. }
  62271. DRWAV_ASSERT(pReader->cursor <= pReader->sizeInBytes);
  62272. if (result == DRWAV_SUCCESS) {
  62273. if (pBytesRead != NULL) {
  62274. *pBytesRead = bytesToRead;
  62275. }
  62276. }
  62277. return DRWAV_SUCCESS;
  62278. }
  62279. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u16(drwav_buffer_reader* pReader, drwav_uint16* pDst)
  62280. {
  62281. drwav_result result;
  62282. size_t bytesRead;
  62283. drwav_uint8 data[2];
  62284. DRWAV_ASSERT(pReader != NULL);
  62285. DRWAV_ASSERT(pDst != NULL);
  62286. *pDst = 0;
  62287. result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  62288. if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
  62289. return result;
  62290. }
  62291. *pDst = drwav_bytes_to_u16(data);
  62292. return DRWAV_SUCCESS;
  62293. }
  62294. DRWAV_PRIVATE drwav_result drwav_buffer_reader_read_u32(drwav_buffer_reader* pReader, drwav_uint32* pDst)
  62295. {
  62296. drwav_result result;
  62297. size_t bytesRead;
  62298. drwav_uint8 data[4];
  62299. DRWAV_ASSERT(pReader != NULL);
  62300. DRWAV_ASSERT(pDst != NULL);
  62301. *pDst = 0;
  62302. result = drwav_buffer_reader_read(pReader, data, sizeof(*pDst), &bytesRead);
  62303. if (result != DRWAV_SUCCESS || bytesRead != sizeof(*pDst)) {
  62304. return result;
  62305. }
  62306. *pDst = drwav_bytes_to_u32(data);
  62307. return DRWAV_SUCCESS;
  62308. }
  62309. DRWAV_PRIVATE drwav_uint64 drwav__read_bext_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
  62310. {
  62311. drwav_uint8 bextData[DRWAV_BEXT_BYTES];
  62312. size_t bytesRead = drwav__metadata_parser_read(pParser, bextData, sizeof(bextData), NULL);
  62313. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62314. if (bytesRead == sizeof(bextData)) {
  62315. drwav_buffer_reader reader;
  62316. drwav_uint32 timeReferenceLow;
  62317. drwav_uint32 timeReferenceHigh;
  62318. size_t extraBytes;
  62319. pMetadata->type = drwav_metadata_type_bext;
  62320. if (drwav_buffer_reader_init(bextData, bytesRead, &reader) == DRWAV_SUCCESS) {
  62321. pMetadata->data.bext.pDescription = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_DESCRIPTION_BYTES);
  62322. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_DESCRIPTION_BYTES);
  62323. pMetadata->data.bext.pOriginatorName = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  62324. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  62325. pMetadata->data.bext.pOriginatorReference = drwav__metadata_copy_string(pParser, (const char*)drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  62326. drwav_buffer_reader_seek(&reader, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  62327. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate), NULL);
  62328. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime), NULL);
  62329. drwav_buffer_reader_read_u32(&reader, &timeReferenceLow);
  62330. drwav_buffer_reader_read_u32(&reader, &timeReferenceHigh);
  62331. pMetadata->data.bext.timeReference = ((drwav_uint64)timeReferenceHigh << 32) + timeReferenceLow;
  62332. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.version);
  62333. pMetadata->data.bext.pUMID = drwav__metadata_get_memory(pParser, DRWAV_BEXT_UMID_BYTES, 1);
  62334. drwav_buffer_reader_read(&reader, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES, NULL);
  62335. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessValue);
  62336. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.loudnessRange);
  62337. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxTruePeakLevel);
  62338. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxMomentaryLoudness);
  62339. drwav_buffer_reader_read_u16(&reader, &pMetadata->data.bext.maxShortTermLoudness);
  62340. DRWAV_ASSERT((drwav_offset_ptr(drwav_buffer_reader_ptr(&reader), DRWAV_BEXT_RESERVED_BYTES)) == (bextData + DRWAV_BEXT_BYTES));
  62341. extraBytes = (size_t)(chunkSize - DRWAV_BEXT_BYTES);
  62342. if (extraBytes > 0) {
  62343. pMetadata->data.bext.pCodingHistory = (char*)drwav__metadata_get_memory(pParser, extraBytes + 1, 1);
  62344. DRWAV_ASSERT(pMetadata->data.bext.pCodingHistory != NULL);
  62345. bytesRead += drwav__metadata_parser_read(pParser, pMetadata->data.bext.pCodingHistory, extraBytes, NULL);
  62346. pMetadata->data.bext.codingHistorySize = (drwav_uint32)drwav__strlen(pMetadata->data.bext.pCodingHistory);
  62347. } else {
  62348. pMetadata->data.bext.pCodingHistory = NULL;
  62349. pMetadata->data.bext.codingHistorySize = 0;
  62350. }
  62351. }
  62352. }
  62353. return bytesRead;
  62354. }
  62355. DRWAV_PRIVATE drwav_uint64 drwav__read_list_label_or_note_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize, drwav_metadata_type type)
  62356. {
  62357. drwav_uint8 cueIDBuffer[DRWAV_LIST_LABEL_OR_NOTE_BYTES];
  62358. drwav_uint64 totalBytesRead = 0;
  62359. size_t bytesJustRead = drwav__metadata_parser_read(pParser, cueIDBuffer, sizeof(cueIDBuffer), &totalBytesRead);
  62360. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62361. if (bytesJustRead == sizeof(cueIDBuffer)) {
  62362. drwav_uint32 sizeIncludingNullTerminator;
  62363. pMetadata->type = type;
  62364. pMetadata->data.labelOrNote.cuePointId = drwav_bytes_to_u32(cueIDBuffer);
  62365. sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  62366. if (sizeIncludingNullTerminator > 0) {
  62367. pMetadata->data.labelOrNote.stringLength = sizeIncludingNullTerminator - 1;
  62368. pMetadata->data.labelOrNote.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  62369. DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  62370. drwav__metadata_parser_read(pParser, pMetadata->data.labelOrNote.pString, sizeIncludingNullTerminator, &totalBytesRead);
  62371. } else {
  62372. pMetadata->data.labelOrNote.stringLength = 0;
  62373. pMetadata->data.labelOrNote.pString = NULL;
  62374. }
  62375. }
  62376. return totalBytesRead;
  62377. }
  62378. DRWAV_PRIVATE drwav_uint64 drwav__read_list_labelled_cue_region_to_metadata_obj(drwav__metadata_parser* pParser, drwav_metadata* pMetadata, drwav_uint64 chunkSize)
  62379. {
  62380. drwav_uint8 buffer[DRWAV_LIST_LABELLED_TEXT_BYTES];
  62381. drwav_uint64 totalBytesRead = 0;
  62382. size_t bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &totalBytesRead);
  62383. DRWAV_ASSERT(pParser->stage == drwav__metadata_parser_stage_read);
  62384. if (bytesJustRead == sizeof(buffer)) {
  62385. drwav_uint32 sizeIncludingNullTerminator;
  62386. pMetadata->type = drwav_metadata_type_list_labelled_cue_region;
  62387. pMetadata->data.labelledCueRegion.cuePointId = drwav_bytes_to_u32(buffer + 0);
  62388. pMetadata->data.labelledCueRegion.sampleLength = drwav_bytes_to_u32(buffer + 4);
  62389. pMetadata->data.labelledCueRegion.purposeId[0] = buffer[8];
  62390. pMetadata->data.labelledCueRegion.purposeId[1] = buffer[9];
  62391. pMetadata->data.labelledCueRegion.purposeId[2] = buffer[10];
  62392. pMetadata->data.labelledCueRegion.purposeId[3] = buffer[11];
  62393. pMetadata->data.labelledCueRegion.country = drwav_bytes_to_u16(buffer + 12);
  62394. pMetadata->data.labelledCueRegion.language = drwav_bytes_to_u16(buffer + 14);
  62395. pMetadata->data.labelledCueRegion.dialect = drwav_bytes_to_u16(buffer + 16);
  62396. pMetadata->data.labelledCueRegion.codePage = drwav_bytes_to_u16(buffer + 18);
  62397. sizeIncludingNullTerminator = (drwav_uint32)chunkSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
  62398. if (sizeIncludingNullTerminator > 0) {
  62399. pMetadata->data.labelledCueRegion.stringLength = sizeIncludingNullTerminator - 1;
  62400. pMetadata->data.labelledCueRegion.pString = (char*)drwav__metadata_get_memory(pParser, sizeIncludingNullTerminator, 1);
  62401. DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  62402. drwav__metadata_parser_read(pParser, pMetadata->data.labelledCueRegion.pString, sizeIncludingNullTerminator, &totalBytesRead);
  62403. } else {
  62404. pMetadata->data.labelledCueRegion.stringLength = 0;
  62405. pMetadata->data.labelledCueRegion.pString = NULL;
  62406. }
  62407. }
  62408. return totalBytesRead;
  62409. }
  62410. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_info_text_chunk(drwav__metadata_parser* pParser, drwav_uint64 chunkSize, drwav_metadata_type type)
  62411. {
  62412. drwav_uint64 bytesRead = 0;
  62413. drwav_uint32 stringSizeWithNullTerminator = (drwav_uint32)chunkSize;
  62414. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62415. pParser->metadataCount += 1;
  62416. drwav__metadata_request_extra_memory_for_stage_2(pParser, stringSizeWithNullTerminator, 1);
  62417. } else {
  62418. drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  62419. pMetadata->type = type;
  62420. if (stringSizeWithNullTerminator > 0) {
  62421. pMetadata->data.infoText.stringLength = stringSizeWithNullTerminator - 1;
  62422. pMetadata->data.infoText.pString = (char*)drwav__metadata_get_memory(pParser, stringSizeWithNullTerminator, 1);
  62423. DRWAV_ASSERT(pMetadata->data.infoText.pString != NULL);
  62424. bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.infoText.pString, (size_t)stringSizeWithNullTerminator, NULL);
  62425. if (bytesRead == chunkSize) {
  62426. pParser->metadataCursor += 1;
  62427. } else {
  62428. }
  62429. } else {
  62430. pMetadata->data.infoText.stringLength = 0;
  62431. pMetadata->data.infoText.pString = NULL;
  62432. pParser->metadataCursor += 1;
  62433. }
  62434. }
  62435. return bytesRead;
  62436. }
  62437. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_unknown_chunk(drwav__metadata_parser* pParser, const drwav_uint8* pChunkId, drwav_uint64 chunkSize, drwav_metadata_location location)
  62438. {
  62439. drwav_uint64 bytesRead = 0;
  62440. if (location == drwav_metadata_location_invalid) {
  62441. return 0;
  62442. }
  62443. if (drwav_fourcc_equal(pChunkId, "data") || drwav_fourcc_equal(pChunkId, "fmt") || drwav_fourcc_equal(pChunkId, "fact")) {
  62444. return 0;
  62445. }
  62446. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62447. pParser->metadataCount += 1;
  62448. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)chunkSize, 1);
  62449. } else {
  62450. drwav_metadata* pMetadata = &pParser->pMetadata[pParser->metadataCursor];
  62451. pMetadata->type = drwav_metadata_type_unknown;
  62452. pMetadata->data.unknown.chunkLocation = location;
  62453. pMetadata->data.unknown.id[0] = pChunkId[0];
  62454. pMetadata->data.unknown.id[1] = pChunkId[1];
  62455. pMetadata->data.unknown.id[2] = pChunkId[2];
  62456. pMetadata->data.unknown.id[3] = pChunkId[3];
  62457. pMetadata->data.unknown.dataSizeInBytes = (drwav_uint32)chunkSize;
  62458. pMetadata->data.unknown.pData = (drwav_uint8 *)drwav__metadata_get_memory(pParser, (size_t)chunkSize, 1);
  62459. DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  62460. bytesRead = drwav__metadata_parser_read(pParser, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes, NULL);
  62461. if (bytesRead == pMetadata->data.unknown.dataSizeInBytes) {
  62462. pParser->metadataCursor += 1;
  62463. } else {
  62464. }
  62465. }
  62466. return bytesRead;
  62467. }
  62468. DRWAV_PRIVATE drwav_bool32 drwav__chunk_matches(drwav_metadata_type allowedMetadataTypes, const drwav_uint8* pChunkID, drwav_metadata_type type, const char* pID)
  62469. {
  62470. return (allowedMetadataTypes & type) && drwav_fourcc_equal(pChunkID, pID);
  62471. }
  62472. DRWAV_PRIVATE drwav_uint64 drwav__metadata_process_chunk(drwav__metadata_parser* pParser, const drwav_chunk_header* pChunkHeader, drwav_metadata_type allowedMetadataTypes)
  62473. {
  62474. const drwav_uint8 *pChunkID = pChunkHeader->id.fourcc;
  62475. drwav_uint64 bytesRead = 0;
  62476. if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_smpl, "smpl")) {
  62477. if (pChunkHeader->sizeInBytes >= DRWAV_SMPL_BYTES) {
  62478. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62479. drwav_uint8 buffer[4];
  62480. size_t bytesJustRead;
  62481. if (!pParser->onSeek(pParser->pReadSeekUserData, 28, drwav_seek_origin_current)) {
  62482. return bytesRead;
  62483. }
  62484. bytesRead += 28;
  62485. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  62486. if (bytesJustRead == sizeof(buffer)) {
  62487. drwav_uint32 loopCount = drwav_bytes_to_u32(buffer);
  62488. drwav_uint64 calculatedLoopCount;
  62489. calculatedLoopCount = (pChunkHeader->sizeInBytes - DRWAV_SMPL_BYTES) / DRWAV_SMPL_LOOP_BYTES;
  62490. if (calculatedLoopCount == loopCount) {
  62491. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, sizeof(buffer), &bytesRead);
  62492. if (bytesJustRead == sizeof(buffer)) {
  62493. drwav_uint32 samplerSpecificDataSizeInBytes = drwav_bytes_to_u32(buffer);
  62494. pParser->metadataCount += 1;
  62495. drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_smpl_loop) * loopCount, DRWAV_METADATA_ALIGNMENT);
  62496. drwav__metadata_request_extra_memory_for_stage_2(pParser, samplerSpecificDataSizeInBytes, 1);
  62497. }
  62498. } else {
  62499. }
  62500. }
  62501. } else {
  62502. bytesRead = drwav__read_smpl_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  62503. if (bytesRead == pChunkHeader->sizeInBytes) {
  62504. pParser->metadataCursor += 1;
  62505. } else {
  62506. }
  62507. }
  62508. } else {
  62509. }
  62510. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_inst, "inst")) {
  62511. if (pChunkHeader->sizeInBytes == DRWAV_INST_BYTES) {
  62512. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62513. pParser->metadataCount += 1;
  62514. } else {
  62515. bytesRead = drwav__read_inst_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  62516. if (bytesRead == pChunkHeader->sizeInBytes) {
  62517. pParser->metadataCursor += 1;
  62518. } else {
  62519. }
  62520. }
  62521. } else {
  62522. }
  62523. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_acid, "acid")) {
  62524. if (pChunkHeader->sizeInBytes == DRWAV_ACID_BYTES) {
  62525. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62526. pParser->metadataCount += 1;
  62527. } else {
  62528. bytesRead = drwav__read_acid_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor]);
  62529. if (bytesRead == pChunkHeader->sizeInBytes) {
  62530. pParser->metadataCursor += 1;
  62531. } else {
  62532. }
  62533. }
  62534. } else {
  62535. }
  62536. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_cue, "cue ")) {
  62537. if (pChunkHeader->sizeInBytes >= DRWAV_CUE_BYTES) {
  62538. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62539. size_t cueCount;
  62540. pParser->metadataCount += 1;
  62541. cueCount = (size_t)(pChunkHeader->sizeInBytes - DRWAV_CUE_BYTES) / DRWAV_CUE_POINT_BYTES;
  62542. drwav__metadata_request_extra_memory_for_stage_2(pParser, sizeof(drwav_cue_point) * cueCount, DRWAV_METADATA_ALIGNMENT);
  62543. } else {
  62544. bytesRead = drwav__read_cue_to_metadata_obj(pParser, pChunkHeader, &pParser->pMetadata[pParser->metadataCursor]);
  62545. if (bytesRead == pChunkHeader->sizeInBytes) {
  62546. pParser->metadataCursor += 1;
  62547. } else {
  62548. }
  62549. }
  62550. } else {
  62551. }
  62552. } else if (drwav__chunk_matches(allowedMetadataTypes, pChunkID, drwav_metadata_type_bext, "bext")) {
  62553. if (pChunkHeader->sizeInBytes >= DRWAV_BEXT_BYTES) {
  62554. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62555. char buffer[DRWAV_BEXT_DESCRIPTION_BYTES + 1];
  62556. size_t allocSizeNeeded = DRWAV_BEXT_UMID_BYTES;
  62557. size_t bytesJustRead;
  62558. buffer[DRWAV_BEXT_DESCRIPTION_BYTES] = '\0';
  62559. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_DESCRIPTION_BYTES, &bytesRead);
  62560. if (bytesJustRead != DRWAV_BEXT_DESCRIPTION_BYTES) {
  62561. return bytesRead;
  62562. }
  62563. allocSizeNeeded += drwav__strlen(buffer) + 1;
  62564. buffer[DRWAV_BEXT_ORIGINATOR_NAME_BYTES] = '\0';
  62565. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_NAME_BYTES, &bytesRead);
  62566. if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_NAME_BYTES) {
  62567. return bytesRead;
  62568. }
  62569. allocSizeNeeded += drwav__strlen(buffer) + 1;
  62570. buffer[DRWAV_BEXT_ORIGINATOR_REF_BYTES] = '\0';
  62571. bytesJustRead = drwav__metadata_parser_read(pParser, buffer, DRWAV_BEXT_ORIGINATOR_REF_BYTES, &bytesRead);
  62572. if (bytesJustRead != DRWAV_BEXT_ORIGINATOR_REF_BYTES) {
  62573. return bytesRead;
  62574. }
  62575. allocSizeNeeded += drwav__strlen(buffer) + 1;
  62576. allocSizeNeeded += (size_t)pChunkHeader->sizeInBytes - DRWAV_BEXT_BYTES;
  62577. drwav__metadata_request_extra_memory_for_stage_2(pParser, allocSizeNeeded, 1);
  62578. pParser->metadataCount += 1;
  62579. } else {
  62580. bytesRead = drwav__read_bext_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], pChunkHeader->sizeInBytes);
  62581. if (bytesRead == pChunkHeader->sizeInBytes) {
  62582. pParser->metadataCursor += 1;
  62583. } else {
  62584. }
  62585. }
  62586. } else {
  62587. }
  62588. } else if (drwav_fourcc_equal(pChunkID, "LIST") || drwav_fourcc_equal(pChunkID, "list")) {
  62589. drwav_metadata_location listType = drwav_metadata_location_invalid;
  62590. while (bytesRead < pChunkHeader->sizeInBytes) {
  62591. drwav_uint8 subchunkId[4];
  62592. drwav_uint8 subchunkSizeBuffer[4];
  62593. drwav_uint64 subchunkDataSize;
  62594. drwav_uint64 subchunkBytesRead = 0;
  62595. drwav_uint64 bytesJustRead = drwav__metadata_parser_read(pParser, subchunkId, sizeof(subchunkId), &bytesRead);
  62596. if (bytesJustRead != sizeof(subchunkId)) {
  62597. break;
  62598. }
  62599. if (drwav_fourcc_equal(subchunkId, "adtl")) {
  62600. listType = drwav_metadata_location_inside_adtl_list;
  62601. continue;
  62602. } else if (drwav_fourcc_equal(subchunkId, "INFO")) {
  62603. listType = drwav_metadata_location_inside_info_list;
  62604. continue;
  62605. }
  62606. bytesJustRead = drwav__metadata_parser_read(pParser, subchunkSizeBuffer, sizeof(subchunkSizeBuffer), &bytesRead);
  62607. if (bytesJustRead != sizeof(subchunkSizeBuffer)) {
  62608. break;
  62609. }
  62610. subchunkDataSize = drwav_bytes_to_u32(subchunkSizeBuffer);
  62611. if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_label, "labl") || drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_note, "note")) {
  62612. if (subchunkDataSize >= DRWAV_LIST_LABEL_OR_NOTE_BYTES) {
  62613. drwav_uint64 stringSizeWithNullTerm = subchunkDataSize - DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  62614. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62615. pParser->metadataCount += 1;
  62616. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerm, 1);
  62617. } else {
  62618. subchunkBytesRead = drwav__read_list_label_or_note_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize, drwav_fourcc_equal(subchunkId, "labl") ? drwav_metadata_type_list_label : drwav_metadata_type_list_note);
  62619. if (subchunkBytesRead == subchunkDataSize) {
  62620. pParser->metadataCursor += 1;
  62621. } else {
  62622. }
  62623. }
  62624. } else {
  62625. }
  62626. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_labelled_cue_region, "ltxt")) {
  62627. if (subchunkDataSize >= DRWAV_LIST_LABELLED_TEXT_BYTES) {
  62628. drwav_uint64 stringSizeWithNullTerminator = subchunkDataSize - DRWAV_LIST_LABELLED_TEXT_BYTES;
  62629. if (pParser->stage == drwav__metadata_parser_stage_count) {
  62630. pParser->metadataCount += 1;
  62631. drwav__metadata_request_extra_memory_for_stage_2(pParser, (size_t)stringSizeWithNullTerminator, 1);
  62632. } else {
  62633. subchunkBytesRead = drwav__read_list_labelled_cue_region_to_metadata_obj(pParser, &pParser->pMetadata[pParser->metadataCursor], subchunkDataSize);
  62634. if (subchunkBytesRead == subchunkDataSize) {
  62635. pParser->metadataCursor += 1;
  62636. } else {
  62637. }
  62638. }
  62639. } else {
  62640. }
  62641. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_software, "ISFT")) {
  62642. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_software);
  62643. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_copyright, "ICOP")) {
  62644. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_copyright);
  62645. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_title, "INAM")) {
  62646. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_title);
  62647. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_artist, "IART")) {
  62648. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_artist);
  62649. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_comment, "ICMT")) {
  62650. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_comment);
  62651. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_date, "ICRD")) {
  62652. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_date);
  62653. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_genre, "IGNR")) {
  62654. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_genre);
  62655. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_album, "IPRD")) {
  62656. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_album);
  62657. } else if (drwav__chunk_matches(allowedMetadataTypes, subchunkId, drwav_metadata_type_list_info_tracknumber, "ITRK")) {
  62658. subchunkBytesRead = drwav__metadata_process_info_text_chunk(pParser, subchunkDataSize, drwav_metadata_type_list_info_tracknumber);
  62659. } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
  62660. subchunkBytesRead = drwav__metadata_process_unknown_chunk(pParser, subchunkId, subchunkDataSize, listType);
  62661. }
  62662. bytesRead += subchunkBytesRead;
  62663. DRWAV_ASSERT(subchunkBytesRead <= subchunkDataSize);
  62664. if (subchunkBytesRead < subchunkDataSize) {
  62665. drwav_uint64 bytesToSeek = subchunkDataSize - subchunkBytesRead;
  62666. if (!pParser->onSeek(pParser->pReadSeekUserData, (int)bytesToSeek, drwav_seek_origin_current)) {
  62667. break;
  62668. }
  62669. bytesRead += bytesToSeek;
  62670. }
  62671. if ((subchunkDataSize % 2) == 1) {
  62672. if (!pParser->onSeek(pParser->pReadSeekUserData, 1, drwav_seek_origin_current)) {
  62673. break;
  62674. }
  62675. bytesRead += 1;
  62676. }
  62677. }
  62678. } else if ((allowedMetadataTypes & drwav_metadata_type_unknown) != 0) {
  62679. bytesRead = drwav__metadata_process_unknown_chunk(pParser, pChunkID, pChunkHeader->sizeInBytes, drwav_metadata_location_top_level);
  62680. }
  62681. return bytesRead;
  62682. }
  62683. DRWAV_PRIVATE drwav_uint32 drwav_get_bytes_per_pcm_frame(drwav* pWav)
  62684. {
  62685. drwav_uint32 bytesPerFrame;
  62686. if ((pWav->bitsPerSample & 0x7) == 0) {
  62687. bytesPerFrame = (pWav->bitsPerSample * pWav->fmt.channels) >> 3;
  62688. } else {
  62689. bytesPerFrame = pWav->fmt.blockAlign;
  62690. }
  62691. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW || pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  62692. if (bytesPerFrame != pWav->fmt.channels) {
  62693. return 0;
  62694. }
  62695. }
  62696. return bytesPerFrame;
  62697. }
  62698. DRWAV_API drwav_uint16 drwav_fmt_get_format(const drwav_fmt* pFMT)
  62699. {
  62700. if (pFMT == NULL) {
  62701. return 0;
  62702. }
  62703. if (pFMT->formatTag != DR_WAVE_FORMAT_EXTENSIBLE) {
  62704. return pFMT->formatTag;
  62705. } else {
  62706. return drwav_bytes_to_u16(pFMT->subFormat);
  62707. }
  62708. }
  62709. DRWAV_PRIVATE drwav_bool32 drwav_preinit(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pReadSeekUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  62710. {
  62711. if (pWav == NULL || onRead == NULL || onSeek == NULL) {
  62712. return DRWAV_FALSE;
  62713. }
  62714. DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  62715. pWav->onRead = onRead;
  62716. pWav->onSeek = onSeek;
  62717. pWav->pUserData = pReadSeekUserData;
  62718. pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  62719. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  62720. return DRWAV_FALSE;
  62721. }
  62722. return DRWAV_TRUE;
  62723. }
  62724. DRWAV_PRIVATE drwav_bool32 drwav_init__internal(drwav* pWav, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags)
  62725. {
  62726. drwav_uint64 cursor;
  62727. drwav_bool32 sequential;
  62728. drwav_uint8 riff[4];
  62729. drwav_fmt fmt;
  62730. unsigned short translatedFormatTag;
  62731. drwav_bool32 foundDataChunk;
  62732. drwav_uint64 dataChunkSize = 0;
  62733. drwav_uint64 sampleCountFromFactChunk = 0;
  62734. drwav_uint64 chunkSize;
  62735. drwav__metadata_parser metadataParser;
  62736. cursor = 0;
  62737. sequential = (flags & DRWAV_SEQUENTIAL) != 0;
  62738. if (drwav__on_read(pWav->onRead, pWav->pUserData, riff, sizeof(riff), &cursor) != sizeof(riff)) {
  62739. return DRWAV_FALSE;
  62740. }
  62741. if (drwav_fourcc_equal(riff, "RIFF")) {
  62742. pWav->container = drwav_container_riff;
  62743. } else if (drwav_fourcc_equal(riff, "riff")) {
  62744. int i;
  62745. drwav_uint8 riff2[12];
  62746. pWav->container = drwav_container_w64;
  62747. if (drwav__on_read(pWav->onRead, pWav->pUserData, riff2, sizeof(riff2), &cursor) != sizeof(riff2)) {
  62748. return DRWAV_FALSE;
  62749. }
  62750. for (i = 0; i < 12; ++i) {
  62751. if (riff2[i] != drwavGUID_W64_RIFF[i+4]) {
  62752. return DRWAV_FALSE;
  62753. }
  62754. }
  62755. } else if (drwav_fourcc_equal(riff, "RF64")) {
  62756. pWav->container = drwav_container_rf64;
  62757. } else {
  62758. return DRWAV_FALSE;
  62759. }
  62760. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  62761. drwav_uint8 chunkSizeBytes[4];
  62762. drwav_uint8 wave[4];
  62763. if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  62764. return DRWAV_FALSE;
  62765. }
  62766. if (pWav->container == drwav_container_riff) {
  62767. if (drwav_bytes_to_u32(chunkSizeBytes) < 36) {
  62768. return DRWAV_FALSE;
  62769. }
  62770. } else {
  62771. if (drwav_bytes_to_u32(chunkSizeBytes) != 0xFFFFFFFF) {
  62772. return DRWAV_FALSE;
  62773. }
  62774. }
  62775. if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  62776. return DRWAV_FALSE;
  62777. }
  62778. if (!drwav_fourcc_equal(wave, "WAVE")) {
  62779. return DRWAV_FALSE;
  62780. }
  62781. } else {
  62782. drwav_uint8 chunkSizeBytes[8];
  62783. drwav_uint8 wave[16];
  62784. if (drwav__on_read(pWav->onRead, pWav->pUserData, chunkSizeBytes, sizeof(chunkSizeBytes), &cursor) != sizeof(chunkSizeBytes)) {
  62785. return DRWAV_FALSE;
  62786. }
  62787. if (drwav_bytes_to_u64(chunkSizeBytes) < 80) {
  62788. return DRWAV_FALSE;
  62789. }
  62790. if (drwav__on_read(pWav->onRead, pWav->pUserData, wave, sizeof(wave), &cursor) != sizeof(wave)) {
  62791. return DRWAV_FALSE;
  62792. }
  62793. if (!drwav_guid_equal(wave, drwavGUID_W64_WAVE)) {
  62794. return DRWAV_FALSE;
  62795. }
  62796. }
  62797. if (pWav->container == drwav_container_rf64) {
  62798. drwav_uint8 sizeBytes[8];
  62799. drwav_uint64 bytesRemainingInChunk;
  62800. drwav_chunk_header header;
  62801. drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  62802. if (result != DRWAV_SUCCESS) {
  62803. return DRWAV_FALSE;
  62804. }
  62805. if (!drwav_fourcc_equal(header.id.fourcc, "ds64")) {
  62806. return DRWAV_FALSE;
  62807. }
  62808. bytesRemainingInChunk = header.sizeInBytes + header.paddingSize;
  62809. if (!drwav__seek_forward(pWav->onSeek, 8, pWav->pUserData)) {
  62810. return DRWAV_FALSE;
  62811. }
  62812. bytesRemainingInChunk -= 8;
  62813. cursor += 8;
  62814. if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  62815. return DRWAV_FALSE;
  62816. }
  62817. bytesRemainingInChunk -= 8;
  62818. dataChunkSize = drwav_bytes_to_u64(sizeBytes);
  62819. if (drwav__on_read(pWav->onRead, pWav->pUserData, sizeBytes, sizeof(sizeBytes), &cursor) != sizeof(sizeBytes)) {
  62820. return DRWAV_FALSE;
  62821. }
  62822. bytesRemainingInChunk -= 8;
  62823. sampleCountFromFactChunk = drwav_bytes_to_u64(sizeBytes);
  62824. if (!drwav__seek_forward(pWav->onSeek, bytesRemainingInChunk, pWav->pUserData)) {
  62825. return DRWAV_FALSE;
  62826. }
  62827. cursor += bytesRemainingInChunk;
  62828. }
  62829. if (!drwav__read_fmt(pWav->onRead, pWav->onSeek, pWav->pUserData, pWav->container, &cursor, &fmt)) {
  62830. return DRWAV_FALSE;
  62831. }
  62832. if ((fmt.sampleRate == 0 || fmt.sampleRate > DRWAV_MAX_SAMPLE_RATE) ||
  62833. (fmt.channels == 0 || fmt.channels > DRWAV_MAX_CHANNELS) ||
  62834. (fmt.bitsPerSample == 0 || fmt.bitsPerSample > DRWAV_MAX_BITS_PER_SAMPLE) ||
  62835. fmt.blockAlign == 0) {
  62836. return DRWAV_FALSE;
  62837. }
  62838. translatedFormatTag = fmt.formatTag;
  62839. if (translatedFormatTag == DR_WAVE_FORMAT_EXTENSIBLE) {
  62840. translatedFormatTag = drwav_bytes_to_u16(fmt.subFormat + 0);
  62841. }
  62842. DRWAV_ZERO_MEMORY(&metadataParser, sizeof(metadataParser));
  62843. if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) {
  62844. drwav_uint64 cursorForMetadata = cursor;
  62845. metadataParser.onRead = pWav->onRead;
  62846. metadataParser.onSeek = pWav->onSeek;
  62847. metadataParser.pReadSeekUserData = pWav->pUserData;
  62848. metadataParser.stage = drwav__metadata_parser_stage_count;
  62849. for (;;) {
  62850. drwav_result result;
  62851. drwav_uint64 bytesRead;
  62852. drwav_uint64 remainingBytes;
  62853. drwav_chunk_header header;
  62854. result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursorForMetadata, &header);
  62855. if (result != DRWAV_SUCCESS) {
  62856. break;
  62857. }
  62858. bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes);
  62859. DRWAV_ASSERT(bytesRead <= header.sizeInBytes);
  62860. remainingBytes = header.sizeInBytes - bytesRead + header.paddingSize;
  62861. if (!drwav__seek_forward(pWav->onSeek, remainingBytes, pWav->pUserData)) {
  62862. break;
  62863. }
  62864. cursorForMetadata += remainingBytes;
  62865. }
  62866. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  62867. return DRWAV_FALSE;
  62868. }
  62869. drwav__metadata_alloc(&metadataParser, &pWav->allocationCallbacks);
  62870. metadataParser.stage = drwav__metadata_parser_stage_read;
  62871. }
  62872. foundDataChunk = DRWAV_FALSE;
  62873. for (;;) {
  62874. drwav_chunk_header header;
  62875. drwav_result result = drwav__read_chunk_header(pWav->onRead, pWav->pUserData, pWav->container, &cursor, &header);
  62876. if (result != DRWAV_SUCCESS) {
  62877. if (!foundDataChunk) {
  62878. return DRWAV_FALSE;
  62879. } else {
  62880. break;
  62881. }
  62882. }
  62883. if (!sequential && onChunk != NULL) {
  62884. drwav_uint64 callbackBytesRead = onChunk(pChunkUserData, pWav->onRead, pWav->onSeek, pWav->pUserData, &header, pWav->container, &fmt);
  62885. if (callbackBytesRead > 0) {
  62886. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  62887. return DRWAV_FALSE;
  62888. }
  62889. }
  62890. }
  62891. if (!sequential && pWav->allowedMetadataTypes != drwav_metadata_type_none && (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64)) {
  62892. drwav_uint64 bytesRead = drwav__metadata_process_chunk(&metadataParser, &header, pWav->allowedMetadataTypes);
  62893. if (bytesRead > 0) {
  62894. if (!drwav__seek_from_start(pWav->onSeek, cursor, pWav->pUserData)) {
  62895. return DRWAV_FALSE;
  62896. }
  62897. }
  62898. }
  62899. if (!foundDataChunk) {
  62900. pWav->dataChunkDataPos = cursor;
  62901. }
  62902. chunkSize = header.sizeInBytes;
  62903. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  62904. if (drwav_fourcc_equal(header.id.fourcc, "data")) {
  62905. foundDataChunk = DRWAV_TRUE;
  62906. if (pWav->container != drwav_container_rf64) {
  62907. dataChunkSize = chunkSize;
  62908. }
  62909. }
  62910. } else {
  62911. if (drwav_guid_equal(header.id.guid, drwavGUID_W64_DATA)) {
  62912. foundDataChunk = DRWAV_TRUE;
  62913. dataChunkSize = chunkSize;
  62914. }
  62915. }
  62916. if (foundDataChunk && sequential) {
  62917. break;
  62918. }
  62919. if (pWav->container == drwav_container_riff) {
  62920. if (drwav_fourcc_equal(header.id.fourcc, "fact")) {
  62921. drwav_uint32 sampleCount;
  62922. if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCount, 4, &cursor) != 4) {
  62923. return DRWAV_FALSE;
  62924. }
  62925. chunkSize -= 4;
  62926. if (!foundDataChunk) {
  62927. pWav->dataChunkDataPos = cursor;
  62928. }
  62929. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  62930. sampleCountFromFactChunk = sampleCount;
  62931. } else {
  62932. sampleCountFromFactChunk = 0;
  62933. }
  62934. }
  62935. } else if (pWav->container == drwav_container_w64) {
  62936. if (drwav_guid_equal(header.id.guid, drwavGUID_W64_FACT)) {
  62937. if (drwav__on_read(pWav->onRead, pWav->pUserData, &sampleCountFromFactChunk, 8, &cursor) != 8) {
  62938. return DRWAV_FALSE;
  62939. }
  62940. chunkSize -= 8;
  62941. if (!foundDataChunk) {
  62942. pWav->dataChunkDataPos = cursor;
  62943. }
  62944. }
  62945. } else if (pWav->container == drwav_container_rf64) {
  62946. }
  62947. chunkSize += header.paddingSize;
  62948. if (!drwav__seek_forward(pWav->onSeek, chunkSize, pWav->pUserData)) {
  62949. break;
  62950. }
  62951. cursor += chunkSize;
  62952. if (!foundDataChunk) {
  62953. pWav->dataChunkDataPos = cursor;
  62954. }
  62955. }
  62956. pWav->pMetadata = metadataParser.pMetadata;
  62957. pWav->metadataCount = metadataParser.metadataCount;
  62958. if (!foundDataChunk) {
  62959. return DRWAV_FALSE;
  62960. }
  62961. if (!sequential) {
  62962. if (!drwav__seek_from_start(pWav->onSeek, pWav->dataChunkDataPos, pWav->pUserData)) {
  62963. return DRWAV_FALSE;
  62964. }
  62965. cursor = pWav->dataChunkDataPos;
  62966. }
  62967. pWav->fmt = fmt;
  62968. pWav->sampleRate = fmt.sampleRate;
  62969. pWav->channels = fmt.channels;
  62970. pWav->bitsPerSample = fmt.bitsPerSample;
  62971. pWav->bytesRemaining = dataChunkSize;
  62972. pWav->translatedFormatTag = translatedFormatTag;
  62973. pWav->dataChunkDataSize = dataChunkSize;
  62974. if (sampleCountFromFactChunk != 0) {
  62975. pWav->totalPCMFrameCount = sampleCountFromFactChunk;
  62976. } else {
  62977. drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  62978. if (bytesPerFrame == 0) {
  62979. return DRWAV_FALSE;
  62980. }
  62981. pWav->totalPCMFrameCount = dataChunkSize / bytesPerFrame;
  62982. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  62983. drwav_uint64 totalBlockHeaderSizeInBytes;
  62984. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  62985. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  62986. blockCount += 1;
  62987. }
  62988. totalBlockHeaderSizeInBytes = blockCount * (6*fmt.channels);
  62989. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  62990. }
  62991. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  62992. drwav_uint64 totalBlockHeaderSizeInBytes;
  62993. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  62994. if ((blockCount * fmt.blockAlign) < dataChunkSize) {
  62995. blockCount += 1;
  62996. }
  62997. totalBlockHeaderSizeInBytes = blockCount * (4*fmt.channels);
  62998. pWav->totalPCMFrameCount = ((dataChunkSize - totalBlockHeaderSizeInBytes) * 2) / fmt.channels;
  62999. pWav->totalPCMFrameCount += blockCount;
  63000. }
  63001. }
  63002. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  63003. if (pWav->channels > 2) {
  63004. return DRWAV_FALSE;
  63005. }
  63006. }
  63007. if (drwav_get_bytes_per_pcm_frame(pWav) == 0) {
  63008. return DRWAV_FALSE;
  63009. }
  63010. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  63011. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  63012. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  63013. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (6*pWav->channels))) * 2)) / fmt.channels;
  63014. }
  63015. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  63016. drwav_uint64 blockCount = dataChunkSize / fmt.blockAlign;
  63017. pWav->totalPCMFrameCount = (((blockCount * (fmt.blockAlign - (4*pWav->channels))) * 2) + (blockCount * pWav->channels)) / fmt.channels;
  63018. }
  63019. #endif
  63020. return DRWAV_TRUE;
  63021. }
  63022. DRWAV_API drwav_bool32 drwav_init(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  63023. {
  63024. return drwav_init_ex(pWav, onRead, onSeek, NULL, pUserData, NULL, 0, pAllocationCallbacks);
  63025. }
  63026. DRWAV_API drwav_bool32 drwav_init_ex(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, drwav_chunk_proc onChunk, void* pReadSeekUserData, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  63027. {
  63028. if (!drwav_preinit(pWav, onRead, onSeek, pReadSeekUserData, pAllocationCallbacks)) {
  63029. return DRWAV_FALSE;
  63030. }
  63031. return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  63032. }
  63033. DRWAV_API drwav_bool32 drwav_init_with_metadata(drwav* pWav, drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  63034. {
  63035. if (!drwav_preinit(pWav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  63036. return DRWAV_FALSE;
  63037. }
  63038. pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown;
  63039. return drwav_init__internal(pWav, NULL, NULL, flags);
  63040. }
  63041. DRWAV_API drwav_metadata* drwav_take_ownership_of_metadata(drwav* pWav)
  63042. {
  63043. drwav_metadata *result = pWav->pMetadata;
  63044. pWav->pMetadata = NULL;
  63045. pWav->metadataCount = 0;
  63046. return result;
  63047. }
  63048. DRWAV_PRIVATE size_t drwav__write(drwav* pWav, const void* pData, size_t dataSize)
  63049. {
  63050. DRWAV_ASSERT(pWav != NULL);
  63051. DRWAV_ASSERT(pWav->onWrite != NULL);
  63052. return pWav->onWrite(pWav->pUserData, pData, dataSize);
  63053. }
  63054. DRWAV_PRIVATE size_t drwav__write_byte(drwav* pWav, drwav_uint8 byte)
  63055. {
  63056. DRWAV_ASSERT(pWav != NULL);
  63057. DRWAV_ASSERT(pWav->onWrite != NULL);
  63058. return pWav->onWrite(pWav->pUserData, &byte, 1);
  63059. }
  63060. DRWAV_PRIVATE size_t drwav__write_u16ne_to_le(drwav* pWav, drwav_uint16 value)
  63061. {
  63062. DRWAV_ASSERT(pWav != NULL);
  63063. DRWAV_ASSERT(pWav->onWrite != NULL);
  63064. if (!drwav__is_little_endian()) {
  63065. value = drwav__bswap16(value);
  63066. }
  63067. return drwav__write(pWav, &value, 2);
  63068. }
  63069. DRWAV_PRIVATE size_t drwav__write_u32ne_to_le(drwav* pWav, drwav_uint32 value)
  63070. {
  63071. DRWAV_ASSERT(pWav != NULL);
  63072. DRWAV_ASSERT(pWav->onWrite != NULL);
  63073. if (!drwav__is_little_endian()) {
  63074. value = drwav__bswap32(value);
  63075. }
  63076. return drwav__write(pWav, &value, 4);
  63077. }
  63078. DRWAV_PRIVATE size_t drwav__write_u64ne_to_le(drwav* pWav, drwav_uint64 value)
  63079. {
  63080. DRWAV_ASSERT(pWav != NULL);
  63081. DRWAV_ASSERT(pWav->onWrite != NULL);
  63082. if (!drwav__is_little_endian()) {
  63083. value = drwav__bswap64(value);
  63084. }
  63085. return drwav__write(pWav, &value, 8);
  63086. }
  63087. DRWAV_PRIVATE size_t drwav__write_f32ne_to_le(drwav* pWav, float value)
  63088. {
  63089. union {
  63090. drwav_uint32 u32;
  63091. float f32;
  63092. } u;
  63093. DRWAV_ASSERT(pWav != NULL);
  63094. DRWAV_ASSERT(pWav->onWrite != NULL);
  63095. u.f32 = value;
  63096. if (!drwav__is_little_endian()) {
  63097. u.u32 = drwav__bswap32(u.u32);
  63098. }
  63099. return drwav__write(pWav, &u.u32, 4);
  63100. }
  63101. DRWAV_PRIVATE size_t drwav__write_or_count(drwav* pWav, const void* pData, size_t dataSize)
  63102. {
  63103. if (pWav == NULL) {
  63104. return dataSize;
  63105. }
  63106. return drwav__write(pWav, pData, dataSize);
  63107. }
  63108. DRWAV_PRIVATE size_t drwav__write_or_count_byte(drwav* pWav, drwav_uint8 byte)
  63109. {
  63110. if (pWav == NULL) {
  63111. return 1;
  63112. }
  63113. return drwav__write_byte(pWav, byte);
  63114. }
  63115. DRWAV_PRIVATE size_t drwav__write_or_count_u16ne_to_le(drwav* pWav, drwav_uint16 value)
  63116. {
  63117. if (pWav == NULL) {
  63118. return 2;
  63119. }
  63120. return drwav__write_u16ne_to_le(pWav, value);
  63121. }
  63122. DRWAV_PRIVATE size_t drwav__write_or_count_u32ne_to_le(drwav* pWav, drwav_uint32 value)
  63123. {
  63124. if (pWav == NULL) {
  63125. return 4;
  63126. }
  63127. return drwav__write_u32ne_to_le(pWav, value);
  63128. }
  63129. #if 0
  63130. DRWAV_PRIVATE size_t drwav__write_or_count_u64ne_to_le(drwav* pWav, drwav_uint64 value)
  63131. {
  63132. if (pWav == NULL) {
  63133. return 8;
  63134. }
  63135. return drwav__write_u64ne_to_le(pWav, value);
  63136. }
  63137. #endif
  63138. DRWAV_PRIVATE size_t drwav__write_or_count_f32ne_to_le(drwav* pWav, float value)
  63139. {
  63140. if (pWav == NULL) {
  63141. return 4;
  63142. }
  63143. return drwav__write_f32ne_to_le(pWav, value);
  63144. }
  63145. DRWAV_PRIVATE size_t drwav__write_or_count_string_to_fixed_size_buf(drwav* pWav, char* str, size_t bufFixedSize)
  63146. {
  63147. size_t len;
  63148. if (pWav == NULL) {
  63149. return bufFixedSize;
  63150. }
  63151. len = drwav__strlen_clamped(str, bufFixedSize);
  63152. drwav__write_or_count(pWav, str, len);
  63153. if (len < bufFixedSize) {
  63154. size_t i;
  63155. for (i = 0; i < bufFixedSize - len; ++i) {
  63156. drwav__write_byte(pWav, 0);
  63157. }
  63158. }
  63159. return bufFixedSize;
  63160. }
  63161. DRWAV_PRIVATE size_t drwav__write_or_count_metadata(drwav* pWav, drwav_metadata* pMetadatas, drwav_uint32 metadataCount)
  63162. {
  63163. size_t bytesWritten = 0;
  63164. drwav_bool32 hasListAdtl = DRWAV_FALSE;
  63165. drwav_bool32 hasListInfo = DRWAV_FALSE;
  63166. drwav_uint32 iMetadata;
  63167. if (pMetadatas == NULL || metadataCount == 0) {
  63168. return 0;
  63169. }
  63170. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  63171. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  63172. drwav_uint32 chunkSize = 0;
  63173. if ((pMetadata->type & drwav_metadata_type_list_all_info_strings) || (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list)) {
  63174. hasListInfo = DRWAV_TRUE;
  63175. }
  63176. if ((pMetadata->type & drwav_metadata_type_list_all_adtl) || (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list)) {
  63177. hasListAdtl = DRWAV_TRUE;
  63178. }
  63179. switch (pMetadata->type) {
  63180. case drwav_metadata_type_smpl:
  63181. {
  63182. drwav_uint32 iLoop;
  63183. chunkSize = DRWAV_SMPL_BYTES + DRWAV_SMPL_LOOP_BYTES * pMetadata->data.smpl.sampleLoopCount + pMetadata->data.smpl.samplerSpecificDataSizeInBytes;
  63184. bytesWritten += drwav__write_or_count(pWav, "smpl", 4);
  63185. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63186. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.manufacturerId);
  63187. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.productId);
  63188. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplePeriodNanoseconds);
  63189. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiUnityNote);
  63190. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.midiPitchFraction);
  63191. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteFormat);
  63192. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.smpteOffset);
  63193. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.sampleLoopCount);
  63194. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  63195. for (iLoop = 0; iLoop < pMetadata->data.smpl.sampleLoopCount; ++iLoop) {
  63196. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].cuePointId);
  63197. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].type);
  63198. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].firstSampleByteOffset);
  63199. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].lastSampleByteOffset);
  63200. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].sampleFraction);
  63201. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.smpl.pLoops[iLoop].playCount);
  63202. }
  63203. if (pMetadata->data.smpl.samplerSpecificDataSizeInBytes > 0) {
  63204. bytesWritten += drwav__write(pWav, pMetadata->data.smpl.pSamplerSpecificData, pMetadata->data.smpl.samplerSpecificDataSizeInBytes);
  63205. }
  63206. } break;
  63207. case drwav_metadata_type_inst:
  63208. {
  63209. chunkSize = DRWAV_INST_BYTES;
  63210. bytesWritten += drwav__write_or_count(pWav, "inst", 4);
  63211. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63212. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.midiUnityNote, 1);
  63213. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.fineTuneCents, 1);
  63214. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.gainDecibels, 1);
  63215. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowNote, 1);
  63216. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highNote, 1);
  63217. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.lowVelocity, 1);
  63218. bytesWritten += drwav__write_or_count(pWav, &pMetadata->data.inst.highVelocity, 1);
  63219. } break;
  63220. case drwav_metadata_type_cue:
  63221. {
  63222. drwav_uint32 iCuePoint;
  63223. chunkSize = DRWAV_CUE_BYTES + DRWAV_CUE_POINT_BYTES * pMetadata->data.cue.cuePointCount;
  63224. bytesWritten += drwav__write_or_count(pWav, "cue ", 4);
  63225. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63226. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.cuePointCount);
  63227. for (iCuePoint = 0; iCuePoint < pMetadata->data.cue.cuePointCount; ++iCuePoint) {
  63228. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].id);
  63229. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].playOrderPosition);
  63230. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].dataChunkId, 4);
  63231. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].chunkStart);
  63232. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].blockStart);
  63233. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.cue.pCuePoints[iCuePoint].sampleByteOffset);
  63234. }
  63235. } break;
  63236. case drwav_metadata_type_acid:
  63237. {
  63238. chunkSize = DRWAV_ACID_BYTES;
  63239. bytesWritten += drwav__write_or_count(pWav, "acid", 4);
  63240. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63241. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.flags);
  63242. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.midiUnityNote);
  63243. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.reserved1);
  63244. bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.reserved2);
  63245. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.acid.numBeats);
  63246. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterDenominator);
  63247. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.acid.meterNumerator);
  63248. bytesWritten += drwav__write_or_count_f32ne_to_le(pWav, pMetadata->data.acid.tempo);
  63249. } break;
  63250. case drwav_metadata_type_bext:
  63251. {
  63252. char reservedBuf[DRWAV_BEXT_RESERVED_BYTES];
  63253. drwav_uint32 timeReferenceLow;
  63254. drwav_uint32 timeReferenceHigh;
  63255. chunkSize = DRWAV_BEXT_BYTES + pMetadata->data.bext.codingHistorySize;
  63256. bytesWritten += drwav__write_or_count(pWav, "bext", 4);
  63257. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63258. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pDescription, DRWAV_BEXT_DESCRIPTION_BYTES);
  63259. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorName, DRWAV_BEXT_ORIGINATOR_NAME_BYTES);
  63260. bytesWritten += drwav__write_or_count_string_to_fixed_size_buf(pWav, pMetadata->data.bext.pOriginatorReference, DRWAV_BEXT_ORIGINATOR_REF_BYTES);
  63261. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationDate, sizeof(pMetadata->data.bext.pOriginationDate));
  63262. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pOriginationTime, sizeof(pMetadata->data.bext.pOriginationTime));
  63263. timeReferenceLow = (drwav_uint32)(pMetadata->data.bext.timeReference & 0xFFFFFFFF);
  63264. timeReferenceHigh = (drwav_uint32)(pMetadata->data.bext.timeReference >> 32);
  63265. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceLow);
  63266. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, timeReferenceHigh);
  63267. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.version);
  63268. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pUMID, DRWAV_BEXT_UMID_BYTES);
  63269. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessValue);
  63270. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.loudnessRange);
  63271. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxTruePeakLevel);
  63272. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxMomentaryLoudness);
  63273. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.bext.maxShortTermLoudness);
  63274. DRWAV_ZERO_MEMORY(reservedBuf, sizeof(reservedBuf));
  63275. bytesWritten += drwav__write_or_count(pWav, reservedBuf, sizeof(reservedBuf));
  63276. if (pMetadata->data.bext.codingHistorySize > 0) {
  63277. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.bext.pCodingHistory, pMetadata->data.bext.codingHistorySize);
  63278. }
  63279. } break;
  63280. case drwav_metadata_type_unknown:
  63281. {
  63282. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_top_level) {
  63283. chunkSize = pMetadata->data.unknown.dataSizeInBytes;
  63284. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  63285. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63286. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, pMetadata->data.unknown.dataSizeInBytes);
  63287. }
  63288. } break;
  63289. default: break;
  63290. }
  63291. if ((chunkSize % 2) != 0) {
  63292. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  63293. }
  63294. }
  63295. if (hasListInfo) {
  63296. drwav_uint32 chunkSize = 4;
  63297. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  63298. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  63299. if ((pMetadata->type & drwav_metadata_type_list_all_info_strings)) {
  63300. chunkSize += 8;
  63301. chunkSize += pMetadata->data.infoText.stringLength + 1;
  63302. } else if (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list) {
  63303. chunkSize += 8;
  63304. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  63305. }
  63306. if ((chunkSize % 2) != 0) {
  63307. chunkSize += 1;
  63308. }
  63309. }
  63310. bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
  63311. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63312. bytesWritten += drwav__write_or_count(pWav, "INFO", 4);
  63313. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  63314. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  63315. drwav_uint32 subchunkSize = 0;
  63316. if (pMetadata->type & drwav_metadata_type_list_all_info_strings) {
  63317. const char* pID = NULL;
  63318. switch (pMetadata->type) {
  63319. case drwav_metadata_type_list_info_software: pID = "ISFT"; break;
  63320. case drwav_metadata_type_list_info_copyright: pID = "ICOP"; break;
  63321. case drwav_metadata_type_list_info_title: pID = "INAM"; break;
  63322. case drwav_metadata_type_list_info_artist: pID = "IART"; break;
  63323. case drwav_metadata_type_list_info_comment: pID = "ICMT"; break;
  63324. case drwav_metadata_type_list_info_date: pID = "ICRD"; break;
  63325. case drwav_metadata_type_list_info_genre: pID = "IGNR"; break;
  63326. case drwav_metadata_type_list_info_album: pID = "IPRD"; break;
  63327. case drwav_metadata_type_list_info_tracknumber: pID = "ITRK"; break;
  63328. default: break;
  63329. }
  63330. DRWAV_ASSERT(pID != NULL);
  63331. if (pMetadata->data.infoText.stringLength) {
  63332. subchunkSize = pMetadata->data.infoText.stringLength + 1;
  63333. bytesWritten += drwav__write_or_count(pWav, pID, 4);
  63334. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  63335. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.infoText.pString, pMetadata->data.infoText.stringLength);
  63336. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  63337. }
  63338. } else if (pMetadata->type == drwav_metadata_type_unknown && pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_info_list) {
  63339. if (pMetadata->data.unknown.dataSizeInBytes) {
  63340. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  63341. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  63342. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.unknown.dataSizeInBytes);
  63343. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  63344. }
  63345. }
  63346. if ((subchunkSize % 2) != 0) {
  63347. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  63348. }
  63349. }
  63350. }
  63351. if (hasListAdtl) {
  63352. drwav_uint32 chunkSize = 4;
  63353. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  63354. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  63355. switch (pMetadata->type)
  63356. {
  63357. case drwav_metadata_type_list_label:
  63358. case drwav_metadata_type_list_note:
  63359. {
  63360. chunkSize += 8;
  63361. chunkSize += DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  63362. if (pMetadata->data.labelOrNote.stringLength > 0) {
  63363. chunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  63364. }
  63365. } break;
  63366. case drwav_metadata_type_list_labelled_cue_region:
  63367. {
  63368. chunkSize += 8;
  63369. chunkSize += DRWAV_LIST_LABELLED_TEXT_BYTES;
  63370. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  63371. chunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  63372. }
  63373. } break;
  63374. case drwav_metadata_type_unknown:
  63375. {
  63376. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list) {
  63377. chunkSize += 8;
  63378. chunkSize += pMetadata->data.unknown.dataSizeInBytes;
  63379. }
  63380. } break;
  63381. default: break;
  63382. }
  63383. if ((chunkSize % 2) != 0) {
  63384. chunkSize += 1;
  63385. }
  63386. }
  63387. bytesWritten += drwav__write_or_count(pWav, "LIST", 4);
  63388. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, chunkSize);
  63389. bytesWritten += drwav__write_or_count(pWav, "adtl", 4);
  63390. for (iMetadata = 0; iMetadata < metadataCount; ++iMetadata) {
  63391. drwav_metadata* pMetadata = &pMetadatas[iMetadata];
  63392. drwav_uint32 subchunkSize = 0;
  63393. switch (pMetadata->type)
  63394. {
  63395. case drwav_metadata_type_list_label:
  63396. case drwav_metadata_type_list_note:
  63397. {
  63398. if (pMetadata->data.labelOrNote.stringLength > 0) {
  63399. const char *pID = NULL;
  63400. if (pMetadata->type == drwav_metadata_type_list_label) {
  63401. pID = "labl";
  63402. }
  63403. else if (pMetadata->type == drwav_metadata_type_list_note) {
  63404. pID = "note";
  63405. }
  63406. DRWAV_ASSERT(pID != NULL);
  63407. DRWAV_ASSERT(pMetadata->data.labelOrNote.pString != NULL);
  63408. subchunkSize = DRWAV_LIST_LABEL_OR_NOTE_BYTES;
  63409. bytesWritten += drwav__write_or_count(pWav, pID, 4);
  63410. subchunkSize += pMetadata->data.labelOrNote.stringLength + 1;
  63411. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  63412. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelOrNote.cuePointId);
  63413. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelOrNote.pString, pMetadata->data.labelOrNote.stringLength);
  63414. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  63415. }
  63416. } break;
  63417. case drwav_metadata_type_list_labelled_cue_region:
  63418. {
  63419. subchunkSize = DRWAV_LIST_LABELLED_TEXT_BYTES;
  63420. bytesWritten += drwav__write_or_count(pWav, "ltxt", 4);
  63421. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  63422. subchunkSize += pMetadata->data.labelledCueRegion.stringLength + 1;
  63423. }
  63424. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  63425. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.cuePointId);
  63426. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, pMetadata->data.labelledCueRegion.sampleLength);
  63427. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.purposeId, 4);
  63428. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.country);
  63429. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.language);
  63430. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.dialect);
  63431. bytesWritten += drwav__write_or_count_u16ne_to_le(pWav, pMetadata->data.labelledCueRegion.codePage);
  63432. if (pMetadata->data.labelledCueRegion.stringLength > 0) {
  63433. DRWAV_ASSERT(pMetadata->data.labelledCueRegion.pString != NULL);
  63434. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.labelledCueRegion.pString, pMetadata->data.labelledCueRegion.stringLength);
  63435. bytesWritten += drwav__write_or_count_byte(pWav, '\0');
  63436. }
  63437. } break;
  63438. case drwav_metadata_type_unknown:
  63439. {
  63440. if (pMetadata->data.unknown.chunkLocation == drwav_metadata_location_inside_adtl_list) {
  63441. subchunkSize = pMetadata->data.unknown.dataSizeInBytes;
  63442. DRWAV_ASSERT(pMetadata->data.unknown.pData != NULL);
  63443. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.id, 4);
  63444. bytesWritten += drwav__write_or_count_u32ne_to_le(pWav, subchunkSize);
  63445. bytesWritten += drwav__write_or_count(pWav, pMetadata->data.unknown.pData, subchunkSize);
  63446. }
  63447. } break;
  63448. default: break;
  63449. }
  63450. if ((subchunkSize % 2) != 0) {
  63451. bytesWritten += drwav__write_or_count_byte(pWav, 0);
  63452. }
  63453. }
  63454. }
  63455. DRWAV_ASSERT((bytesWritten % 2) == 0);
  63456. return bytesWritten;
  63457. }
  63458. DRWAV_PRIVATE drwav_uint32 drwav__riff_chunk_size_riff(drwav_uint64 dataChunkSize, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  63459. {
  63460. drwav_uint64 chunkSize = 4 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, pMetadata, metadataCount) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize);
  63461. if (chunkSize > 0xFFFFFFFFUL) {
  63462. chunkSize = 0xFFFFFFFFUL;
  63463. }
  63464. return (drwav_uint32)chunkSize;
  63465. }
  63466. DRWAV_PRIVATE drwav_uint32 drwav__data_chunk_size_riff(drwav_uint64 dataChunkSize)
  63467. {
  63468. if (dataChunkSize <= 0xFFFFFFFFUL) {
  63469. return (drwav_uint32)dataChunkSize;
  63470. } else {
  63471. return 0xFFFFFFFFUL;
  63472. }
  63473. }
  63474. DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_w64(drwav_uint64 dataChunkSize)
  63475. {
  63476. drwav_uint64 dataSubchunkPaddingSize = drwav__chunk_padding_size_w64(dataChunkSize);
  63477. return 80 + 24 + dataChunkSize + dataSubchunkPaddingSize;
  63478. }
  63479. DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_w64(drwav_uint64 dataChunkSize)
  63480. {
  63481. return 24 + dataChunkSize;
  63482. }
  63483. DRWAV_PRIVATE drwav_uint64 drwav__riff_chunk_size_rf64(drwav_uint64 dataChunkSize, drwav_metadata *metadata, drwav_uint32 numMetadata)
  63484. {
  63485. drwav_uint64 chunkSize = 4 + 36 + 24 + (drwav_uint64)drwav__write_or_count_metadata(NULL, metadata, numMetadata) + 8 + dataChunkSize + drwav__chunk_padding_size_riff(dataChunkSize);
  63486. if (chunkSize > 0xFFFFFFFFUL) {
  63487. chunkSize = 0xFFFFFFFFUL;
  63488. }
  63489. return chunkSize;
  63490. }
  63491. DRWAV_PRIVATE drwav_uint64 drwav__data_chunk_size_rf64(drwav_uint64 dataChunkSize)
  63492. {
  63493. return dataChunkSize;
  63494. }
  63495. DRWAV_PRIVATE drwav_bool32 drwav_preinit_write(drwav* pWav, const drwav_data_format* pFormat, drwav_bool32 isSequential, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  63496. {
  63497. if (pWav == NULL || onWrite == NULL) {
  63498. return DRWAV_FALSE;
  63499. }
  63500. if (!isSequential && onSeek == NULL) {
  63501. return DRWAV_FALSE;
  63502. }
  63503. if (pFormat->format == DR_WAVE_FORMAT_EXTENSIBLE) {
  63504. return DRWAV_FALSE;
  63505. }
  63506. if (pFormat->format == DR_WAVE_FORMAT_ADPCM || pFormat->format == DR_WAVE_FORMAT_DVI_ADPCM) {
  63507. return DRWAV_FALSE;
  63508. }
  63509. DRWAV_ZERO_MEMORY(pWav, sizeof(*pWav));
  63510. pWav->onWrite = onWrite;
  63511. pWav->onSeek = onSeek;
  63512. pWav->pUserData = pUserData;
  63513. pWav->allocationCallbacks = drwav_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  63514. if (pWav->allocationCallbacks.onFree == NULL || (pWav->allocationCallbacks.onMalloc == NULL && pWav->allocationCallbacks.onRealloc == NULL)) {
  63515. return DRWAV_FALSE;
  63516. }
  63517. pWav->fmt.formatTag = (drwav_uint16)pFormat->format;
  63518. pWav->fmt.channels = (drwav_uint16)pFormat->channels;
  63519. pWav->fmt.sampleRate = pFormat->sampleRate;
  63520. pWav->fmt.avgBytesPerSec = (drwav_uint32)((pFormat->bitsPerSample * pFormat->sampleRate * pFormat->channels) / 8);
  63521. pWav->fmt.blockAlign = (drwav_uint16)((pFormat->channels * pFormat->bitsPerSample) / 8);
  63522. pWav->fmt.bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  63523. pWav->fmt.extendedSize = 0;
  63524. pWav->isSequentialWrite = isSequential;
  63525. return DRWAV_TRUE;
  63526. }
  63527. DRWAV_PRIVATE drwav_bool32 drwav_init_write__internal(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount)
  63528. {
  63529. size_t runningPos = 0;
  63530. drwav_uint64 initialDataChunkSize = 0;
  63531. drwav_uint64 chunkSizeFMT;
  63532. if (pWav->isSequentialWrite) {
  63533. initialDataChunkSize = (totalSampleCount * pWav->fmt.bitsPerSample) / 8;
  63534. if (pFormat->container == drwav_container_riff) {
  63535. if (initialDataChunkSize > (0xFFFFFFFFUL - 36)) {
  63536. return DRWAV_FALSE;
  63537. }
  63538. }
  63539. }
  63540. pWav->dataChunkDataSizeTargetWrite = initialDataChunkSize;
  63541. if (pFormat->container == drwav_container_riff) {
  63542. drwav_uint32 chunkSizeRIFF = 28 + (drwav_uint32)initialDataChunkSize;
  63543. runningPos += drwav__write(pWav, "RIFF", 4);
  63544. runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeRIFF);
  63545. runningPos += drwav__write(pWav, "WAVE", 4);
  63546. } else if (pFormat->container == drwav_container_w64) {
  63547. drwav_uint64 chunkSizeRIFF = 80 + 24 + initialDataChunkSize;
  63548. runningPos += drwav__write(pWav, drwavGUID_W64_RIFF, 16);
  63549. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeRIFF);
  63550. runningPos += drwav__write(pWav, drwavGUID_W64_WAVE, 16);
  63551. } else if (pFormat->container == drwav_container_rf64) {
  63552. runningPos += drwav__write(pWav, "RF64", 4);
  63553. runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  63554. runningPos += drwav__write(pWav, "WAVE", 4);
  63555. }
  63556. if (pFormat->container == drwav_container_rf64) {
  63557. drwav_uint32 initialds64ChunkSize = 28;
  63558. drwav_uint64 initialRiffChunkSize = 8 + initialds64ChunkSize + initialDataChunkSize;
  63559. runningPos += drwav__write(pWav, "ds64", 4);
  63560. runningPos += drwav__write_u32ne_to_le(pWav, initialds64ChunkSize);
  63561. runningPos += drwav__write_u64ne_to_le(pWav, initialRiffChunkSize);
  63562. runningPos += drwav__write_u64ne_to_le(pWav, initialDataChunkSize);
  63563. runningPos += drwav__write_u64ne_to_le(pWav, totalSampleCount);
  63564. runningPos += drwav__write_u32ne_to_le(pWav, 0);
  63565. }
  63566. if (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64) {
  63567. chunkSizeFMT = 16;
  63568. runningPos += drwav__write(pWav, "fmt ", 4);
  63569. runningPos += drwav__write_u32ne_to_le(pWav, (drwav_uint32)chunkSizeFMT);
  63570. } else if (pFormat->container == drwav_container_w64) {
  63571. chunkSizeFMT = 40;
  63572. runningPos += drwav__write(pWav, drwavGUID_W64_FMT, 16);
  63573. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeFMT);
  63574. }
  63575. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.formatTag);
  63576. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.channels);
  63577. runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.sampleRate);
  63578. runningPos += drwav__write_u32ne_to_le(pWav, pWav->fmt.avgBytesPerSec);
  63579. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.blockAlign);
  63580. runningPos += drwav__write_u16ne_to_le(pWav, pWav->fmt.bitsPerSample);
  63581. if (!pWav->isSequentialWrite && pWav->pMetadata != NULL && pWav->metadataCount > 0 && (pFormat->container == drwav_container_riff || pFormat->container == drwav_container_rf64)) {
  63582. runningPos += drwav__write_or_count_metadata(pWav, pWav->pMetadata, pWav->metadataCount);
  63583. }
  63584. pWav->dataChunkDataPos = runningPos;
  63585. if (pFormat->container == drwav_container_riff) {
  63586. drwav_uint32 chunkSizeDATA = (drwav_uint32)initialDataChunkSize;
  63587. runningPos += drwav__write(pWav, "data", 4);
  63588. runningPos += drwav__write_u32ne_to_le(pWav, chunkSizeDATA);
  63589. } else if (pFormat->container == drwav_container_w64) {
  63590. drwav_uint64 chunkSizeDATA = 24 + initialDataChunkSize;
  63591. runningPos += drwav__write(pWav, drwavGUID_W64_DATA, 16);
  63592. runningPos += drwav__write_u64ne_to_le(pWav, chunkSizeDATA);
  63593. } else if (pFormat->container == drwav_container_rf64) {
  63594. runningPos += drwav__write(pWav, "data", 4);
  63595. runningPos += drwav__write_u32ne_to_le(pWav, 0xFFFFFFFF);
  63596. }
  63597. pWav->container = pFormat->container;
  63598. pWav->channels = (drwav_uint16)pFormat->channels;
  63599. pWav->sampleRate = pFormat->sampleRate;
  63600. pWav->bitsPerSample = (drwav_uint16)pFormat->bitsPerSample;
  63601. pWav->translatedFormatTag = (drwav_uint16)pFormat->format;
  63602. pWav->dataChunkDataPos = runningPos;
  63603. return DRWAV_TRUE;
  63604. }
  63605. DRWAV_API drwav_bool32 drwav_init_write(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  63606. {
  63607. if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  63608. return DRWAV_FALSE;
  63609. }
  63610. return drwav_init_write__internal(pWav, pFormat, 0);
  63611. }
  63612. DRWAV_API drwav_bool32 drwav_init_write_sequential(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  63613. {
  63614. if (!drwav_preinit_write(pWav, pFormat, DRWAV_TRUE, onWrite, NULL, pUserData, pAllocationCallbacks)) {
  63615. return DRWAV_FALSE;
  63616. }
  63617. return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  63618. }
  63619. DRWAV_API drwav_bool32 drwav_init_write_sequential_pcm_frames(drwav* pWav, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, drwav_write_proc onWrite, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks)
  63620. {
  63621. if (pFormat == NULL) {
  63622. return DRWAV_FALSE;
  63623. }
  63624. return drwav_init_write_sequential(pWav, pFormat, totalPCMFrameCount*pFormat->channels, onWrite, pUserData, pAllocationCallbacks);
  63625. }
  63626. DRWAV_API drwav_bool32 drwav_init_write_with_metadata(drwav* pWav, const drwav_data_format* pFormat, drwav_write_proc onWrite, drwav_seek_proc onSeek, void* pUserData, const drwav_allocation_callbacks* pAllocationCallbacks, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  63627. {
  63628. if (!drwav_preinit_write(pWav, pFormat, DRWAV_FALSE, onWrite, onSeek, pUserData, pAllocationCallbacks)) {
  63629. return DRWAV_FALSE;
  63630. }
  63631. pWav->pMetadata = pMetadata;
  63632. pWav->metadataCount = metadataCount;
  63633. return drwav_init_write__internal(pWav, pFormat, 0);
  63634. }
  63635. DRWAV_API drwav_uint64 drwav_target_write_size_bytes(const drwav_data_format* pFormat, drwav_uint64 totalFrameCount, drwav_metadata* pMetadata, drwav_uint32 metadataCount)
  63636. {
  63637. drwav_uint64 targetDataSizeBytes = (drwav_uint64)((drwav_int64)totalFrameCount * pFormat->channels * pFormat->bitsPerSample/8.0);
  63638. drwav_uint64 riffChunkSizeBytes;
  63639. drwav_uint64 fileSizeBytes = 0;
  63640. if (pFormat->container == drwav_container_riff) {
  63641. riffChunkSizeBytes = drwav__riff_chunk_size_riff(targetDataSizeBytes, pMetadata, metadataCount);
  63642. fileSizeBytes = (8 + riffChunkSizeBytes);
  63643. } else if (pFormat->container == drwav_container_w64) {
  63644. riffChunkSizeBytes = drwav__riff_chunk_size_w64(targetDataSizeBytes);
  63645. fileSizeBytes = riffChunkSizeBytes;
  63646. } else if (pFormat->container == drwav_container_rf64) {
  63647. riffChunkSizeBytes = drwav__riff_chunk_size_rf64(targetDataSizeBytes, pMetadata, metadataCount);
  63648. fileSizeBytes = (8 + riffChunkSizeBytes);
  63649. }
  63650. return fileSizeBytes;
  63651. }
  63652. #ifndef DR_WAV_NO_STDIO
  63653. #include <errno.h>
  63654. DRWAV_PRIVATE drwav_result drwav_result_from_errno(int e)
  63655. {
  63656. switch (e)
  63657. {
  63658. case 0: return DRWAV_SUCCESS;
  63659. #ifdef EPERM
  63660. case EPERM: return DRWAV_INVALID_OPERATION;
  63661. #endif
  63662. #ifdef ENOENT
  63663. case ENOENT: return DRWAV_DOES_NOT_EXIST;
  63664. #endif
  63665. #ifdef ESRCH
  63666. case ESRCH: return DRWAV_DOES_NOT_EXIST;
  63667. #endif
  63668. #ifdef EINTR
  63669. case EINTR: return DRWAV_INTERRUPT;
  63670. #endif
  63671. #ifdef EIO
  63672. case EIO: return DRWAV_IO_ERROR;
  63673. #endif
  63674. #ifdef ENXIO
  63675. case ENXIO: return DRWAV_DOES_NOT_EXIST;
  63676. #endif
  63677. #ifdef E2BIG
  63678. case E2BIG: return DRWAV_INVALID_ARGS;
  63679. #endif
  63680. #ifdef ENOEXEC
  63681. case ENOEXEC: return DRWAV_INVALID_FILE;
  63682. #endif
  63683. #ifdef EBADF
  63684. case EBADF: return DRWAV_INVALID_FILE;
  63685. #endif
  63686. #ifdef ECHILD
  63687. case ECHILD: return DRWAV_ERROR;
  63688. #endif
  63689. #ifdef EAGAIN
  63690. case EAGAIN: return DRWAV_UNAVAILABLE;
  63691. #endif
  63692. #ifdef ENOMEM
  63693. case ENOMEM: return DRWAV_OUT_OF_MEMORY;
  63694. #endif
  63695. #ifdef EACCES
  63696. case EACCES: return DRWAV_ACCESS_DENIED;
  63697. #endif
  63698. #ifdef EFAULT
  63699. case EFAULT: return DRWAV_BAD_ADDRESS;
  63700. #endif
  63701. #ifdef ENOTBLK
  63702. case ENOTBLK: return DRWAV_ERROR;
  63703. #endif
  63704. #ifdef EBUSY
  63705. case EBUSY: return DRWAV_BUSY;
  63706. #endif
  63707. #ifdef EEXIST
  63708. case EEXIST: return DRWAV_ALREADY_EXISTS;
  63709. #endif
  63710. #ifdef EXDEV
  63711. case EXDEV: return DRWAV_ERROR;
  63712. #endif
  63713. #ifdef ENODEV
  63714. case ENODEV: return DRWAV_DOES_NOT_EXIST;
  63715. #endif
  63716. #ifdef ENOTDIR
  63717. case ENOTDIR: return DRWAV_NOT_DIRECTORY;
  63718. #endif
  63719. #ifdef EISDIR
  63720. case EISDIR: return DRWAV_IS_DIRECTORY;
  63721. #endif
  63722. #ifdef EINVAL
  63723. case EINVAL: return DRWAV_INVALID_ARGS;
  63724. #endif
  63725. #ifdef ENFILE
  63726. case ENFILE: return DRWAV_TOO_MANY_OPEN_FILES;
  63727. #endif
  63728. #ifdef EMFILE
  63729. case EMFILE: return DRWAV_TOO_MANY_OPEN_FILES;
  63730. #endif
  63731. #ifdef ENOTTY
  63732. case ENOTTY: return DRWAV_INVALID_OPERATION;
  63733. #endif
  63734. #ifdef ETXTBSY
  63735. case ETXTBSY: return DRWAV_BUSY;
  63736. #endif
  63737. #ifdef EFBIG
  63738. case EFBIG: return DRWAV_TOO_BIG;
  63739. #endif
  63740. #ifdef ENOSPC
  63741. case ENOSPC: return DRWAV_NO_SPACE;
  63742. #endif
  63743. #ifdef ESPIPE
  63744. case ESPIPE: return DRWAV_BAD_SEEK;
  63745. #endif
  63746. #ifdef EROFS
  63747. case EROFS: return DRWAV_ACCESS_DENIED;
  63748. #endif
  63749. #ifdef EMLINK
  63750. case EMLINK: return DRWAV_TOO_MANY_LINKS;
  63751. #endif
  63752. #ifdef EPIPE
  63753. case EPIPE: return DRWAV_BAD_PIPE;
  63754. #endif
  63755. #ifdef EDOM
  63756. case EDOM: return DRWAV_OUT_OF_RANGE;
  63757. #endif
  63758. #ifdef ERANGE
  63759. case ERANGE: return DRWAV_OUT_OF_RANGE;
  63760. #endif
  63761. #ifdef EDEADLK
  63762. case EDEADLK: return DRWAV_DEADLOCK;
  63763. #endif
  63764. #ifdef ENAMETOOLONG
  63765. case ENAMETOOLONG: return DRWAV_PATH_TOO_LONG;
  63766. #endif
  63767. #ifdef ENOLCK
  63768. case ENOLCK: return DRWAV_ERROR;
  63769. #endif
  63770. #ifdef ENOSYS
  63771. case ENOSYS: return DRWAV_NOT_IMPLEMENTED;
  63772. #endif
  63773. #ifdef ENOTEMPTY
  63774. case ENOTEMPTY: return DRWAV_DIRECTORY_NOT_EMPTY;
  63775. #endif
  63776. #ifdef ELOOP
  63777. case ELOOP: return DRWAV_TOO_MANY_LINKS;
  63778. #endif
  63779. #ifdef ENOMSG
  63780. case ENOMSG: return DRWAV_NO_MESSAGE;
  63781. #endif
  63782. #ifdef EIDRM
  63783. case EIDRM: return DRWAV_ERROR;
  63784. #endif
  63785. #ifdef ECHRNG
  63786. case ECHRNG: return DRWAV_ERROR;
  63787. #endif
  63788. #ifdef EL2NSYNC
  63789. case EL2NSYNC: return DRWAV_ERROR;
  63790. #endif
  63791. #ifdef EL3HLT
  63792. case EL3HLT: return DRWAV_ERROR;
  63793. #endif
  63794. #ifdef EL3RST
  63795. case EL3RST: return DRWAV_ERROR;
  63796. #endif
  63797. #ifdef ELNRNG
  63798. case ELNRNG: return DRWAV_OUT_OF_RANGE;
  63799. #endif
  63800. #ifdef EUNATCH
  63801. case EUNATCH: return DRWAV_ERROR;
  63802. #endif
  63803. #ifdef ENOCSI
  63804. case ENOCSI: return DRWAV_ERROR;
  63805. #endif
  63806. #ifdef EL2HLT
  63807. case EL2HLT: return DRWAV_ERROR;
  63808. #endif
  63809. #ifdef EBADE
  63810. case EBADE: return DRWAV_ERROR;
  63811. #endif
  63812. #ifdef EBADR
  63813. case EBADR: return DRWAV_ERROR;
  63814. #endif
  63815. #ifdef EXFULL
  63816. case EXFULL: return DRWAV_ERROR;
  63817. #endif
  63818. #ifdef ENOANO
  63819. case ENOANO: return DRWAV_ERROR;
  63820. #endif
  63821. #ifdef EBADRQC
  63822. case EBADRQC: return DRWAV_ERROR;
  63823. #endif
  63824. #ifdef EBADSLT
  63825. case EBADSLT: return DRWAV_ERROR;
  63826. #endif
  63827. #ifdef EBFONT
  63828. case EBFONT: return DRWAV_INVALID_FILE;
  63829. #endif
  63830. #ifdef ENOSTR
  63831. case ENOSTR: return DRWAV_ERROR;
  63832. #endif
  63833. #ifdef ENODATA
  63834. case ENODATA: return DRWAV_NO_DATA_AVAILABLE;
  63835. #endif
  63836. #ifdef ETIME
  63837. case ETIME: return DRWAV_TIMEOUT;
  63838. #endif
  63839. #ifdef ENOSR
  63840. case ENOSR: return DRWAV_NO_DATA_AVAILABLE;
  63841. #endif
  63842. #ifdef ENONET
  63843. case ENONET: return DRWAV_NO_NETWORK;
  63844. #endif
  63845. #ifdef ENOPKG
  63846. case ENOPKG: return DRWAV_ERROR;
  63847. #endif
  63848. #ifdef EREMOTE
  63849. case EREMOTE: return DRWAV_ERROR;
  63850. #endif
  63851. #ifdef ENOLINK
  63852. case ENOLINK: return DRWAV_ERROR;
  63853. #endif
  63854. #ifdef EADV
  63855. case EADV: return DRWAV_ERROR;
  63856. #endif
  63857. #ifdef ESRMNT
  63858. case ESRMNT: return DRWAV_ERROR;
  63859. #endif
  63860. #ifdef ECOMM
  63861. case ECOMM: return DRWAV_ERROR;
  63862. #endif
  63863. #ifdef EPROTO
  63864. case EPROTO: return DRWAV_ERROR;
  63865. #endif
  63866. #ifdef EMULTIHOP
  63867. case EMULTIHOP: return DRWAV_ERROR;
  63868. #endif
  63869. #ifdef EDOTDOT
  63870. case EDOTDOT: return DRWAV_ERROR;
  63871. #endif
  63872. #ifdef EBADMSG
  63873. case EBADMSG: return DRWAV_BAD_MESSAGE;
  63874. #endif
  63875. #ifdef EOVERFLOW
  63876. case EOVERFLOW: return DRWAV_TOO_BIG;
  63877. #endif
  63878. #ifdef ENOTUNIQ
  63879. case ENOTUNIQ: return DRWAV_NOT_UNIQUE;
  63880. #endif
  63881. #ifdef EBADFD
  63882. case EBADFD: return DRWAV_ERROR;
  63883. #endif
  63884. #ifdef EREMCHG
  63885. case EREMCHG: return DRWAV_ERROR;
  63886. #endif
  63887. #ifdef ELIBACC
  63888. case ELIBACC: return DRWAV_ACCESS_DENIED;
  63889. #endif
  63890. #ifdef ELIBBAD
  63891. case ELIBBAD: return DRWAV_INVALID_FILE;
  63892. #endif
  63893. #ifdef ELIBSCN
  63894. case ELIBSCN: return DRWAV_INVALID_FILE;
  63895. #endif
  63896. #ifdef ELIBMAX
  63897. case ELIBMAX: return DRWAV_ERROR;
  63898. #endif
  63899. #ifdef ELIBEXEC
  63900. case ELIBEXEC: return DRWAV_ERROR;
  63901. #endif
  63902. #ifdef EILSEQ
  63903. case EILSEQ: return DRWAV_INVALID_DATA;
  63904. #endif
  63905. #ifdef ERESTART
  63906. case ERESTART: return DRWAV_ERROR;
  63907. #endif
  63908. #ifdef ESTRPIPE
  63909. case ESTRPIPE: return DRWAV_ERROR;
  63910. #endif
  63911. #ifdef EUSERS
  63912. case EUSERS: return DRWAV_ERROR;
  63913. #endif
  63914. #ifdef ENOTSOCK
  63915. case ENOTSOCK: return DRWAV_NOT_SOCKET;
  63916. #endif
  63917. #ifdef EDESTADDRREQ
  63918. case EDESTADDRREQ: return DRWAV_NO_ADDRESS;
  63919. #endif
  63920. #ifdef EMSGSIZE
  63921. case EMSGSIZE: return DRWAV_TOO_BIG;
  63922. #endif
  63923. #ifdef EPROTOTYPE
  63924. case EPROTOTYPE: return DRWAV_BAD_PROTOCOL;
  63925. #endif
  63926. #ifdef ENOPROTOOPT
  63927. case ENOPROTOOPT: return DRWAV_PROTOCOL_UNAVAILABLE;
  63928. #endif
  63929. #ifdef EPROTONOSUPPORT
  63930. case EPROTONOSUPPORT: return DRWAV_PROTOCOL_NOT_SUPPORTED;
  63931. #endif
  63932. #ifdef ESOCKTNOSUPPORT
  63933. case ESOCKTNOSUPPORT: return DRWAV_SOCKET_NOT_SUPPORTED;
  63934. #endif
  63935. #ifdef EOPNOTSUPP
  63936. case EOPNOTSUPP: return DRWAV_INVALID_OPERATION;
  63937. #endif
  63938. #ifdef EPFNOSUPPORT
  63939. case EPFNOSUPPORT: return DRWAV_PROTOCOL_FAMILY_NOT_SUPPORTED;
  63940. #endif
  63941. #ifdef EAFNOSUPPORT
  63942. case EAFNOSUPPORT: return DRWAV_ADDRESS_FAMILY_NOT_SUPPORTED;
  63943. #endif
  63944. #ifdef EADDRINUSE
  63945. case EADDRINUSE: return DRWAV_ALREADY_IN_USE;
  63946. #endif
  63947. #ifdef EADDRNOTAVAIL
  63948. case EADDRNOTAVAIL: return DRWAV_ERROR;
  63949. #endif
  63950. #ifdef ENETDOWN
  63951. case ENETDOWN: return DRWAV_NO_NETWORK;
  63952. #endif
  63953. #ifdef ENETUNREACH
  63954. case ENETUNREACH: return DRWAV_NO_NETWORK;
  63955. #endif
  63956. #ifdef ENETRESET
  63957. case ENETRESET: return DRWAV_NO_NETWORK;
  63958. #endif
  63959. #ifdef ECONNABORTED
  63960. case ECONNABORTED: return DRWAV_NO_NETWORK;
  63961. #endif
  63962. #ifdef ECONNRESET
  63963. case ECONNRESET: return DRWAV_CONNECTION_RESET;
  63964. #endif
  63965. #ifdef ENOBUFS
  63966. case ENOBUFS: return DRWAV_NO_SPACE;
  63967. #endif
  63968. #ifdef EISCONN
  63969. case EISCONN: return DRWAV_ALREADY_CONNECTED;
  63970. #endif
  63971. #ifdef ENOTCONN
  63972. case ENOTCONN: return DRWAV_NOT_CONNECTED;
  63973. #endif
  63974. #ifdef ESHUTDOWN
  63975. case ESHUTDOWN: return DRWAV_ERROR;
  63976. #endif
  63977. #ifdef ETOOMANYREFS
  63978. case ETOOMANYREFS: return DRWAV_ERROR;
  63979. #endif
  63980. #ifdef ETIMEDOUT
  63981. case ETIMEDOUT: return DRWAV_TIMEOUT;
  63982. #endif
  63983. #ifdef ECONNREFUSED
  63984. case ECONNREFUSED: return DRWAV_CONNECTION_REFUSED;
  63985. #endif
  63986. #ifdef EHOSTDOWN
  63987. case EHOSTDOWN: return DRWAV_NO_HOST;
  63988. #endif
  63989. #ifdef EHOSTUNREACH
  63990. case EHOSTUNREACH: return DRWAV_NO_HOST;
  63991. #endif
  63992. #ifdef EALREADY
  63993. case EALREADY: return DRWAV_IN_PROGRESS;
  63994. #endif
  63995. #ifdef EINPROGRESS
  63996. case EINPROGRESS: return DRWAV_IN_PROGRESS;
  63997. #endif
  63998. #ifdef ESTALE
  63999. case ESTALE: return DRWAV_INVALID_FILE;
  64000. #endif
  64001. #ifdef EUCLEAN
  64002. case EUCLEAN: return DRWAV_ERROR;
  64003. #endif
  64004. #ifdef ENOTNAM
  64005. case ENOTNAM: return DRWAV_ERROR;
  64006. #endif
  64007. #ifdef ENAVAIL
  64008. case ENAVAIL: return DRWAV_ERROR;
  64009. #endif
  64010. #ifdef EISNAM
  64011. case EISNAM: return DRWAV_ERROR;
  64012. #endif
  64013. #ifdef EREMOTEIO
  64014. case EREMOTEIO: return DRWAV_IO_ERROR;
  64015. #endif
  64016. #ifdef EDQUOT
  64017. case EDQUOT: return DRWAV_NO_SPACE;
  64018. #endif
  64019. #ifdef ENOMEDIUM
  64020. case ENOMEDIUM: return DRWAV_DOES_NOT_EXIST;
  64021. #endif
  64022. #ifdef EMEDIUMTYPE
  64023. case EMEDIUMTYPE: return DRWAV_ERROR;
  64024. #endif
  64025. #ifdef ECANCELED
  64026. case ECANCELED: return DRWAV_CANCELLED;
  64027. #endif
  64028. #ifdef ENOKEY
  64029. case ENOKEY: return DRWAV_ERROR;
  64030. #endif
  64031. #ifdef EKEYEXPIRED
  64032. case EKEYEXPIRED: return DRWAV_ERROR;
  64033. #endif
  64034. #ifdef EKEYREVOKED
  64035. case EKEYREVOKED: return DRWAV_ERROR;
  64036. #endif
  64037. #ifdef EKEYREJECTED
  64038. case EKEYREJECTED: return DRWAV_ERROR;
  64039. #endif
  64040. #ifdef EOWNERDEAD
  64041. case EOWNERDEAD: return DRWAV_ERROR;
  64042. #endif
  64043. #ifdef ENOTRECOVERABLE
  64044. case ENOTRECOVERABLE: return DRWAV_ERROR;
  64045. #endif
  64046. #ifdef ERFKILL
  64047. case ERFKILL: return DRWAV_ERROR;
  64048. #endif
  64049. #ifdef EHWPOISON
  64050. case EHWPOISON: return DRWAV_ERROR;
  64051. #endif
  64052. default: return DRWAV_ERROR;
  64053. }
  64054. }
  64055. DRWAV_PRIVATE drwav_result drwav_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  64056. {
  64057. #if defined(_MSC_VER) && _MSC_VER >= 1400
  64058. errno_t err;
  64059. #endif
  64060. if (ppFile != NULL) {
  64061. *ppFile = NULL;
  64062. }
  64063. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  64064. return DRWAV_INVALID_ARGS;
  64065. }
  64066. #if defined(_MSC_VER) && _MSC_VER >= 1400
  64067. err = fopen_s(ppFile, pFilePath, pOpenMode);
  64068. if (err != 0) {
  64069. return drwav_result_from_errno(err);
  64070. }
  64071. #else
  64072. #if defined(_WIN32) || defined(__APPLE__)
  64073. *ppFile = fopen(pFilePath, pOpenMode);
  64074. #else
  64075. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  64076. *ppFile = fopen64(pFilePath, pOpenMode);
  64077. #else
  64078. *ppFile = fopen(pFilePath, pOpenMode);
  64079. #endif
  64080. #endif
  64081. if (*ppFile == NULL) {
  64082. drwav_result result = drwav_result_from_errno(errno);
  64083. if (result == DRWAV_SUCCESS) {
  64084. result = DRWAV_ERROR;
  64085. }
  64086. return result;
  64087. }
  64088. #endif
  64089. return DRWAV_SUCCESS;
  64090. }
  64091. #if defined(_WIN32)
  64092. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  64093. #define DRWAV_HAS_WFOPEN
  64094. #endif
  64095. #endif
  64096. #ifndef DR_WAV_NO_WCHAR
  64097. DRWAV_PRIVATE drwav_result drwav_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drwav_allocation_callbacks* pAllocationCallbacks)
  64098. {
  64099. if (ppFile != NULL) {
  64100. *ppFile = NULL;
  64101. }
  64102. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  64103. return DRWAV_INVALID_ARGS;
  64104. }
  64105. #if defined(DRWAV_HAS_WFOPEN)
  64106. {
  64107. #if defined(_MSC_VER) && _MSC_VER >= 1400
  64108. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  64109. if (err != 0) {
  64110. return drwav_result_from_errno(err);
  64111. }
  64112. #else
  64113. *ppFile = _wfopen(pFilePath, pOpenMode);
  64114. if (*ppFile == NULL) {
  64115. return drwav_result_from_errno(errno);
  64116. }
  64117. #endif
  64118. (void)pAllocationCallbacks;
  64119. }
  64120. #else
  64121. #if defined(__DJGPP__)
  64122. {
  64123. }
  64124. #else
  64125. {
  64126. mbstate_t mbs;
  64127. size_t lenMB;
  64128. const wchar_t* pFilePathTemp = pFilePath;
  64129. char* pFilePathMB = NULL;
  64130. char pOpenModeMB[32] = {0};
  64131. DRWAV_ZERO_OBJECT(&mbs);
  64132. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  64133. if (lenMB == (size_t)-1) {
  64134. return drwav_result_from_errno(errno);
  64135. }
  64136. pFilePathMB = (char*)drwav__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  64137. if (pFilePathMB == NULL) {
  64138. return DRWAV_OUT_OF_MEMORY;
  64139. }
  64140. pFilePathTemp = pFilePath;
  64141. DRWAV_ZERO_OBJECT(&mbs);
  64142. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  64143. {
  64144. size_t i = 0;
  64145. for (;;) {
  64146. if (pOpenMode[i] == 0) {
  64147. pOpenModeMB[i] = '\0';
  64148. break;
  64149. }
  64150. pOpenModeMB[i] = (char)pOpenMode[i];
  64151. i += 1;
  64152. }
  64153. }
  64154. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  64155. drwav__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  64156. }
  64157. #endif
  64158. if (*ppFile == NULL) {
  64159. return DRWAV_ERROR;
  64160. }
  64161. #endif
  64162. return DRWAV_SUCCESS;
  64163. }
  64164. #endif
  64165. DRWAV_PRIVATE size_t drwav__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  64166. {
  64167. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  64168. }
  64169. DRWAV_PRIVATE size_t drwav__on_write_stdio(void* pUserData, const void* pData, size_t bytesToWrite)
  64170. {
  64171. return fwrite(pData, 1, bytesToWrite, (FILE*)pUserData);
  64172. }
  64173. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_stdio(void* pUserData, int offset, drwav_seek_origin origin)
  64174. {
  64175. return fseek((FILE*)pUserData, offset, (origin == drwav_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  64176. }
  64177. DRWAV_API drwav_bool32 drwav_init_file(drwav* pWav, const char* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
  64178. {
  64179. return drwav_init_file_ex(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  64180. }
  64181. DRWAV_PRIVATE drwav_bool32 drwav_init_file__internal_FILE(drwav* pWav, FILE* pFile, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, drwav_metadata_type allowedMetadataTypes, const drwav_allocation_callbacks* pAllocationCallbacks)
  64182. {
  64183. drwav_bool32 result;
  64184. result = drwav_preinit(pWav, drwav__on_read_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  64185. if (result != DRWAV_TRUE) {
  64186. fclose(pFile);
  64187. return result;
  64188. }
  64189. pWav->allowedMetadataTypes = allowedMetadataTypes;
  64190. result = drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  64191. if (result != DRWAV_TRUE) {
  64192. fclose(pFile);
  64193. return result;
  64194. }
  64195. return DRWAV_TRUE;
  64196. }
  64197. DRWAV_API drwav_bool32 drwav_init_file_ex(drwav* pWav, const char* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64198. {
  64199. FILE* pFile;
  64200. if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
  64201. return DRWAV_FALSE;
  64202. }
  64203. return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks);
  64204. }
  64205. #ifndef DR_WAV_NO_WCHAR
  64206. DRWAV_API drwav_bool32 drwav_init_file_w(drwav* pWav, const wchar_t* filename, const drwav_allocation_callbacks* pAllocationCallbacks)
  64207. {
  64208. return drwav_init_file_ex_w(pWav, filename, NULL, NULL, 0, pAllocationCallbacks);
  64209. }
  64210. DRWAV_API drwav_bool32 drwav_init_file_ex_w(drwav* pWav, const wchar_t* filename, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64211. {
  64212. FILE* pFile;
  64213. if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  64214. return DRWAV_FALSE;
  64215. }
  64216. return drwav_init_file__internal_FILE(pWav, pFile, onChunk, pChunkUserData, flags, drwav_metadata_type_none, pAllocationCallbacks);
  64217. }
  64218. #endif
  64219. DRWAV_API drwav_bool32 drwav_init_file_with_metadata(drwav* pWav, const char* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64220. {
  64221. FILE* pFile;
  64222. if (drwav_fopen(&pFile, filename, "rb") != DRWAV_SUCCESS) {
  64223. return DRWAV_FALSE;
  64224. }
  64225. return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks);
  64226. }
  64227. #ifndef DR_WAV_NO_WCHAR
  64228. DRWAV_API drwav_bool32 drwav_init_file_with_metadata_w(drwav* pWav, const wchar_t* filename, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64229. {
  64230. FILE* pFile;
  64231. if (drwav_wfopen(&pFile, filename, L"rb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  64232. return DRWAV_FALSE;
  64233. }
  64234. return drwav_init_file__internal_FILE(pWav, pFile, NULL, NULL, flags, drwav_metadata_type_all_including_unknown, pAllocationCallbacks);
  64235. }
  64236. #endif
  64237. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal_FILE(drwav* pWav, FILE* pFile, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  64238. {
  64239. drwav_bool32 result;
  64240. result = drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_stdio, drwav__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  64241. if (result != DRWAV_TRUE) {
  64242. fclose(pFile);
  64243. return result;
  64244. }
  64245. result = drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  64246. if (result != DRWAV_TRUE) {
  64247. fclose(pFile);
  64248. return result;
  64249. }
  64250. return DRWAV_TRUE;
  64251. }
  64252. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write__internal(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  64253. {
  64254. FILE* pFile;
  64255. if (drwav_fopen(&pFile, filename, "wb") != DRWAV_SUCCESS) {
  64256. return DRWAV_FALSE;
  64257. }
  64258. return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  64259. }
  64260. #ifndef DR_WAV_NO_WCHAR
  64261. DRWAV_PRIVATE drwav_bool32 drwav_init_file_write_w__internal(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  64262. {
  64263. FILE* pFile;
  64264. if (drwav_wfopen(&pFile, filename, L"wb", pAllocationCallbacks) != DRWAV_SUCCESS) {
  64265. return DRWAV_FALSE;
  64266. }
  64267. return drwav_init_file_write__internal_FILE(pWav, pFile, pFormat, totalSampleCount, isSequential, pAllocationCallbacks);
  64268. }
  64269. #endif
  64270. DRWAV_API drwav_bool32 drwav_init_file_write(drwav* pWav, const char* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  64271. {
  64272. return drwav_init_file_write__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  64273. }
  64274. DRWAV_API drwav_bool32 drwav_init_file_write_sequential(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64275. {
  64276. return drwav_init_file_write__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  64277. }
  64278. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames(drwav* pWav, const char* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64279. {
  64280. if (pFormat == NULL) {
  64281. return DRWAV_FALSE;
  64282. }
  64283. return drwav_init_file_write_sequential(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  64284. }
  64285. #ifndef DR_WAV_NO_WCHAR
  64286. DRWAV_API drwav_bool32 drwav_init_file_write_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  64287. {
  64288. return drwav_init_file_write_w__internal(pWav, filename, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  64289. }
  64290. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64291. {
  64292. return drwav_init_file_write_w__internal(pWav, filename, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  64293. }
  64294. DRWAV_API drwav_bool32 drwav_init_file_write_sequential_pcm_frames_w(drwav* pWav, const wchar_t* filename, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64295. {
  64296. if (pFormat == NULL) {
  64297. return DRWAV_FALSE;
  64298. }
  64299. return drwav_init_file_write_sequential_w(pWav, filename, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  64300. }
  64301. #endif
  64302. #endif
  64303. DRWAV_PRIVATE size_t drwav__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  64304. {
  64305. drwav* pWav = (drwav*)pUserData;
  64306. size_t bytesRemaining;
  64307. DRWAV_ASSERT(pWav != NULL);
  64308. DRWAV_ASSERT(pWav->memoryStream.dataSize >= pWav->memoryStream.currentReadPos);
  64309. bytesRemaining = pWav->memoryStream.dataSize - pWav->memoryStream.currentReadPos;
  64310. if (bytesToRead > bytesRemaining) {
  64311. bytesToRead = bytesRemaining;
  64312. }
  64313. if (bytesToRead > 0) {
  64314. DRWAV_COPY_MEMORY(pBufferOut, pWav->memoryStream.data + pWav->memoryStream.currentReadPos, bytesToRead);
  64315. pWav->memoryStream.currentReadPos += bytesToRead;
  64316. }
  64317. return bytesToRead;
  64318. }
  64319. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory(void* pUserData, int offset, drwav_seek_origin origin)
  64320. {
  64321. drwav* pWav = (drwav*)pUserData;
  64322. DRWAV_ASSERT(pWav != NULL);
  64323. if (origin == drwav_seek_origin_current) {
  64324. if (offset > 0) {
  64325. if (pWav->memoryStream.currentReadPos + offset > pWav->memoryStream.dataSize) {
  64326. return DRWAV_FALSE;
  64327. }
  64328. } else {
  64329. if (pWav->memoryStream.currentReadPos < (size_t)-offset) {
  64330. return DRWAV_FALSE;
  64331. }
  64332. }
  64333. pWav->memoryStream.currentReadPos += offset;
  64334. } else {
  64335. if ((drwav_uint32)offset <= pWav->memoryStream.dataSize) {
  64336. pWav->memoryStream.currentReadPos = offset;
  64337. } else {
  64338. return DRWAV_FALSE;
  64339. }
  64340. }
  64341. return DRWAV_TRUE;
  64342. }
  64343. DRWAV_PRIVATE size_t drwav__on_write_memory(void* pUserData, const void* pDataIn, size_t bytesToWrite)
  64344. {
  64345. drwav* pWav = (drwav*)pUserData;
  64346. size_t bytesRemaining;
  64347. DRWAV_ASSERT(pWav != NULL);
  64348. DRWAV_ASSERT(pWav->memoryStreamWrite.dataCapacity >= pWav->memoryStreamWrite.currentWritePos);
  64349. bytesRemaining = pWav->memoryStreamWrite.dataCapacity - pWav->memoryStreamWrite.currentWritePos;
  64350. if (bytesRemaining < bytesToWrite) {
  64351. void* pNewData;
  64352. size_t newDataCapacity = (pWav->memoryStreamWrite.dataCapacity == 0) ? 256 : pWav->memoryStreamWrite.dataCapacity * 2;
  64353. if ((newDataCapacity - pWav->memoryStreamWrite.currentWritePos) < bytesToWrite) {
  64354. newDataCapacity = pWav->memoryStreamWrite.currentWritePos + bytesToWrite;
  64355. }
  64356. pNewData = drwav__realloc_from_callbacks(*pWav->memoryStreamWrite.ppData, newDataCapacity, pWav->memoryStreamWrite.dataCapacity, &pWav->allocationCallbacks);
  64357. if (pNewData == NULL) {
  64358. return 0;
  64359. }
  64360. *pWav->memoryStreamWrite.ppData = pNewData;
  64361. pWav->memoryStreamWrite.dataCapacity = newDataCapacity;
  64362. }
  64363. DRWAV_COPY_MEMORY(((drwav_uint8*)(*pWav->memoryStreamWrite.ppData)) + pWav->memoryStreamWrite.currentWritePos, pDataIn, bytesToWrite);
  64364. pWav->memoryStreamWrite.currentWritePos += bytesToWrite;
  64365. if (pWav->memoryStreamWrite.dataSize < pWav->memoryStreamWrite.currentWritePos) {
  64366. pWav->memoryStreamWrite.dataSize = pWav->memoryStreamWrite.currentWritePos;
  64367. }
  64368. *pWav->memoryStreamWrite.pDataSize = pWav->memoryStreamWrite.dataSize;
  64369. return bytesToWrite;
  64370. }
  64371. DRWAV_PRIVATE drwav_bool32 drwav__on_seek_memory_write(void* pUserData, int offset, drwav_seek_origin origin)
  64372. {
  64373. drwav* pWav = (drwav*)pUserData;
  64374. DRWAV_ASSERT(pWav != NULL);
  64375. if (origin == drwav_seek_origin_current) {
  64376. if (offset > 0) {
  64377. if (pWav->memoryStreamWrite.currentWritePos + offset > pWav->memoryStreamWrite.dataSize) {
  64378. offset = (int)(pWav->memoryStreamWrite.dataSize - pWav->memoryStreamWrite.currentWritePos);
  64379. }
  64380. } else {
  64381. if (pWav->memoryStreamWrite.currentWritePos < (size_t)-offset) {
  64382. offset = -(int)pWav->memoryStreamWrite.currentWritePos;
  64383. }
  64384. }
  64385. pWav->memoryStreamWrite.currentWritePos += offset;
  64386. } else {
  64387. if ((drwav_uint32)offset <= pWav->memoryStreamWrite.dataSize) {
  64388. pWav->memoryStreamWrite.currentWritePos = offset;
  64389. } else {
  64390. pWav->memoryStreamWrite.currentWritePos = pWav->memoryStreamWrite.dataSize;
  64391. }
  64392. }
  64393. return DRWAV_TRUE;
  64394. }
  64395. DRWAV_API drwav_bool32 drwav_init_memory(drwav* pWav, const void* data, size_t dataSize, const drwav_allocation_callbacks* pAllocationCallbacks)
  64396. {
  64397. return drwav_init_memory_ex(pWav, data, dataSize, NULL, NULL, 0, pAllocationCallbacks);
  64398. }
  64399. DRWAV_API drwav_bool32 drwav_init_memory_ex(drwav* pWav, const void* data, size_t dataSize, drwav_chunk_proc onChunk, void* pChunkUserData, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64400. {
  64401. if (data == NULL || dataSize == 0) {
  64402. return DRWAV_FALSE;
  64403. }
  64404. if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, pWav, pAllocationCallbacks)) {
  64405. return DRWAV_FALSE;
  64406. }
  64407. pWav->memoryStream.data = (const drwav_uint8*)data;
  64408. pWav->memoryStream.dataSize = dataSize;
  64409. pWav->memoryStream.currentReadPos = 0;
  64410. return drwav_init__internal(pWav, onChunk, pChunkUserData, flags);
  64411. }
  64412. DRWAV_API drwav_bool32 drwav_init_memory_with_metadata(drwav* pWav, const void* data, size_t dataSize, drwav_uint32 flags, const drwav_allocation_callbacks* pAllocationCallbacks)
  64413. {
  64414. if (data == NULL || dataSize == 0) {
  64415. return DRWAV_FALSE;
  64416. }
  64417. if (!drwav_preinit(pWav, drwav__on_read_memory, drwav__on_seek_memory, pWav, pAllocationCallbacks)) {
  64418. return DRWAV_FALSE;
  64419. }
  64420. pWav->memoryStream.data = (const drwav_uint8*)data;
  64421. pWav->memoryStream.dataSize = dataSize;
  64422. pWav->memoryStream.currentReadPos = 0;
  64423. pWav->allowedMetadataTypes = drwav_metadata_type_all_including_unknown;
  64424. return drwav_init__internal(pWav, NULL, NULL, flags);
  64425. }
  64426. DRWAV_PRIVATE drwav_bool32 drwav_init_memory_write__internal(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, drwav_bool32 isSequential, const drwav_allocation_callbacks* pAllocationCallbacks)
  64427. {
  64428. if (ppData == NULL || pDataSize == NULL) {
  64429. return DRWAV_FALSE;
  64430. }
  64431. *ppData = NULL;
  64432. *pDataSize = 0;
  64433. if (!drwav_preinit_write(pWav, pFormat, isSequential, drwav__on_write_memory, drwav__on_seek_memory_write, pWav, pAllocationCallbacks)) {
  64434. return DRWAV_FALSE;
  64435. }
  64436. pWav->memoryStreamWrite.ppData = ppData;
  64437. pWav->memoryStreamWrite.pDataSize = pDataSize;
  64438. pWav->memoryStreamWrite.dataSize = 0;
  64439. pWav->memoryStreamWrite.dataCapacity = 0;
  64440. pWav->memoryStreamWrite.currentWritePos = 0;
  64441. return drwav_init_write__internal(pWav, pFormat, totalSampleCount);
  64442. }
  64443. DRWAV_API drwav_bool32 drwav_init_memory_write(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, const drwav_allocation_callbacks* pAllocationCallbacks)
  64444. {
  64445. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, 0, DRWAV_FALSE, pAllocationCallbacks);
  64446. }
  64447. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalSampleCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64448. {
  64449. return drwav_init_memory_write__internal(pWav, ppData, pDataSize, pFormat, totalSampleCount, DRWAV_TRUE, pAllocationCallbacks);
  64450. }
  64451. DRWAV_API drwav_bool32 drwav_init_memory_write_sequential_pcm_frames(drwav* pWav, void** ppData, size_t* pDataSize, const drwav_data_format* pFormat, drwav_uint64 totalPCMFrameCount, const drwav_allocation_callbacks* pAllocationCallbacks)
  64452. {
  64453. if (pFormat == NULL) {
  64454. return DRWAV_FALSE;
  64455. }
  64456. return drwav_init_memory_write_sequential(pWav, ppData, pDataSize, pFormat, totalPCMFrameCount*pFormat->channels, pAllocationCallbacks);
  64457. }
  64458. DRWAV_API drwav_result drwav_uninit(drwav* pWav)
  64459. {
  64460. drwav_result result = DRWAV_SUCCESS;
  64461. if (pWav == NULL) {
  64462. return DRWAV_INVALID_ARGS;
  64463. }
  64464. if (pWav->onWrite != NULL) {
  64465. drwav_uint32 paddingSize = 0;
  64466. if (pWav->container == drwav_container_riff || pWav->container == drwav_container_rf64) {
  64467. paddingSize = drwav__chunk_padding_size_riff(pWav->dataChunkDataSize);
  64468. } else {
  64469. paddingSize = drwav__chunk_padding_size_w64(pWav->dataChunkDataSize);
  64470. }
  64471. if (paddingSize > 0) {
  64472. drwav_uint64 paddingData = 0;
  64473. drwav__write(pWav, &paddingData, paddingSize);
  64474. }
  64475. if (pWav->onSeek && !pWav->isSequentialWrite) {
  64476. if (pWav->container == drwav_container_riff) {
  64477. if (pWav->onSeek(pWav->pUserData, 4, drwav_seek_origin_start)) {
  64478. drwav_uint32 riffChunkSize = drwav__riff_chunk_size_riff(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  64479. drwav__write_u32ne_to_le(pWav, riffChunkSize);
  64480. }
  64481. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 4, drwav_seek_origin_start)) {
  64482. drwav_uint32 dataChunkSize = drwav__data_chunk_size_riff(pWav->dataChunkDataSize);
  64483. drwav__write_u32ne_to_le(pWav, dataChunkSize);
  64484. }
  64485. } else if (pWav->container == drwav_container_w64) {
  64486. if (pWav->onSeek(pWav->pUserData, 16, drwav_seek_origin_start)) {
  64487. drwav_uint64 riffChunkSize = drwav__riff_chunk_size_w64(pWav->dataChunkDataSize);
  64488. drwav__write_u64ne_to_le(pWav, riffChunkSize);
  64489. }
  64490. if (pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos - 8, drwav_seek_origin_start)) {
  64491. drwav_uint64 dataChunkSize = drwav__data_chunk_size_w64(pWav->dataChunkDataSize);
  64492. drwav__write_u64ne_to_le(pWav, dataChunkSize);
  64493. }
  64494. } else if (pWav->container == drwav_container_rf64) {
  64495. int ds64BodyPos = 12 + 8;
  64496. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 0, drwav_seek_origin_start)) {
  64497. drwav_uint64 riffChunkSize = drwav__riff_chunk_size_rf64(pWav->dataChunkDataSize, pWav->pMetadata, pWav->metadataCount);
  64498. drwav__write_u64ne_to_le(pWav, riffChunkSize);
  64499. }
  64500. if (pWav->onSeek(pWav->pUserData, ds64BodyPos + 8, drwav_seek_origin_start)) {
  64501. drwav_uint64 dataChunkSize = drwav__data_chunk_size_rf64(pWav->dataChunkDataSize);
  64502. drwav__write_u64ne_to_le(pWav, dataChunkSize);
  64503. }
  64504. }
  64505. }
  64506. if (pWav->isSequentialWrite) {
  64507. if (pWav->dataChunkDataSize != pWav->dataChunkDataSizeTargetWrite) {
  64508. result = DRWAV_INVALID_FILE;
  64509. }
  64510. }
  64511. } else {
  64512. if (pWav->pMetadata != NULL) {
  64513. pWav->allocationCallbacks.onFree(pWav->pMetadata, pWav->allocationCallbacks.pUserData);
  64514. }
  64515. }
  64516. #ifndef DR_WAV_NO_STDIO
  64517. if (pWav->onRead == drwav__on_read_stdio || pWav->onWrite == drwav__on_write_stdio) {
  64518. fclose((FILE*)pWav->pUserData);
  64519. }
  64520. #endif
  64521. return result;
  64522. }
  64523. DRWAV_API size_t drwav_read_raw(drwav* pWav, size_t bytesToRead, void* pBufferOut)
  64524. {
  64525. size_t bytesRead;
  64526. drwav_uint32 bytesPerFrame;
  64527. if (pWav == NULL || bytesToRead == 0) {
  64528. return 0;
  64529. }
  64530. if (bytesToRead > pWav->bytesRemaining) {
  64531. bytesToRead = (size_t)pWav->bytesRemaining;
  64532. }
  64533. if (bytesToRead == 0) {
  64534. return 0;
  64535. }
  64536. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  64537. if (bytesPerFrame == 0) {
  64538. return 0;
  64539. }
  64540. if (pBufferOut != NULL) {
  64541. bytesRead = pWav->onRead(pWav->pUserData, pBufferOut, bytesToRead);
  64542. } else {
  64543. bytesRead = 0;
  64544. while (bytesRead < bytesToRead) {
  64545. size_t bytesToSeek = (bytesToRead - bytesRead);
  64546. if (bytesToSeek > 0x7FFFFFFF) {
  64547. bytesToSeek = 0x7FFFFFFF;
  64548. }
  64549. if (pWav->onSeek(pWav->pUserData, (int)bytesToSeek, drwav_seek_origin_current) == DRWAV_FALSE) {
  64550. break;
  64551. }
  64552. bytesRead += bytesToSeek;
  64553. }
  64554. while (bytesRead < bytesToRead) {
  64555. drwav_uint8 buffer[4096];
  64556. size_t bytesSeeked;
  64557. size_t bytesToSeek = (bytesToRead - bytesRead);
  64558. if (bytesToSeek > sizeof(buffer)) {
  64559. bytesToSeek = sizeof(buffer);
  64560. }
  64561. bytesSeeked = pWav->onRead(pWav->pUserData, buffer, bytesToSeek);
  64562. bytesRead += bytesSeeked;
  64563. if (bytesSeeked < bytesToSeek) {
  64564. break;
  64565. }
  64566. }
  64567. }
  64568. pWav->readCursorInPCMFrames += bytesRead / bytesPerFrame;
  64569. pWav->bytesRemaining -= bytesRead;
  64570. return bytesRead;
  64571. }
  64572. DRWAV_API drwav_uint64 drwav_read_pcm_frames_le(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  64573. {
  64574. drwav_uint32 bytesPerFrame;
  64575. drwav_uint64 bytesToRead;
  64576. if (pWav == NULL || framesToRead == 0) {
  64577. return 0;
  64578. }
  64579. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  64580. return 0;
  64581. }
  64582. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  64583. if (bytesPerFrame == 0) {
  64584. return 0;
  64585. }
  64586. bytesToRead = framesToRead * bytesPerFrame;
  64587. if (bytesToRead > DRWAV_SIZE_MAX) {
  64588. bytesToRead = (DRWAV_SIZE_MAX / bytesPerFrame) * bytesPerFrame;
  64589. }
  64590. if (bytesToRead == 0) {
  64591. return 0;
  64592. }
  64593. return drwav_read_raw(pWav, (size_t)bytesToRead, pBufferOut) / bytesPerFrame;
  64594. }
  64595. DRWAV_API drwav_uint64 drwav_read_pcm_frames_be(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  64596. {
  64597. drwav_uint64 framesRead = drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  64598. if (pBufferOut != NULL) {
  64599. drwav_uint32 bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  64600. if (bytesPerFrame == 0) {
  64601. return 0;
  64602. }
  64603. drwav__bswap_samples(pBufferOut, framesRead*pWav->channels, bytesPerFrame/pWav->channels, pWav->translatedFormatTag);
  64604. }
  64605. return framesRead;
  64606. }
  64607. DRWAV_API drwav_uint64 drwav_read_pcm_frames(drwav* pWav, drwav_uint64 framesToRead, void* pBufferOut)
  64608. {
  64609. if (drwav__is_little_endian()) {
  64610. return drwav_read_pcm_frames_le(pWav, framesToRead, pBufferOut);
  64611. } else {
  64612. return drwav_read_pcm_frames_be(pWav, framesToRead, pBufferOut);
  64613. }
  64614. }
  64615. DRWAV_PRIVATE drwav_bool32 drwav_seek_to_first_pcm_frame(drwav* pWav)
  64616. {
  64617. if (pWav->onWrite != NULL) {
  64618. return DRWAV_FALSE;
  64619. }
  64620. if (!pWav->onSeek(pWav->pUserData, (int)pWav->dataChunkDataPos, drwav_seek_origin_start)) {
  64621. return DRWAV_FALSE;
  64622. }
  64623. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  64624. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  64625. DRWAV_ZERO_OBJECT(&pWav->msadpcm);
  64626. } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  64627. DRWAV_ZERO_OBJECT(&pWav->ima);
  64628. } else {
  64629. DRWAV_ASSERT(DRWAV_FALSE);
  64630. }
  64631. }
  64632. pWav->readCursorInPCMFrames = 0;
  64633. pWav->bytesRemaining = pWav->dataChunkDataSize;
  64634. return DRWAV_TRUE;
  64635. }
  64636. DRWAV_API drwav_bool32 drwav_seek_to_pcm_frame(drwav* pWav, drwav_uint64 targetFrameIndex)
  64637. {
  64638. if (pWav == NULL || pWav->onSeek == NULL) {
  64639. return DRWAV_FALSE;
  64640. }
  64641. if (pWav->onWrite != NULL) {
  64642. return DRWAV_FALSE;
  64643. }
  64644. if (pWav->totalPCMFrameCount == 0) {
  64645. return DRWAV_TRUE;
  64646. }
  64647. if (targetFrameIndex > pWav->totalPCMFrameCount) {
  64648. targetFrameIndex = pWav->totalPCMFrameCount;
  64649. }
  64650. if (drwav__is_compressed_format_tag(pWav->translatedFormatTag)) {
  64651. if (targetFrameIndex < pWav->readCursorInPCMFrames) {
  64652. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  64653. return DRWAV_FALSE;
  64654. }
  64655. }
  64656. if (targetFrameIndex > pWav->readCursorInPCMFrames) {
  64657. drwav_uint64 offsetInFrames = targetFrameIndex - pWav->readCursorInPCMFrames;
  64658. drwav_int16 devnull[2048];
  64659. while (offsetInFrames > 0) {
  64660. drwav_uint64 framesRead = 0;
  64661. drwav_uint64 framesToRead = offsetInFrames;
  64662. if (framesToRead > drwav_countof(devnull)/pWav->channels) {
  64663. framesToRead = drwav_countof(devnull)/pWav->channels;
  64664. }
  64665. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  64666. framesRead = drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, devnull);
  64667. } else if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  64668. framesRead = drwav_read_pcm_frames_s16__ima(pWav, framesToRead, devnull);
  64669. } else {
  64670. DRWAV_ASSERT(DRWAV_FALSE);
  64671. }
  64672. if (framesRead != framesToRead) {
  64673. return DRWAV_FALSE;
  64674. }
  64675. offsetInFrames -= framesRead;
  64676. }
  64677. }
  64678. } else {
  64679. drwav_uint64 totalSizeInBytes;
  64680. drwav_uint64 currentBytePos;
  64681. drwav_uint64 targetBytePos;
  64682. drwav_uint64 offset;
  64683. drwav_uint32 bytesPerFrame;
  64684. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  64685. if (bytesPerFrame == 0) {
  64686. return DRWAV_FALSE;
  64687. }
  64688. totalSizeInBytes = pWav->totalPCMFrameCount * bytesPerFrame;
  64689. DRWAV_ASSERT(totalSizeInBytes >= pWav->bytesRemaining);
  64690. currentBytePos = totalSizeInBytes - pWav->bytesRemaining;
  64691. targetBytePos = targetFrameIndex * bytesPerFrame;
  64692. if (currentBytePos < targetBytePos) {
  64693. offset = (targetBytePos - currentBytePos);
  64694. } else {
  64695. if (!drwav_seek_to_first_pcm_frame(pWav)) {
  64696. return DRWAV_FALSE;
  64697. }
  64698. offset = targetBytePos;
  64699. }
  64700. while (offset > 0) {
  64701. int offset32 = ((offset > INT_MAX) ? INT_MAX : (int)offset);
  64702. if (!pWav->onSeek(pWav->pUserData, offset32, drwav_seek_origin_current)) {
  64703. return DRWAV_FALSE;
  64704. }
  64705. pWav->readCursorInPCMFrames += offset32 / bytesPerFrame;
  64706. pWav->bytesRemaining -= offset32;
  64707. offset -= offset32;
  64708. }
  64709. }
  64710. return DRWAV_TRUE;
  64711. }
  64712. DRWAV_API drwav_result drwav_get_cursor_in_pcm_frames(drwav* pWav, drwav_uint64* pCursor)
  64713. {
  64714. if (pCursor == NULL) {
  64715. return DRWAV_INVALID_ARGS;
  64716. }
  64717. *pCursor = 0;
  64718. if (pWav == NULL) {
  64719. return DRWAV_INVALID_ARGS;
  64720. }
  64721. *pCursor = pWav->readCursorInPCMFrames;
  64722. return DRWAV_SUCCESS;
  64723. }
  64724. DRWAV_API drwav_result drwav_get_length_in_pcm_frames(drwav* pWav, drwav_uint64* pLength)
  64725. {
  64726. if (pLength == NULL) {
  64727. return DRWAV_INVALID_ARGS;
  64728. }
  64729. *pLength = 0;
  64730. if (pWav == NULL) {
  64731. return DRWAV_INVALID_ARGS;
  64732. }
  64733. *pLength = pWav->totalPCMFrameCount;
  64734. return DRWAV_SUCCESS;
  64735. }
  64736. DRWAV_API size_t drwav_write_raw(drwav* pWav, size_t bytesToWrite, const void* pData)
  64737. {
  64738. size_t bytesWritten;
  64739. if (pWav == NULL || bytesToWrite == 0 || pData == NULL) {
  64740. return 0;
  64741. }
  64742. bytesWritten = pWav->onWrite(pWav->pUserData, pData, bytesToWrite);
  64743. pWav->dataChunkDataSize += bytesWritten;
  64744. return bytesWritten;
  64745. }
  64746. DRWAV_API drwav_uint64 drwav_write_pcm_frames_le(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  64747. {
  64748. drwav_uint64 bytesToWrite;
  64749. drwav_uint64 bytesWritten;
  64750. const drwav_uint8* pRunningData;
  64751. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  64752. return 0;
  64753. }
  64754. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  64755. if (bytesToWrite > DRWAV_SIZE_MAX) {
  64756. return 0;
  64757. }
  64758. bytesWritten = 0;
  64759. pRunningData = (const drwav_uint8*)pData;
  64760. while (bytesToWrite > 0) {
  64761. size_t bytesJustWritten;
  64762. drwav_uint64 bytesToWriteThisIteration;
  64763. bytesToWriteThisIteration = bytesToWrite;
  64764. DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
  64765. bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, pRunningData);
  64766. if (bytesJustWritten == 0) {
  64767. break;
  64768. }
  64769. bytesToWrite -= bytesJustWritten;
  64770. bytesWritten += bytesJustWritten;
  64771. pRunningData += bytesJustWritten;
  64772. }
  64773. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  64774. }
  64775. DRWAV_API drwav_uint64 drwav_write_pcm_frames_be(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  64776. {
  64777. drwav_uint64 bytesToWrite;
  64778. drwav_uint64 bytesWritten;
  64779. drwav_uint32 bytesPerSample;
  64780. const drwav_uint8* pRunningData;
  64781. if (pWav == NULL || framesToWrite == 0 || pData == NULL) {
  64782. return 0;
  64783. }
  64784. bytesToWrite = ((framesToWrite * pWav->channels * pWav->bitsPerSample) / 8);
  64785. if (bytesToWrite > DRWAV_SIZE_MAX) {
  64786. return 0;
  64787. }
  64788. bytesWritten = 0;
  64789. pRunningData = (const drwav_uint8*)pData;
  64790. bytesPerSample = drwav_get_bytes_per_pcm_frame(pWav) / pWav->channels;
  64791. if (bytesPerSample == 0) {
  64792. return 0;
  64793. }
  64794. while (bytesToWrite > 0) {
  64795. drwav_uint8 temp[4096];
  64796. drwav_uint32 sampleCount;
  64797. size_t bytesJustWritten;
  64798. drwav_uint64 bytesToWriteThisIteration;
  64799. bytesToWriteThisIteration = bytesToWrite;
  64800. DRWAV_ASSERT(bytesToWriteThisIteration <= DRWAV_SIZE_MAX);
  64801. sampleCount = sizeof(temp)/bytesPerSample;
  64802. if (bytesToWriteThisIteration > ((drwav_uint64)sampleCount)*bytesPerSample) {
  64803. bytesToWriteThisIteration = ((drwav_uint64)sampleCount)*bytesPerSample;
  64804. }
  64805. DRWAV_COPY_MEMORY(temp, pRunningData, (size_t)bytesToWriteThisIteration);
  64806. drwav__bswap_samples(temp, sampleCount, bytesPerSample, pWav->translatedFormatTag);
  64807. bytesJustWritten = drwav_write_raw(pWav, (size_t)bytesToWriteThisIteration, temp);
  64808. if (bytesJustWritten == 0) {
  64809. break;
  64810. }
  64811. bytesToWrite -= bytesJustWritten;
  64812. bytesWritten += bytesJustWritten;
  64813. pRunningData += bytesJustWritten;
  64814. }
  64815. return (bytesWritten * 8) / pWav->bitsPerSample / pWav->channels;
  64816. }
  64817. DRWAV_API drwav_uint64 drwav_write_pcm_frames(drwav* pWav, drwav_uint64 framesToWrite, const void* pData)
  64818. {
  64819. if (drwav__is_little_endian()) {
  64820. return drwav_write_pcm_frames_le(pWav, framesToWrite, pData);
  64821. } else {
  64822. return drwav_write_pcm_frames_be(pWav, framesToWrite, pData);
  64823. }
  64824. }
  64825. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__msadpcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  64826. {
  64827. drwav_uint64 totalFramesRead = 0;
  64828. DRWAV_ASSERT(pWav != NULL);
  64829. DRWAV_ASSERT(framesToRead > 0);
  64830. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  64831. DRWAV_ASSERT(framesToRead > 0);
  64832. if (pWav->msadpcm.cachedFrameCount == 0 && pWav->msadpcm.bytesRemainingInBlock == 0) {
  64833. if (pWav->channels == 1) {
  64834. drwav_uint8 header[7];
  64835. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  64836. return totalFramesRead;
  64837. }
  64838. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  64839. pWav->msadpcm.predictor[0] = header[0];
  64840. pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 1);
  64841. pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 3);
  64842. pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 5);
  64843. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][0];
  64844. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[0][1];
  64845. pWav->msadpcm.cachedFrameCount = 2;
  64846. } else {
  64847. drwav_uint8 header[14];
  64848. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  64849. return totalFramesRead;
  64850. }
  64851. pWav->msadpcm.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  64852. pWav->msadpcm.predictor[0] = header[0];
  64853. pWav->msadpcm.predictor[1] = header[1];
  64854. pWav->msadpcm.delta[0] = drwav_bytes_to_s16(header + 2);
  64855. pWav->msadpcm.delta[1] = drwav_bytes_to_s16(header + 4);
  64856. pWav->msadpcm.prevFrames[0][1] = (drwav_int32)drwav_bytes_to_s16(header + 6);
  64857. pWav->msadpcm.prevFrames[1][1] = (drwav_int32)drwav_bytes_to_s16(header + 8);
  64858. pWav->msadpcm.prevFrames[0][0] = (drwav_int32)drwav_bytes_to_s16(header + 10);
  64859. pWav->msadpcm.prevFrames[1][0] = (drwav_int32)drwav_bytes_to_s16(header + 12);
  64860. pWav->msadpcm.cachedFrames[0] = pWav->msadpcm.prevFrames[0][0];
  64861. pWav->msadpcm.cachedFrames[1] = pWav->msadpcm.prevFrames[1][0];
  64862. pWav->msadpcm.cachedFrames[2] = pWav->msadpcm.prevFrames[0][1];
  64863. pWav->msadpcm.cachedFrames[3] = pWav->msadpcm.prevFrames[1][1];
  64864. pWav->msadpcm.cachedFrameCount = 2;
  64865. }
  64866. }
  64867. while (framesToRead > 0 && pWav->msadpcm.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  64868. if (pBufferOut != NULL) {
  64869. drwav_uint32 iSample = 0;
  64870. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  64871. pBufferOut[iSample] = (drwav_int16)pWav->msadpcm.cachedFrames[(drwav_countof(pWav->msadpcm.cachedFrames) - (pWav->msadpcm.cachedFrameCount*pWav->channels)) + iSample];
  64872. }
  64873. pBufferOut += pWav->channels;
  64874. }
  64875. framesToRead -= 1;
  64876. totalFramesRead += 1;
  64877. pWav->readCursorInPCMFrames += 1;
  64878. pWav->msadpcm.cachedFrameCount -= 1;
  64879. }
  64880. if (framesToRead == 0) {
  64881. break;
  64882. }
  64883. if (pWav->msadpcm.cachedFrameCount == 0) {
  64884. if (pWav->msadpcm.bytesRemainingInBlock == 0) {
  64885. continue;
  64886. } else {
  64887. static drwav_int32 adaptationTable[] = {
  64888. 230, 230, 230, 230, 307, 409, 512, 614,
  64889. 768, 614, 512, 409, 307, 230, 230, 230
  64890. };
  64891. static drwav_int32 coeff1Table[] = { 256, 512, 0, 192, 240, 460, 392 };
  64892. static drwav_int32 coeff2Table[] = { 0, -256, 0, 64, 0, -208, -232 };
  64893. drwav_uint8 nibbles;
  64894. drwav_int32 nibble0;
  64895. drwav_int32 nibble1;
  64896. if (pWav->onRead(pWav->pUserData, &nibbles, 1) != 1) {
  64897. return totalFramesRead;
  64898. }
  64899. pWav->msadpcm.bytesRemainingInBlock -= 1;
  64900. nibble0 = ((nibbles & 0xF0) >> 4); if ((nibbles & 0x80)) { nibble0 |= 0xFFFFFFF0UL; }
  64901. nibble1 = ((nibbles & 0x0F) >> 0); if ((nibbles & 0x08)) { nibble1 |= 0xFFFFFFF0UL; }
  64902. if (pWav->channels == 1) {
  64903. drwav_int32 newSample0;
  64904. drwav_int32 newSample1;
  64905. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  64906. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  64907. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  64908. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  64909. if (pWav->msadpcm.delta[0] < 16) {
  64910. pWav->msadpcm.delta[0] = 16;
  64911. }
  64912. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  64913. pWav->msadpcm.prevFrames[0][1] = newSample0;
  64914. newSample1 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  64915. newSample1 += nibble1 * pWav->msadpcm.delta[0];
  64916. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  64917. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[0]) >> 8;
  64918. if (pWav->msadpcm.delta[0] < 16) {
  64919. pWav->msadpcm.delta[0] = 16;
  64920. }
  64921. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  64922. pWav->msadpcm.prevFrames[0][1] = newSample1;
  64923. pWav->msadpcm.cachedFrames[2] = newSample0;
  64924. pWav->msadpcm.cachedFrames[3] = newSample1;
  64925. pWav->msadpcm.cachedFrameCount = 2;
  64926. } else {
  64927. drwav_int32 newSample0;
  64928. drwav_int32 newSample1;
  64929. newSample0 = ((pWav->msadpcm.prevFrames[0][1] * coeff1Table[pWav->msadpcm.predictor[0]]) + (pWav->msadpcm.prevFrames[0][0] * coeff2Table[pWav->msadpcm.predictor[0]])) >> 8;
  64930. newSample0 += nibble0 * pWav->msadpcm.delta[0];
  64931. newSample0 = drwav_clamp(newSample0, -32768, 32767);
  64932. pWav->msadpcm.delta[0] = (adaptationTable[((nibbles & 0xF0) >> 4)] * pWav->msadpcm.delta[0]) >> 8;
  64933. if (pWav->msadpcm.delta[0] < 16) {
  64934. pWav->msadpcm.delta[0] = 16;
  64935. }
  64936. pWav->msadpcm.prevFrames[0][0] = pWav->msadpcm.prevFrames[0][1];
  64937. pWav->msadpcm.prevFrames[0][1] = newSample0;
  64938. newSample1 = ((pWav->msadpcm.prevFrames[1][1] * coeff1Table[pWav->msadpcm.predictor[1]]) + (pWav->msadpcm.prevFrames[1][0] * coeff2Table[pWav->msadpcm.predictor[1]])) >> 8;
  64939. newSample1 += nibble1 * pWav->msadpcm.delta[1];
  64940. newSample1 = drwav_clamp(newSample1, -32768, 32767);
  64941. pWav->msadpcm.delta[1] = (adaptationTable[((nibbles & 0x0F) >> 0)] * pWav->msadpcm.delta[1]) >> 8;
  64942. if (pWav->msadpcm.delta[1] < 16) {
  64943. pWav->msadpcm.delta[1] = 16;
  64944. }
  64945. pWav->msadpcm.prevFrames[1][0] = pWav->msadpcm.prevFrames[1][1];
  64946. pWav->msadpcm.prevFrames[1][1] = newSample1;
  64947. pWav->msadpcm.cachedFrames[2] = newSample0;
  64948. pWav->msadpcm.cachedFrames[3] = newSample1;
  64949. pWav->msadpcm.cachedFrameCount = 1;
  64950. }
  64951. }
  64952. }
  64953. }
  64954. return totalFramesRead;
  64955. }
  64956. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  64957. {
  64958. drwav_uint64 totalFramesRead = 0;
  64959. drwav_uint32 iChannel;
  64960. static drwav_int32 indexTable[16] = {
  64961. -1, -1, -1, -1, 2, 4, 6, 8,
  64962. -1, -1, -1, -1, 2, 4, 6, 8
  64963. };
  64964. static drwav_int32 stepTable[89] = {
  64965. 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
  64966. 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
  64967. 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
  64968. 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
  64969. 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
  64970. 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
  64971. 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
  64972. 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
  64973. 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
  64974. };
  64975. DRWAV_ASSERT(pWav != NULL);
  64976. DRWAV_ASSERT(framesToRead > 0);
  64977. while (pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  64978. DRWAV_ASSERT(framesToRead > 0);
  64979. if (pWav->ima.cachedFrameCount == 0 && pWav->ima.bytesRemainingInBlock == 0) {
  64980. if (pWav->channels == 1) {
  64981. drwav_uint8 header[4];
  64982. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  64983. return totalFramesRead;
  64984. }
  64985. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  64986. if (header[2] >= drwav_countof(stepTable)) {
  64987. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
  64988. pWav->ima.bytesRemainingInBlock = 0;
  64989. return totalFramesRead;
  64990. }
  64991. pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0);
  64992. pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1);
  64993. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[0];
  64994. pWav->ima.cachedFrameCount = 1;
  64995. } else {
  64996. drwav_uint8 header[8];
  64997. if (pWav->onRead(pWav->pUserData, header, sizeof(header)) != sizeof(header)) {
  64998. return totalFramesRead;
  64999. }
  65000. pWav->ima.bytesRemainingInBlock = pWav->fmt.blockAlign - sizeof(header);
  65001. if (header[2] >= drwav_countof(stepTable) || header[6] >= drwav_countof(stepTable)) {
  65002. pWav->onSeek(pWav->pUserData, pWav->ima.bytesRemainingInBlock, drwav_seek_origin_current);
  65003. pWav->ima.bytesRemainingInBlock = 0;
  65004. return totalFramesRead;
  65005. }
  65006. pWav->ima.predictor[0] = drwav_bytes_to_s16(header + 0);
  65007. pWav->ima.stepIndex[0] = drwav_clamp(header[2], 0, (drwav_int32)drwav_countof(stepTable)-1);
  65008. pWav->ima.predictor[1] = drwav_bytes_to_s16(header + 4);
  65009. pWav->ima.stepIndex[1] = drwav_clamp(header[6], 0, (drwav_int32)drwav_countof(stepTable)-1);
  65010. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 2] = pWav->ima.predictor[0];
  65011. pWav->ima.cachedFrames[drwav_countof(pWav->ima.cachedFrames) - 1] = pWav->ima.predictor[1];
  65012. pWav->ima.cachedFrameCount = 1;
  65013. }
  65014. }
  65015. while (framesToRead > 0 && pWav->ima.cachedFrameCount > 0 && pWav->readCursorInPCMFrames < pWav->totalPCMFrameCount) {
  65016. if (pBufferOut != NULL) {
  65017. drwav_uint32 iSample;
  65018. for (iSample = 0; iSample < pWav->channels; iSample += 1) {
  65019. pBufferOut[iSample] = (drwav_int16)pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + iSample];
  65020. }
  65021. pBufferOut += pWav->channels;
  65022. }
  65023. framesToRead -= 1;
  65024. totalFramesRead += 1;
  65025. pWav->readCursorInPCMFrames += 1;
  65026. pWav->ima.cachedFrameCount -= 1;
  65027. }
  65028. if (framesToRead == 0) {
  65029. break;
  65030. }
  65031. if (pWav->ima.cachedFrameCount == 0) {
  65032. if (pWav->ima.bytesRemainingInBlock == 0) {
  65033. continue;
  65034. } else {
  65035. pWav->ima.cachedFrameCount = 8;
  65036. for (iChannel = 0; iChannel < pWav->channels; ++iChannel) {
  65037. drwav_uint32 iByte;
  65038. drwav_uint8 nibbles[4];
  65039. if (pWav->onRead(pWav->pUserData, &nibbles, 4) != 4) {
  65040. pWav->ima.cachedFrameCount = 0;
  65041. return totalFramesRead;
  65042. }
  65043. pWav->ima.bytesRemainingInBlock -= 4;
  65044. for (iByte = 0; iByte < 4; ++iByte) {
  65045. drwav_uint8 nibble0 = ((nibbles[iByte] & 0x0F) >> 0);
  65046. drwav_uint8 nibble1 = ((nibbles[iByte] & 0xF0) >> 4);
  65047. drwav_int32 step = stepTable[pWav->ima.stepIndex[iChannel]];
  65048. drwav_int32 predictor = pWav->ima.predictor[iChannel];
  65049. drwav_int32 diff = step >> 3;
  65050. if (nibble0 & 1) diff += step >> 2;
  65051. if (nibble0 & 2) diff += step >> 1;
  65052. if (nibble0 & 4) diff += step;
  65053. if (nibble0 & 8) diff = -diff;
  65054. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  65055. pWav->ima.predictor[iChannel] = predictor;
  65056. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble0], 0, (drwav_int32)drwav_countof(stepTable)-1);
  65057. pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+0)*pWav->channels + iChannel] = predictor;
  65058. step = stepTable[pWav->ima.stepIndex[iChannel]];
  65059. predictor = pWav->ima.predictor[iChannel];
  65060. diff = step >> 3;
  65061. if (nibble1 & 1) diff += step >> 2;
  65062. if (nibble1 & 2) diff += step >> 1;
  65063. if (nibble1 & 4) diff += step;
  65064. if (nibble1 & 8) diff = -diff;
  65065. predictor = drwav_clamp(predictor + diff, -32768, 32767);
  65066. pWav->ima.predictor[iChannel] = predictor;
  65067. pWav->ima.stepIndex[iChannel] = drwav_clamp(pWav->ima.stepIndex[iChannel] + indexTable[nibble1], 0, (drwav_int32)drwav_countof(stepTable)-1);
  65068. pWav->ima.cachedFrames[(drwav_countof(pWav->ima.cachedFrames) - (pWav->ima.cachedFrameCount*pWav->channels)) + (iByte*2+1)*pWav->channels + iChannel] = predictor;
  65069. }
  65070. }
  65071. }
  65072. }
  65073. }
  65074. return totalFramesRead;
  65075. }
  65076. #ifndef DR_WAV_NO_CONVERSION_API
  65077. static unsigned short g_drwavAlawTable[256] = {
  65078. 0xEA80, 0xEB80, 0xE880, 0xE980, 0xEE80, 0xEF80, 0xEC80, 0xED80, 0xE280, 0xE380, 0xE080, 0xE180, 0xE680, 0xE780, 0xE480, 0xE580,
  65079. 0xF540, 0xF5C0, 0xF440, 0xF4C0, 0xF740, 0xF7C0, 0xF640, 0xF6C0, 0xF140, 0xF1C0, 0xF040, 0xF0C0, 0xF340, 0xF3C0, 0xF240, 0xF2C0,
  65080. 0xAA00, 0xAE00, 0xA200, 0xA600, 0xBA00, 0xBE00, 0xB200, 0xB600, 0x8A00, 0x8E00, 0x8200, 0x8600, 0x9A00, 0x9E00, 0x9200, 0x9600,
  65081. 0xD500, 0xD700, 0xD100, 0xD300, 0xDD00, 0xDF00, 0xD900, 0xDB00, 0xC500, 0xC700, 0xC100, 0xC300, 0xCD00, 0xCF00, 0xC900, 0xCB00,
  65082. 0xFEA8, 0xFEB8, 0xFE88, 0xFE98, 0xFEE8, 0xFEF8, 0xFEC8, 0xFED8, 0xFE28, 0xFE38, 0xFE08, 0xFE18, 0xFE68, 0xFE78, 0xFE48, 0xFE58,
  65083. 0xFFA8, 0xFFB8, 0xFF88, 0xFF98, 0xFFE8, 0xFFF8, 0xFFC8, 0xFFD8, 0xFF28, 0xFF38, 0xFF08, 0xFF18, 0xFF68, 0xFF78, 0xFF48, 0xFF58,
  65084. 0xFAA0, 0xFAE0, 0xFA20, 0xFA60, 0xFBA0, 0xFBE0, 0xFB20, 0xFB60, 0xF8A0, 0xF8E0, 0xF820, 0xF860, 0xF9A0, 0xF9E0, 0xF920, 0xF960,
  65085. 0xFD50, 0xFD70, 0xFD10, 0xFD30, 0xFDD0, 0xFDF0, 0xFD90, 0xFDB0, 0xFC50, 0xFC70, 0xFC10, 0xFC30, 0xFCD0, 0xFCF0, 0xFC90, 0xFCB0,
  65086. 0x1580, 0x1480, 0x1780, 0x1680, 0x1180, 0x1080, 0x1380, 0x1280, 0x1D80, 0x1C80, 0x1F80, 0x1E80, 0x1980, 0x1880, 0x1B80, 0x1A80,
  65087. 0x0AC0, 0x0A40, 0x0BC0, 0x0B40, 0x08C0, 0x0840, 0x09C0, 0x0940, 0x0EC0, 0x0E40, 0x0FC0, 0x0F40, 0x0CC0, 0x0C40, 0x0DC0, 0x0D40,
  65088. 0x5600, 0x5200, 0x5E00, 0x5A00, 0x4600, 0x4200, 0x4E00, 0x4A00, 0x7600, 0x7200, 0x7E00, 0x7A00, 0x6600, 0x6200, 0x6E00, 0x6A00,
  65089. 0x2B00, 0x2900, 0x2F00, 0x2D00, 0x2300, 0x2100, 0x2700, 0x2500, 0x3B00, 0x3900, 0x3F00, 0x3D00, 0x3300, 0x3100, 0x3700, 0x3500,
  65090. 0x0158, 0x0148, 0x0178, 0x0168, 0x0118, 0x0108, 0x0138, 0x0128, 0x01D8, 0x01C8, 0x01F8, 0x01E8, 0x0198, 0x0188, 0x01B8, 0x01A8,
  65091. 0x0058, 0x0048, 0x0078, 0x0068, 0x0018, 0x0008, 0x0038, 0x0028, 0x00D8, 0x00C8, 0x00F8, 0x00E8, 0x0098, 0x0088, 0x00B8, 0x00A8,
  65092. 0x0560, 0x0520, 0x05E0, 0x05A0, 0x0460, 0x0420, 0x04E0, 0x04A0, 0x0760, 0x0720, 0x07E0, 0x07A0, 0x0660, 0x0620, 0x06E0, 0x06A0,
  65093. 0x02B0, 0x0290, 0x02F0, 0x02D0, 0x0230, 0x0210, 0x0270, 0x0250, 0x03B0, 0x0390, 0x03F0, 0x03D0, 0x0330, 0x0310, 0x0370, 0x0350
  65094. };
  65095. static unsigned short g_drwavMulawTable[256] = {
  65096. 0x8284, 0x8684, 0x8A84, 0x8E84, 0x9284, 0x9684, 0x9A84, 0x9E84, 0xA284, 0xA684, 0xAA84, 0xAE84, 0xB284, 0xB684, 0xBA84, 0xBE84,
  65097. 0xC184, 0xC384, 0xC584, 0xC784, 0xC984, 0xCB84, 0xCD84, 0xCF84, 0xD184, 0xD384, 0xD584, 0xD784, 0xD984, 0xDB84, 0xDD84, 0xDF84,
  65098. 0xE104, 0xE204, 0xE304, 0xE404, 0xE504, 0xE604, 0xE704, 0xE804, 0xE904, 0xEA04, 0xEB04, 0xEC04, 0xED04, 0xEE04, 0xEF04, 0xF004,
  65099. 0xF0C4, 0xF144, 0xF1C4, 0xF244, 0xF2C4, 0xF344, 0xF3C4, 0xF444, 0xF4C4, 0xF544, 0xF5C4, 0xF644, 0xF6C4, 0xF744, 0xF7C4, 0xF844,
  65100. 0xF8A4, 0xF8E4, 0xF924, 0xF964, 0xF9A4, 0xF9E4, 0xFA24, 0xFA64, 0xFAA4, 0xFAE4, 0xFB24, 0xFB64, 0xFBA4, 0xFBE4, 0xFC24, 0xFC64,
  65101. 0xFC94, 0xFCB4, 0xFCD4, 0xFCF4, 0xFD14, 0xFD34, 0xFD54, 0xFD74, 0xFD94, 0xFDB4, 0xFDD4, 0xFDF4, 0xFE14, 0xFE34, 0xFE54, 0xFE74,
  65102. 0xFE8C, 0xFE9C, 0xFEAC, 0xFEBC, 0xFECC, 0xFEDC, 0xFEEC, 0xFEFC, 0xFF0C, 0xFF1C, 0xFF2C, 0xFF3C, 0xFF4C, 0xFF5C, 0xFF6C, 0xFF7C,
  65103. 0xFF88, 0xFF90, 0xFF98, 0xFFA0, 0xFFA8, 0xFFB0, 0xFFB8, 0xFFC0, 0xFFC8, 0xFFD0, 0xFFD8, 0xFFE0, 0xFFE8, 0xFFF0, 0xFFF8, 0x0000,
  65104. 0x7D7C, 0x797C, 0x757C, 0x717C, 0x6D7C, 0x697C, 0x657C, 0x617C, 0x5D7C, 0x597C, 0x557C, 0x517C, 0x4D7C, 0x497C, 0x457C, 0x417C,
  65105. 0x3E7C, 0x3C7C, 0x3A7C, 0x387C, 0x367C, 0x347C, 0x327C, 0x307C, 0x2E7C, 0x2C7C, 0x2A7C, 0x287C, 0x267C, 0x247C, 0x227C, 0x207C,
  65106. 0x1EFC, 0x1DFC, 0x1CFC, 0x1BFC, 0x1AFC, 0x19FC, 0x18FC, 0x17FC, 0x16FC, 0x15FC, 0x14FC, 0x13FC, 0x12FC, 0x11FC, 0x10FC, 0x0FFC,
  65107. 0x0F3C, 0x0EBC, 0x0E3C, 0x0DBC, 0x0D3C, 0x0CBC, 0x0C3C, 0x0BBC, 0x0B3C, 0x0ABC, 0x0A3C, 0x09BC, 0x093C, 0x08BC, 0x083C, 0x07BC,
  65108. 0x075C, 0x071C, 0x06DC, 0x069C, 0x065C, 0x061C, 0x05DC, 0x059C, 0x055C, 0x051C, 0x04DC, 0x049C, 0x045C, 0x041C, 0x03DC, 0x039C,
  65109. 0x036C, 0x034C, 0x032C, 0x030C, 0x02EC, 0x02CC, 0x02AC, 0x028C, 0x026C, 0x024C, 0x022C, 0x020C, 0x01EC, 0x01CC, 0x01AC, 0x018C,
  65110. 0x0174, 0x0164, 0x0154, 0x0144, 0x0134, 0x0124, 0x0114, 0x0104, 0x00F4, 0x00E4, 0x00D4, 0x00C4, 0x00B4, 0x00A4, 0x0094, 0x0084,
  65111. 0x0078, 0x0070, 0x0068, 0x0060, 0x0058, 0x0050, 0x0048, 0x0040, 0x0038, 0x0030, 0x0028, 0x0020, 0x0018, 0x0010, 0x0008, 0x0000
  65112. };
  65113. static DRWAV_INLINE drwav_int16 drwav__alaw_to_s16(drwav_uint8 sampleIn)
  65114. {
  65115. return (short)g_drwavAlawTable[sampleIn];
  65116. }
  65117. static DRWAV_INLINE drwav_int16 drwav__mulaw_to_s16(drwav_uint8 sampleIn)
  65118. {
  65119. return (short)g_drwavMulawTable[sampleIn];
  65120. }
  65121. DRWAV_PRIVATE void drwav__pcm_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  65122. {
  65123. size_t i;
  65124. if (bytesPerSample == 1) {
  65125. drwav_u8_to_s16(pOut, pIn, totalSampleCount);
  65126. return;
  65127. }
  65128. if (bytesPerSample == 2) {
  65129. for (i = 0; i < totalSampleCount; ++i) {
  65130. *pOut++ = ((const drwav_int16*)pIn)[i];
  65131. }
  65132. return;
  65133. }
  65134. if (bytesPerSample == 3) {
  65135. drwav_s24_to_s16(pOut, pIn, totalSampleCount);
  65136. return;
  65137. }
  65138. if (bytesPerSample == 4) {
  65139. drwav_s32_to_s16(pOut, (const drwav_int32*)pIn, totalSampleCount);
  65140. return;
  65141. }
  65142. if (bytesPerSample > 8) {
  65143. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  65144. return;
  65145. }
  65146. for (i = 0; i < totalSampleCount; ++i) {
  65147. drwav_uint64 sample = 0;
  65148. unsigned int shift = (8 - bytesPerSample) * 8;
  65149. unsigned int j;
  65150. for (j = 0; j < bytesPerSample; j += 1) {
  65151. DRWAV_ASSERT(j < 8);
  65152. sample |= (drwav_uint64)(pIn[j]) << shift;
  65153. shift += 8;
  65154. }
  65155. pIn += j;
  65156. *pOut++ = (drwav_int16)((drwav_int64)sample >> 48);
  65157. }
  65158. }
  65159. DRWAV_PRIVATE void drwav__ieee_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  65160. {
  65161. if (bytesPerSample == 4) {
  65162. drwav_f32_to_s16(pOut, (const float*)pIn, totalSampleCount);
  65163. return;
  65164. } else if (bytesPerSample == 8) {
  65165. drwav_f64_to_s16(pOut, (const double*)pIn, totalSampleCount);
  65166. return;
  65167. } else {
  65168. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  65169. return;
  65170. }
  65171. }
  65172. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65173. {
  65174. drwav_uint64 totalFramesRead;
  65175. drwav_uint8 sampleData[4096] = {0};
  65176. drwav_uint32 bytesPerFrame;
  65177. drwav_uint32 bytesPerSample;
  65178. drwav_uint64 samplesRead;
  65179. if ((pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 16) || pBufferOut == NULL) {
  65180. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  65181. }
  65182. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65183. if (bytesPerFrame == 0) {
  65184. return 0;
  65185. }
  65186. bytesPerSample = bytesPerFrame / pWav->channels;
  65187. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65188. return 0;
  65189. }
  65190. totalFramesRead = 0;
  65191. while (framesToRead > 0) {
  65192. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65193. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65194. if (framesRead == 0) {
  65195. break;
  65196. }
  65197. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65198. samplesRead = framesRead * pWav->channels;
  65199. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65200. DRWAV_ASSERT(DRWAV_FALSE);
  65201. break;
  65202. }
  65203. drwav__pcm_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65204. pBufferOut += samplesRead;
  65205. framesToRead -= framesRead;
  65206. totalFramesRead += framesRead;
  65207. }
  65208. return totalFramesRead;
  65209. }
  65210. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65211. {
  65212. drwav_uint64 totalFramesRead;
  65213. drwav_uint8 sampleData[4096] = {0};
  65214. drwav_uint32 bytesPerFrame;
  65215. drwav_uint32 bytesPerSample;
  65216. drwav_uint64 samplesRead;
  65217. if (pBufferOut == NULL) {
  65218. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  65219. }
  65220. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65221. if (bytesPerFrame == 0) {
  65222. return 0;
  65223. }
  65224. bytesPerSample = bytesPerFrame / pWav->channels;
  65225. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65226. return 0;
  65227. }
  65228. totalFramesRead = 0;
  65229. while (framesToRead > 0) {
  65230. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65231. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65232. if (framesRead == 0) {
  65233. break;
  65234. }
  65235. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65236. samplesRead = framesRead * pWav->channels;
  65237. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65238. DRWAV_ASSERT(DRWAV_FALSE);
  65239. break;
  65240. }
  65241. drwav__ieee_to_s16(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65242. pBufferOut += samplesRead;
  65243. framesToRead -= framesRead;
  65244. totalFramesRead += framesRead;
  65245. }
  65246. return totalFramesRead;
  65247. }
  65248. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65249. {
  65250. drwav_uint64 totalFramesRead;
  65251. drwav_uint8 sampleData[4096] = {0};
  65252. drwav_uint32 bytesPerFrame;
  65253. drwav_uint32 bytesPerSample;
  65254. drwav_uint64 samplesRead;
  65255. if (pBufferOut == NULL) {
  65256. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  65257. }
  65258. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65259. if (bytesPerFrame == 0) {
  65260. return 0;
  65261. }
  65262. bytesPerSample = bytesPerFrame / pWav->channels;
  65263. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65264. return 0;
  65265. }
  65266. totalFramesRead = 0;
  65267. while (framesToRead > 0) {
  65268. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65269. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65270. if (framesRead == 0) {
  65271. break;
  65272. }
  65273. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65274. samplesRead = framesRead * pWav->channels;
  65275. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65276. DRWAV_ASSERT(DRWAV_FALSE);
  65277. break;
  65278. }
  65279. drwav_alaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  65280. pBufferOut += samplesRead;
  65281. framesToRead -= framesRead;
  65282. totalFramesRead += framesRead;
  65283. }
  65284. return totalFramesRead;
  65285. }
  65286. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s16__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65287. {
  65288. drwav_uint64 totalFramesRead;
  65289. drwav_uint8 sampleData[4096] = {0};
  65290. drwav_uint32 bytesPerFrame;
  65291. drwav_uint32 bytesPerSample;
  65292. drwav_uint64 samplesRead;
  65293. if (pBufferOut == NULL) {
  65294. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  65295. }
  65296. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65297. if (bytesPerFrame == 0) {
  65298. return 0;
  65299. }
  65300. bytesPerSample = bytesPerFrame / pWav->channels;
  65301. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65302. return 0;
  65303. }
  65304. totalFramesRead = 0;
  65305. while (framesToRead > 0) {
  65306. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65307. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65308. if (framesRead == 0) {
  65309. break;
  65310. }
  65311. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65312. samplesRead = framesRead * pWav->channels;
  65313. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65314. DRWAV_ASSERT(DRWAV_FALSE);
  65315. break;
  65316. }
  65317. drwav_mulaw_to_s16(pBufferOut, sampleData, (size_t)samplesRead);
  65318. pBufferOut += samplesRead;
  65319. framesToRead -= framesRead;
  65320. totalFramesRead += framesRead;
  65321. }
  65322. return totalFramesRead;
  65323. }
  65324. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65325. {
  65326. if (pWav == NULL || framesToRead == 0) {
  65327. return 0;
  65328. }
  65329. if (pBufferOut == NULL) {
  65330. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  65331. }
  65332. if (framesToRead * pWav->channels * sizeof(drwav_int16) > DRWAV_SIZE_MAX) {
  65333. framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int16) / pWav->channels;
  65334. }
  65335. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  65336. return drwav_read_pcm_frames_s16__pcm(pWav, framesToRead, pBufferOut);
  65337. }
  65338. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  65339. return drwav_read_pcm_frames_s16__ieee(pWav, framesToRead, pBufferOut);
  65340. }
  65341. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  65342. return drwav_read_pcm_frames_s16__alaw(pWav, framesToRead, pBufferOut);
  65343. }
  65344. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  65345. return drwav_read_pcm_frames_s16__mulaw(pWav, framesToRead, pBufferOut);
  65346. }
  65347. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM) {
  65348. return drwav_read_pcm_frames_s16__msadpcm(pWav, framesToRead, pBufferOut);
  65349. }
  65350. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  65351. return drwav_read_pcm_frames_s16__ima(pWav, framesToRead, pBufferOut);
  65352. }
  65353. return 0;
  65354. }
  65355. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16le(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65356. {
  65357. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  65358. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  65359. drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  65360. }
  65361. return framesRead;
  65362. }
  65363. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s16be(drwav* pWav, drwav_uint64 framesToRead, drwav_int16* pBufferOut)
  65364. {
  65365. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToRead, pBufferOut);
  65366. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  65367. drwav__bswap_samples_s16(pBufferOut, framesRead*pWav->channels);
  65368. }
  65369. return framesRead;
  65370. }
  65371. DRWAV_API void drwav_u8_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65372. {
  65373. int r;
  65374. size_t i;
  65375. for (i = 0; i < sampleCount; ++i) {
  65376. int x = pIn[i];
  65377. r = x << 8;
  65378. r = r - 32768;
  65379. pOut[i] = (short)r;
  65380. }
  65381. }
  65382. DRWAV_API void drwav_s24_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65383. {
  65384. int r;
  65385. size_t i;
  65386. for (i = 0; i < sampleCount; ++i) {
  65387. int x = ((int)(((unsigned int)(((const drwav_uint8*)pIn)[i*3+0]) << 8) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+1]) << 16) | ((unsigned int)(((const drwav_uint8*)pIn)[i*3+2])) << 24)) >> 8;
  65388. r = x >> 8;
  65389. pOut[i] = (short)r;
  65390. }
  65391. }
  65392. DRWAV_API void drwav_s32_to_s16(drwav_int16* pOut, const drwav_int32* pIn, size_t sampleCount)
  65393. {
  65394. int r;
  65395. size_t i;
  65396. for (i = 0; i < sampleCount; ++i) {
  65397. int x = pIn[i];
  65398. r = x >> 16;
  65399. pOut[i] = (short)r;
  65400. }
  65401. }
  65402. DRWAV_API void drwav_f32_to_s16(drwav_int16* pOut, const float* pIn, size_t sampleCount)
  65403. {
  65404. int r;
  65405. size_t i;
  65406. for (i = 0; i < sampleCount; ++i) {
  65407. float x = pIn[i];
  65408. float c;
  65409. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  65410. c = c + 1;
  65411. r = (int)(c * 32767.5f);
  65412. r = r - 32768;
  65413. pOut[i] = (short)r;
  65414. }
  65415. }
  65416. DRWAV_API void drwav_f64_to_s16(drwav_int16* pOut, const double* pIn, size_t sampleCount)
  65417. {
  65418. int r;
  65419. size_t i;
  65420. for (i = 0; i < sampleCount; ++i) {
  65421. double x = pIn[i];
  65422. double c;
  65423. c = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  65424. c = c + 1;
  65425. r = (int)(c * 32767.5);
  65426. r = r - 32768;
  65427. pOut[i] = (short)r;
  65428. }
  65429. }
  65430. DRWAV_API void drwav_alaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65431. {
  65432. size_t i;
  65433. for (i = 0; i < sampleCount; ++i) {
  65434. pOut[i] = drwav__alaw_to_s16(pIn[i]);
  65435. }
  65436. }
  65437. DRWAV_API void drwav_mulaw_to_s16(drwav_int16* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65438. {
  65439. size_t i;
  65440. for (i = 0; i < sampleCount; ++i) {
  65441. pOut[i] = drwav__mulaw_to_s16(pIn[i]);
  65442. }
  65443. }
  65444. DRWAV_PRIVATE void drwav__pcm_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  65445. {
  65446. unsigned int i;
  65447. if (bytesPerSample == 1) {
  65448. drwav_u8_to_f32(pOut, pIn, sampleCount);
  65449. return;
  65450. }
  65451. if (bytesPerSample == 2) {
  65452. drwav_s16_to_f32(pOut, (const drwav_int16*)pIn, sampleCount);
  65453. return;
  65454. }
  65455. if (bytesPerSample == 3) {
  65456. drwav_s24_to_f32(pOut, pIn, sampleCount);
  65457. return;
  65458. }
  65459. if (bytesPerSample == 4) {
  65460. drwav_s32_to_f32(pOut, (const drwav_int32*)pIn, sampleCount);
  65461. return;
  65462. }
  65463. if (bytesPerSample > 8) {
  65464. DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  65465. return;
  65466. }
  65467. for (i = 0; i < sampleCount; ++i) {
  65468. drwav_uint64 sample = 0;
  65469. unsigned int shift = (8 - bytesPerSample) * 8;
  65470. unsigned int j;
  65471. for (j = 0; j < bytesPerSample; j += 1) {
  65472. DRWAV_ASSERT(j < 8);
  65473. sample |= (drwav_uint64)(pIn[j]) << shift;
  65474. shift += 8;
  65475. }
  65476. pIn += j;
  65477. *pOut++ = (float)((drwav_int64)sample / 9223372036854775807.0);
  65478. }
  65479. }
  65480. DRWAV_PRIVATE void drwav__ieee_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount, unsigned int bytesPerSample)
  65481. {
  65482. if (bytesPerSample == 4) {
  65483. unsigned int i;
  65484. for (i = 0; i < sampleCount; ++i) {
  65485. *pOut++ = ((const float*)pIn)[i];
  65486. }
  65487. return;
  65488. } else if (bytesPerSample == 8) {
  65489. drwav_f64_to_f32(pOut, (const double*)pIn, sampleCount);
  65490. return;
  65491. } else {
  65492. DRWAV_ZERO_MEMORY(pOut, sampleCount * sizeof(*pOut));
  65493. return;
  65494. }
  65495. }
  65496. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__pcm(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65497. {
  65498. drwav_uint64 totalFramesRead;
  65499. drwav_uint8 sampleData[4096] = {0};
  65500. drwav_uint32 bytesPerFrame;
  65501. drwav_uint32 bytesPerSample;
  65502. drwav_uint64 samplesRead;
  65503. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65504. if (bytesPerFrame == 0) {
  65505. return 0;
  65506. }
  65507. bytesPerSample = bytesPerFrame / pWav->channels;
  65508. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65509. return 0;
  65510. }
  65511. totalFramesRead = 0;
  65512. while (framesToRead > 0) {
  65513. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65514. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65515. if (framesRead == 0) {
  65516. break;
  65517. }
  65518. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65519. samplesRead = framesRead * pWav->channels;
  65520. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65521. DRWAV_ASSERT(DRWAV_FALSE);
  65522. break;
  65523. }
  65524. drwav__pcm_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65525. pBufferOut += samplesRead;
  65526. framesToRead -= framesRead;
  65527. totalFramesRead += framesRead;
  65528. }
  65529. return totalFramesRead;
  65530. }
  65531. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65532. {
  65533. drwav_uint64 totalFramesRead;
  65534. drwav_int16 samples16[2048];
  65535. totalFramesRead = 0;
  65536. while (framesToRead > 0) {
  65537. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
  65538. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  65539. if (framesRead == 0) {
  65540. break;
  65541. }
  65542. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65543. drwav_s16_to_f32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  65544. pBufferOut += framesRead*pWav->channels;
  65545. framesToRead -= framesRead;
  65546. totalFramesRead += framesRead;
  65547. }
  65548. return totalFramesRead;
  65549. }
  65550. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__ieee(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65551. {
  65552. drwav_uint64 totalFramesRead;
  65553. drwav_uint8 sampleData[4096] = {0};
  65554. drwav_uint32 bytesPerFrame;
  65555. drwav_uint32 bytesPerSample;
  65556. drwav_uint64 samplesRead;
  65557. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT && pWav->bitsPerSample == 32) {
  65558. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  65559. }
  65560. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65561. if (bytesPerFrame == 0) {
  65562. return 0;
  65563. }
  65564. bytesPerSample = bytesPerFrame / pWav->channels;
  65565. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65566. return 0;
  65567. }
  65568. totalFramesRead = 0;
  65569. while (framesToRead > 0) {
  65570. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65571. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65572. if (framesRead == 0) {
  65573. break;
  65574. }
  65575. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65576. samplesRead = framesRead * pWav->channels;
  65577. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65578. DRWAV_ASSERT(DRWAV_FALSE);
  65579. break;
  65580. }
  65581. drwav__ieee_to_f32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65582. pBufferOut += samplesRead;
  65583. framesToRead -= framesRead;
  65584. totalFramesRead += framesRead;
  65585. }
  65586. return totalFramesRead;
  65587. }
  65588. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__alaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65589. {
  65590. drwav_uint64 totalFramesRead;
  65591. drwav_uint8 sampleData[4096] = {0};
  65592. drwav_uint32 bytesPerFrame;
  65593. drwav_uint32 bytesPerSample;
  65594. drwav_uint64 samplesRead;
  65595. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65596. if (bytesPerFrame == 0) {
  65597. return 0;
  65598. }
  65599. bytesPerSample = bytesPerFrame / pWav->channels;
  65600. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65601. return 0;
  65602. }
  65603. totalFramesRead = 0;
  65604. while (framesToRead > 0) {
  65605. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65606. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65607. if (framesRead == 0) {
  65608. break;
  65609. }
  65610. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65611. samplesRead = framesRead * pWav->channels;
  65612. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65613. DRWAV_ASSERT(DRWAV_FALSE);
  65614. break;
  65615. }
  65616. drwav_alaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  65617. pBufferOut += samplesRead;
  65618. framesToRead -= framesRead;
  65619. totalFramesRead += framesRead;
  65620. }
  65621. return totalFramesRead;
  65622. }
  65623. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_f32__mulaw(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65624. {
  65625. drwav_uint64 totalFramesRead;
  65626. drwav_uint8 sampleData[4096] = {0};
  65627. drwav_uint32 bytesPerFrame;
  65628. drwav_uint32 bytesPerSample;
  65629. drwav_uint64 samplesRead;
  65630. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65631. if (bytesPerFrame == 0) {
  65632. return 0;
  65633. }
  65634. bytesPerSample = bytesPerFrame / pWav->channels;
  65635. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65636. return 0;
  65637. }
  65638. totalFramesRead = 0;
  65639. while (framesToRead > 0) {
  65640. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65641. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65642. if (framesRead == 0) {
  65643. break;
  65644. }
  65645. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65646. samplesRead = framesRead * pWav->channels;
  65647. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65648. DRWAV_ASSERT(DRWAV_FALSE);
  65649. break;
  65650. }
  65651. drwav_mulaw_to_f32(pBufferOut, sampleData, (size_t)samplesRead);
  65652. pBufferOut += samplesRead;
  65653. framesToRead -= framesRead;
  65654. totalFramesRead += framesRead;
  65655. }
  65656. return totalFramesRead;
  65657. }
  65658. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65659. {
  65660. if (pWav == NULL || framesToRead == 0) {
  65661. return 0;
  65662. }
  65663. if (pBufferOut == NULL) {
  65664. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  65665. }
  65666. if (framesToRead * pWav->channels * sizeof(float) > DRWAV_SIZE_MAX) {
  65667. framesToRead = DRWAV_SIZE_MAX / sizeof(float) / pWav->channels;
  65668. }
  65669. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  65670. return drwav_read_pcm_frames_f32__pcm(pWav, framesToRead, pBufferOut);
  65671. }
  65672. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  65673. return drwav_read_pcm_frames_f32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  65674. }
  65675. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  65676. return drwav_read_pcm_frames_f32__ieee(pWav, framesToRead, pBufferOut);
  65677. }
  65678. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  65679. return drwav_read_pcm_frames_f32__alaw(pWav, framesToRead, pBufferOut);
  65680. }
  65681. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  65682. return drwav_read_pcm_frames_f32__mulaw(pWav, framesToRead, pBufferOut);
  65683. }
  65684. return 0;
  65685. }
  65686. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32le(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65687. {
  65688. drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  65689. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  65690. drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  65691. }
  65692. return framesRead;
  65693. }
  65694. DRWAV_API drwav_uint64 drwav_read_pcm_frames_f32be(drwav* pWav, drwav_uint64 framesToRead, float* pBufferOut)
  65695. {
  65696. drwav_uint64 framesRead = drwav_read_pcm_frames_f32(pWav, framesToRead, pBufferOut);
  65697. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  65698. drwav__bswap_samples_f32(pBufferOut, framesRead*pWav->channels);
  65699. }
  65700. return framesRead;
  65701. }
  65702. DRWAV_API void drwav_u8_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65703. {
  65704. size_t i;
  65705. if (pOut == NULL || pIn == NULL) {
  65706. return;
  65707. }
  65708. #ifdef DR_WAV_LIBSNDFILE_COMPAT
  65709. for (i = 0; i < sampleCount; ++i) {
  65710. *pOut++ = (pIn[i] / 256.0f) * 2 - 1;
  65711. }
  65712. #else
  65713. for (i = 0; i < sampleCount; ++i) {
  65714. float x = pIn[i];
  65715. x = x * 0.00784313725490196078f;
  65716. x = x - 1;
  65717. *pOut++ = x;
  65718. }
  65719. #endif
  65720. }
  65721. DRWAV_API void drwav_s16_to_f32(float* pOut, const drwav_int16* pIn, size_t sampleCount)
  65722. {
  65723. size_t i;
  65724. if (pOut == NULL || pIn == NULL) {
  65725. return;
  65726. }
  65727. for (i = 0; i < sampleCount; ++i) {
  65728. *pOut++ = pIn[i] * 0.000030517578125f;
  65729. }
  65730. }
  65731. DRWAV_API void drwav_s24_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65732. {
  65733. size_t i;
  65734. if (pOut == NULL || pIn == NULL) {
  65735. return;
  65736. }
  65737. for (i = 0; i < sampleCount; ++i) {
  65738. double x;
  65739. drwav_uint32 a = ((drwav_uint32)(pIn[i*3+0]) << 8);
  65740. drwav_uint32 b = ((drwav_uint32)(pIn[i*3+1]) << 16);
  65741. drwav_uint32 c = ((drwav_uint32)(pIn[i*3+2]) << 24);
  65742. x = (double)((drwav_int32)(a | b | c) >> 8);
  65743. *pOut++ = (float)(x * 0.00000011920928955078125);
  65744. }
  65745. }
  65746. DRWAV_API void drwav_s32_to_f32(float* pOut, const drwav_int32* pIn, size_t sampleCount)
  65747. {
  65748. size_t i;
  65749. if (pOut == NULL || pIn == NULL) {
  65750. return;
  65751. }
  65752. for (i = 0; i < sampleCount; ++i) {
  65753. *pOut++ = (float)(pIn[i] / 2147483648.0);
  65754. }
  65755. }
  65756. DRWAV_API void drwav_f64_to_f32(float* pOut, const double* pIn, size_t sampleCount)
  65757. {
  65758. size_t i;
  65759. if (pOut == NULL || pIn == NULL) {
  65760. return;
  65761. }
  65762. for (i = 0; i < sampleCount; ++i) {
  65763. *pOut++ = (float)pIn[i];
  65764. }
  65765. }
  65766. DRWAV_API void drwav_alaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65767. {
  65768. size_t i;
  65769. if (pOut == NULL || pIn == NULL) {
  65770. return;
  65771. }
  65772. for (i = 0; i < sampleCount; ++i) {
  65773. *pOut++ = drwav__alaw_to_s16(pIn[i]) / 32768.0f;
  65774. }
  65775. }
  65776. DRWAV_API void drwav_mulaw_to_f32(float* pOut, const drwav_uint8* pIn, size_t sampleCount)
  65777. {
  65778. size_t i;
  65779. if (pOut == NULL || pIn == NULL) {
  65780. return;
  65781. }
  65782. for (i = 0; i < sampleCount; ++i) {
  65783. *pOut++ = drwav__mulaw_to_s16(pIn[i]) / 32768.0f;
  65784. }
  65785. }
  65786. DRWAV_PRIVATE void drwav__pcm_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  65787. {
  65788. unsigned int i;
  65789. if (bytesPerSample == 1) {
  65790. drwav_u8_to_s32(pOut, pIn, totalSampleCount);
  65791. return;
  65792. }
  65793. if (bytesPerSample == 2) {
  65794. drwav_s16_to_s32(pOut, (const drwav_int16*)pIn, totalSampleCount);
  65795. return;
  65796. }
  65797. if (bytesPerSample == 3) {
  65798. drwav_s24_to_s32(pOut, pIn, totalSampleCount);
  65799. return;
  65800. }
  65801. if (bytesPerSample == 4) {
  65802. for (i = 0; i < totalSampleCount; ++i) {
  65803. *pOut++ = ((const drwav_int32*)pIn)[i];
  65804. }
  65805. return;
  65806. }
  65807. if (bytesPerSample > 8) {
  65808. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  65809. return;
  65810. }
  65811. for (i = 0; i < totalSampleCount; ++i) {
  65812. drwav_uint64 sample = 0;
  65813. unsigned int shift = (8 - bytesPerSample) * 8;
  65814. unsigned int j;
  65815. for (j = 0; j < bytesPerSample; j += 1) {
  65816. DRWAV_ASSERT(j < 8);
  65817. sample |= (drwav_uint64)(pIn[j]) << shift;
  65818. shift += 8;
  65819. }
  65820. pIn += j;
  65821. *pOut++ = (drwav_int32)((drwav_int64)sample >> 32);
  65822. }
  65823. }
  65824. DRWAV_PRIVATE void drwav__ieee_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t totalSampleCount, unsigned int bytesPerSample)
  65825. {
  65826. if (bytesPerSample == 4) {
  65827. drwav_f32_to_s32(pOut, (const float*)pIn, totalSampleCount);
  65828. return;
  65829. } else if (bytesPerSample == 8) {
  65830. drwav_f64_to_s32(pOut, (const double*)pIn, totalSampleCount);
  65831. return;
  65832. } else {
  65833. DRWAV_ZERO_MEMORY(pOut, totalSampleCount * sizeof(*pOut));
  65834. return;
  65835. }
  65836. }
  65837. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__pcm(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65838. {
  65839. drwav_uint64 totalFramesRead;
  65840. drwav_uint8 sampleData[4096] = {0};
  65841. drwav_uint32 bytesPerFrame;
  65842. drwav_uint32 bytesPerSample;
  65843. drwav_uint64 samplesRead;
  65844. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM && pWav->bitsPerSample == 32) {
  65845. return drwav_read_pcm_frames(pWav, framesToRead, pBufferOut);
  65846. }
  65847. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65848. if (bytesPerFrame == 0) {
  65849. return 0;
  65850. }
  65851. bytesPerSample = bytesPerFrame / pWav->channels;
  65852. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65853. return 0;
  65854. }
  65855. totalFramesRead = 0;
  65856. while (framesToRead > 0) {
  65857. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65858. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65859. if (framesRead == 0) {
  65860. break;
  65861. }
  65862. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65863. samplesRead = framesRead * pWav->channels;
  65864. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65865. DRWAV_ASSERT(DRWAV_FALSE);
  65866. break;
  65867. }
  65868. drwav__pcm_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65869. pBufferOut += samplesRead;
  65870. framesToRead -= framesRead;
  65871. totalFramesRead += framesRead;
  65872. }
  65873. return totalFramesRead;
  65874. }
  65875. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__msadpcm_ima(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65876. {
  65877. drwav_uint64 totalFramesRead = 0;
  65878. drwav_int16 samples16[2048];
  65879. while (framesToRead > 0) {
  65880. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, drwav_countof(samples16)/pWav->channels);
  65881. drwav_uint64 framesRead = drwav_read_pcm_frames_s16(pWav, framesToReadThisIteration, samples16);
  65882. if (framesRead == 0) {
  65883. break;
  65884. }
  65885. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65886. drwav_s16_to_s32(pBufferOut, samples16, (size_t)(framesRead*pWav->channels));
  65887. pBufferOut += framesRead*pWav->channels;
  65888. framesToRead -= framesRead;
  65889. totalFramesRead += framesRead;
  65890. }
  65891. return totalFramesRead;
  65892. }
  65893. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__ieee(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65894. {
  65895. drwav_uint64 totalFramesRead;
  65896. drwav_uint8 sampleData[4096] = {0};
  65897. drwav_uint32 bytesPerFrame;
  65898. drwav_uint32 bytesPerSample;
  65899. drwav_uint64 samplesRead;
  65900. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65901. if (bytesPerFrame == 0) {
  65902. return 0;
  65903. }
  65904. bytesPerSample = bytesPerFrame / pWav->channels;
  65905. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65906. return 0;
  65907. }
  65908. totalFramesRead = 0;
  65909. while (framesToRead > 0) {
  65910. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65911. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65912. if (framesRead == 0) {
  65913. break;
  65914. }
  65915. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65916. samplesRead = framesRead * pWav->channels;
  65917. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65918. DRWAV_ASSERT(DRWAV_FALSE);
  65919. break;
  65920. }
  65921. drwav__ieee_to_s32(pBufferOut, sampleData, (size_t)samplesRead, bytesPerSample);
  65922. pBufferOut += samplesRead;
  65923. framesToRead -= framesRead;
  65924. totalFramesRead += framesRead;
  65925. }
  65926. return totalFramesRead;
  65927. }
  65928. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__alaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65929. {
  65930. drwav_uint64 totalFramesRead;
  65931. drwav_uint8 sampleData[4096] = {0};
  65932. drwav_uint32 bytesPerFrame;
  65933. drwav_uint32 bytesPerSample;
  65934. drwav_uint64 samplesRead;
  65935. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65936. if (bytesPerFrame == 0) {
  65937. return 0;
  65938. }
  65939. bytesPerSample = bytesPerFrame / pWav->channels;
  65940. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65941. return 0;
  65942. }
  65943. totalFramesRead = 0;
  65944. while (framesToRead > 0) {
  65945. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65946. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65947. if (framesRead == 0) {
  65948. break;
  65949. }
  65950. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65951. samplesRead = framesRead * pWav->channels;
  65952. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65953. DRWAV_ASSERT(DRWAV_FALSE);
  65954. break;
  65955. }
  65956. drwav_alaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  65957. pBufferOut += samplesRead;
  65958. framesToRead -= framesRead;
  65959. totalFramesRead += framesRead;
  65960. }
  65961. return totalFramesRead;
  65962. }
  65963. DRWAV_PRIVATE drwav_uint64 drwav_read_pcm_frames_s32__mulaw(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65964. {
  65965. drwav_uint64 totalFramesRead;
  65966. drwav_uint8 sampleData[4096] = {0};
  65967. drwav_uint32 bytesPerFrame;
  65968. drwav_uint32 bytesPerSample;
  65969. drwav_uint64 samplesRead;
  65970. bytesPerFrame = drwav_get_bytes_per_pcm_frame(pWav);
  65971. if (bytesPerFrame == 0) {
  65972. return 0;
  65973. }
  65974. bytesPerSample = bytesPerFrame / pWav->channels;
  65975. if (bytesPerSample == 0 || (bytesPerFrame % pWav->channels) != 0) {
  65976. return 0;
  65977. }
  65978. totalFramesRead = 0;
  65979. while (framesToRead > 0) {
  65980. drwav_uint64 framesToReadThisIteration = drwav_min(framesToRead, sizeof(sampleData)/bytesPerFrame);
  65981. drwav_uint64 framesRead = drwav_read_pcm_frames(pWav, framesToReadThisIteration, sampleData);
  65982. if (framesRead == 0) {
  65983. break;
  65984. }
  65985. DRWAV_ASSERT(framesRead <= framesToReadThisIteration);
  65986. samplesRead = framesRead * pWav->channels;
  65987. if ((samplesRead * bytesPerSample) > sizeof(sampleData)) {
  65988. DRWAV_ASSERT(DRWAV_FALSE);
  65989. break;
  65990. }
  65991. drwav_mulaw_to_s32(pBufferOut, sampleData, (size_t)samplesRead);
  65992. pBufferOut += samplesRead;
  65993. framesToRead -= framesRead;
  65994. totalFramesRead += framesRead;
  65995. }
  65996. return totalFramesRead;
  65997. }
  65998. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  65999. {
  66000. if (pWav == NULL || framesToRead == 0) {
  66001. return 0;
  66002. }
  66003. if (pBufferOut == NULL) {
  66004. return drwav_read_pcm_frames(pWav, framesToRead, NULL);
  66005. }
  66006. if (framesToRead * pWav->channels * sizeof(drwav_int32) > DRWAV_SIZE_MAX) {
  66007. framesToRead = DRWAV_SIZE_MAX / sizeof(drwav_int32) / pWav->channels;
  66008. }
  66009. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_PCM) {
  66010. return drwav_read_pcm_frames_s32__pcm(pWav, framesToRead, pBufferOut);
  66011. }
  66012. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ADPCM || pWav->translatedFormatTag == DR_WAVE_FORMAT_DVI_ADPCM) {
  66013. return drwav_read_pcm_frames_s32__msadpcm_ima(pWav, framesToRead, pBufferOut);
  66014. }
  66015. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_IEEE_FLOAT) {
  66016. return drwav_read_pcm_frames_s32__ieee(pWav, framesToRead, pBufferOut);
  66017. }
  66018. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_ALAW) {
  66019. return drwav_read_pcm_frames_s32__alaw(pWav, framesToRead, pBufferOut);
  66020. }
  66021. if (pWav->translatedFormatTag == DR_WAVE_FORMAT_MULAW) {
  66022. return drwav_read_pcm_frames_s32__mulaw(pWav, framesToRead, pBufferOut);
  66023. }
  66024. return 0;
  66025. }
  66026. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32le(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  66027. {
  66028. drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  66029. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_FALSE) {
  66030. drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  66031. }
  66032. return framesRead;
  66033. }
  66034. DRWAV_API drwav_uint64 drwav_read_pcm_frames_s32be(drwav* pWav, drwav_uint64 framesToRead, drwav_int32* pBufferOut)
  66035. {
  66036. drwav_uint64 framesRead = drwav_read_pcm_frames_s32(pWav, framesToRead, pBufferOut);
  66037. if (pBufferOut != NULL && drwav__is_little_endian() == DRWAV_TRUE) {
  66038. drwav__bswap_samples_s32(pBufferOut, framesRead*pWav->channels);
  66039. }
  66040. return framesRead;
  66041. }
  66042. DRWAV_API void drwav_u8_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  66043. {
  66044. size_t i;
  66045. if (pOut == NULL || pIn == NULL) {
  66046. return;
  66047. }
  66048. for (i = 0; i < sampleCount; ++i) {
  66049. *pOut++ = ((int)pIn[i] - 128) << 24;
  66050. }
  66051. }
  66052. DRWAV_API void drwav_s16_to_s32(drwav_int32* pOut, const drwav_int16* pIn, size_t sampleCount)
  66053. {
  66054. size_t i;
  66055. if (pOut == NULL || pIn == NULL) {
  66056. return;
  66057. }
  66058. for (i = 0; i < sampleCount; ++i) {
  66059. *pOut++ = pIn[i] << 16;
  66060. }
  66061. }
  66062. DRWAV_API void drwav_s24_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  66063. {
  66064. size_t i;
  66065. if (pOut == NULL || pIn == NULL) {
  66066. return;
  66067. }
  66068. for (i = 0; i < sampleCount; ++i) {
  66069. unsigned int s0 = pIn[i*3 + 0];
  66070. unsigned int s1 = pIn[i*3 + 1];
  66071. unsigned int s2 = pIn[i*3 + 2];
  66072. drwav_int32 sample32 = (drwav_int32)((s0 << 8) | (s1 << 16) | (s2 << 24));
  66073. *pOut++ = sample32;
  66074. }
  66075. }
  66076. DRWAV_API void drwav_f32_to_s32(drwav_int32* pOut, const float* pIn, size_t sampleCount)
  66077. {
  66078. size_t i;
  66079. if (pOut == NULL || pIn == NULL) {
  66080. return;
  66081. }
  66082. for (i = 0; i < sampleCount; ++i) {
  66083. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  66084. }
  66085. }
  66086. DRWAV_API void drwav_f64_to_s32(drwav_int32* pOut, const double* pIn, size_t sampleCount)
  66087. {
  66088. size_t i;
  66089. if (pOut == NULL || pIn == NULL) {
  66090. return;
  66091. }
  66092. for (i = 0; i < sampleCount; ++i) {
  66093. *pOut++ = (drwav_int32)(2147483648.0 * pIn[i]);
  66094. }
  66095. }
  66096. DRWAV_API void drwav_alaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  66097. {
  66098. size_t i;
  66099. if (pOut == NULL || pIn == NULL) {
  66100. return;
  66101. }
  66102. for (i = 0; i < sampleCount; ++i) {
  66103. *pOut++ = ((drwav_int32)drwav__alaw_to_s16(pIn[i])) << 16;
  66104. }
  66105. }
  66106. DRWAV_API void drwav_mulaw_to_s32(drwav_int32* pOut, const drwav_uint8* pIn, size_t sampleCount)
  66107. {
  66108. size_t i;
  66109. if (pOut == NULL || pIn == NULL) {
  66110. return;
  66111. }
  66112. for (i= 0; i < sampleCount; ++i) {
  66113. *pOut++ = ((drwav_int32)drwav__mulaw_to_s16(pIn[i])) << 16;
  66114. }
  66115. }
  66116. DRWAV_PRIVATE drwav_int16* drwav__read_pcm_frames_and_close_s16(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  66117. {
  66118. drwav_uint64 sampleDataSize;
  66119. drwav_int16* pSampleData;
  66120. drwav_uint64 framesRead;
  66121. DRWAV_ASSERT(pWav != NULL);
  66122. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int16);
  66123. if (sampleDataSize > DRWAV_SIZE_MAX) {
  66124. drwav_uninit(pWav);
  66125. return NULL;
  66126. }
  66127. pSampleData = (drwav_int16*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  66128. if (pSampleData == NULL) {
  66129. drwav_uninit(pWav);
  66130. return NULL;
  66131. }
  66132. framesRead = drwav_read_pcm_frames_s16(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  66133. if (framesRead != pWav->totalPCMFrameCount) {
  66134. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  66135. drwav_uninit(pWav);
  66136. return NULL;
  66137. }
  66138. drwav_uninit(pWav);
  66139. if (sampleRate) {
  66140. *sampleRate = pWav->sampleRate;
  66141. }
  66142. if (channels) {
  66143. *channels = pWav->channels;
  66144. }
  66145. if (totalFrameCount) {
  66146. *totalFrameCount = pWav->totalPCMFrameCount;
  66147. }
  66148. return pSampleData;
  66149. }
  66150. DRWAV_PRIVATE float* drwav__read_pcm_frames_and_close_f32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  66151. {
  66152. drwav_uint64 sampleDataSize;
  66153. float* pSampleData;
  66154. drwav_uint64 framesRead;
  66155. DRWAV_ASSERT(pWav != NULL);
  66156. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(float);
  66157. if (sampleDataSize > DRWAV_SIZE_MAX) {
  66158. drwav_uninit(pWav);
  66159. return NULL;
  66160. }
  66161. pSampleData = (float*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  66162. if (pSampleData == NULL) {
  66163. drwav_uninit(pWav);
  66164. return NULL;
  66165. }
  66166. framesRead = drwav_read_pcm_frames_f32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  66167. if (framesRead != pWav->totalPCMFrameCount) {
  66168. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  66169. drwav_uninit(pWav);
  66170. return NULL;
  66171. }
  66172. drwav_uninit(pWav);
  66173. if (sampleRate) {
  66174. *sampleRate = pWav->sampleRate;
  66175. }
  66176. if (channels) {
  66177. *channels = pWav->channels;
  66178. }
  66179. if (totalFrameCount) {
  66180. *totalFrameCount = pWav->totalPCMFrameCount;
  66181. }
  66182. return pSampleData;
  66183. }
  66184. DRWAV_PRIVATE drwav_int32* drwav__read_pcm_frames_and_close_s32(drwav* pWav, unsigned int* channels, unsigned int* sampleRate, drwav_uint64* totalFrameCount)
  66185. {
  66186. drwav_uint64 sampleDataSize;
  66187. drwav_int32* pSampleData;
  66188. drwav_uint64 framesRead;
  66189. DRWAV_ASSERT(pWav != NULL);
  66190. sampleDataSize = pWav->totalPCMFrameCount * pWav->channels * sizeof(drwav_int32);
  66191. if (sampleDataSize > DRWAV_SIZE_MAX) {
  66192. drwav_uninit(pWav);
  66193. return NULL;
  66194. }
  66195. pSampleData = (drwav_int32*)drwav__malloc_from_callbacks((size_t)sampleDataSize, &pWav->allocationCallbacks);
  66196. if (pSampleData == NULL) {
  66197. drwav_uninit(pWav);
  66198. return NULL;
  66199. }
  66200. framesRead = drwav_read_pcm_frames_s32(pWav, (size_t)pWav->totalPCMFrameCount, pSampleData);
  66201. if (framesRead != pWav->totalPCMFrameCount) {
  66202. drwav__free_from_callbacks(pSampleData, &pWav->allocationCallbacks);
  66203. drwav_uninit(pWav);
  66204. return NULL;
  66205. }
  66206. drwav_uninit(pWav);
  66207. if (sampleRate) {
  66208. *sampleRate = pWav->sampleRate;
  66209. }
  66210. if (channels) {
  66211. *channels = pWav->channels;
  66212. }
  66213. if (totalFrameCount) {
  66214. *totalFrameCount = pWav->totalPCMFrameCount;
  66215. }
  66216. return pSampleData;
  66217. }
  66218. DRWAV_API drwav_int16* drwav_open_and_read_pcm_frames_s16(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66219. {
  66220. drwav wav;
  66221. if (channelsOut) {
  66222. *channelsOut = 0;
  66223. }
  66224. if (sampleRateOut) {
  66225. *sampleRateOut = 0;
  66226. }
  66227. if (totalFrameCountOut) {
  66228. *totalFrameCountOut = 0;
  66229. }
  66230. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  66231. return NULL;
  66232. }
  66233. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66234. }
  66235. DRWAV_API float* drwav_open_and_read_pcm_frames_f32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66236. {
  66237. drwav wav;
  66238. if (channelsOut) {
  66239. *channelsOut = 0;
  66240. }
  66241. if (sampleRateOut) {
  66242. *sampleRateOut = 0;
  66243. }
  66244. if (totalFrameCountOut) {
  66245. *totalFrameCountOut = 0;
  66246. }
  66247. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  66248. return NULL;
  66249. }
  66250. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66251. }
  66252. DRWAV_API drwav_int32* drwav_open_and_read_pcm_frames_s32(drwav_read_proc onRead, drwav_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66253. {
  66254. drwav wav;
  66255. if (channelsOut) {
  66256. *channelsOut = 0;
  66257. }
  66258. if (sampleRateOut) {
  66259. *sampleRateOut = 0;
  66260. }
  66261. if (totalFrameCountOut) {
  66262. *totalFrameCountOut = 0;
  66263. }
  66264. if (!drwav_init(&wav, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  66265. return NULL;
  66266. }
  66267. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66268. }
  66269. #ifndef DR_WAV_NO_STDIO
  66270. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66271. {
  66272. drwav wav;
  66273. if (channelsOut) {
  66274. *channelsOut = 0;
  66275. }
  66276. if (sampleRateOut) {
  66277. *sampleRateOut = 0;
  66278. }
  66279. if (totalFrameCountOut) {
  66280. *totalFrameCountOut = 0;
  66281. }
  66282. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  66283. return NULL;
  66284. }
  66285. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66286. }
  66287. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66288. {
  66289. drwav wav;
  66290. if (channelsOut) {
  66291. *channelsOut = 0;
  66292. }
  66293. if (sampleRateOut) {
  66294. *sampleRateOut = 0;
  66295. }
  66296. if (totalFrameCountOut) {
  66297. *totalFrameCountOut = 0;
  66298. }
  66299. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  66300. return NULL;
  66301. }
  66302. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66303. }
  66304. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66305. {
  66306. drwav wav;
  66307. if (channelsOut) {
  66308. *channelsOut = 0;
  66309. }
  66310. if (sampleRateOut) {
  66311. *sampleRateOut = 0;
  66312. }
  66313. if (totalFrameCountOut) {
  66314. *totalFrameCountOut = 0;
  66315. }
  66316. if (!drwav_init_file(&wav, filename, pAllocationCallbacks)) {
  66317. return NULL;
  66318. }
  66319. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66320. }
  66321. #ifndef DR_WAV_NO_WCHAR
  66322. DRWAV_API drwav_int16* drwav_open_file_and_read_pcm_frames_s16_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66323. {
  66324. drwav wav;
  66325. if (sampleRateOut) {
  66326. *sampleRateOut = 0;
  66327. }
  66328. if (channelsOut) {
  66329. *channelsOut = 0;
  66330. }
  66331. if (totalFrameCountOut) {
  66332. *totalFrameCountOut = 0;
  66333. }
  66334. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  66335. return NULL;
  66336. }
  66337. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66338. }
  66339. DRWAV_API float* drwav_open_file_and_read_pcm_frames_f32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66340. {
  66341. drwav wav;
  66342. if (sampleRateOut) {
  66343. *sampleRateOut = 0;
  66344. }
  66345. if (channelsOut) {
  66346. *channelsOut = 0;
  66347. }
  66348. if (totalFrameCountOut) {
  66349. *totalFrameCountOut = 0;
  66350. }
  66351. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  66352. return NULL;
  66353. }
  66354. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66355. }
  66356. DRWAV_API drwav_int32* drwav_open_file_and_read_pcm_frames_s32_w(const wchar_t* filename, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66357. {
  66358. drwav wav;
  66359. if (sampleRateOut) {
  66360. *sampleRateOut = 0;
  66361. }
  66362. if (channelsOut) {
  66363. *channelsOut = 0;
  66364. }
  66365. if (totalFrameCountOut) {
  66366. *totalFrameCountOut = 0;
  66367. }
  66368. if (!drwav_init_file_w(&wav, filename, pAllocationCallbacks)) {
  66369. return NULL;
  66370. }
  66371. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66372. }
  66373. #endif
  66374. #endif
  66375. DRWAV_API drwav_int16* drwav_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66376. {
  66377. drwav wav;
  66378. if (channelsOut) {
  66379. *channelsOut = 0;
  66380. }
  66381. if (sampleRateOut) {
  66382. *sampleRateOut = 0;
  66383. }
  66384. if (totalFrameCountOut) {
  66385. *totalFrameCountOut = 0;
  66386. }
  66387. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  66388. return NULL;
  66389. }
  66390. return drwav__read_pcm_frames_and_close_s16(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66391. }
  66392. DRWAV_API float* drwav_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66393. {
  66394. drwav wav;
  66395. if (channelsOut) {
  66396. *channelsOut = 0;
  66397. }
  66398. if (sampleRateOut) {
  66399. *sampleRateOut = 0;
  66400. }
  66401. if (totalFrameCountOut) {
  66402. *totalFrameCountOut = 0;
  66403. }
  66404. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  66405. return NULL;
  66406. }
  66407. return drwav__read_pcm_frames_and_close_f32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66408. }
  66409. DRWAV_API drwav_int32* drwav_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channelsOut, unsigned int* sampleRateOut, drwav_uint64* totalFrameCountOut, const drwav_allocation_callbacks* pAllocationCallbacks)
  66410. {
  66411. drwav wav;
  66412. if (channelsOut) {
  66413. *channelsOut = 0;
  66414. }
  66415. if (sampleRateOut) {
  66416. *sampleRateOut = 0;
  66417. }
  66418. if (totalFrameCountOut) {
  66419. *totalFrameCountOut = 0;
  66420. }
  66421. if (!drwav_init_memory(&wav, data, dataSize, pAllocationCallbacks)) {
  66422. return NULL;
  66423. }
  66424. return drwav__read_pcm_frames_and_close_s32(&wav, channelsOut, sampleRateOut, totalFrameCountOut);
  66425. }
  66426. #endif
  66427. DRWAV_API void drwav_free(void* p, const drwav_allocation_callbacks* pAllocationCallbacks)
  66428. {
  66429. if (pAllocationCallbacks != NULL) {
  66430. drwav__free_from_callbacks(p, pAllocationCallbacks);
  66431. } else {
  66432. drwav__free_default(p, NULL);
  66433. }
  66434. }
  66435. DRWAV_API drwav_uint16 drwav_bytes_to_u16(const drwav_uint8* data)
  66436. {
  66437. return ((drwav_uint16)data[0] << 0) | ((drwav_uint16)data[1] << 8);
  66438. }
  66439. DRWAV_API drwav_int16 drwav_bytes_to_s16(const drwav_uint8* data)
  66440. {
  66441. return (drwav_int16)drwav_bytes_to_u16(data);
  66442. }
  66443. DRWAV_API drwav_uint32 drwav_bytes_to_u32(const drwav_uint8* data)
  66444. {
  66445. return ((drwav_uint32)data[0] << 0) | ((drwav_uint32)data[1] << 8) | ((drwav_uint32)data[2] << 16) | ((drwav_uint32)data[3] << 24);
  66446. }
  66447. DRWAV_API float drwav_bytes_to_f32(const drwav_uint8* data)
  66448. {
  66449. union {
  66450. drwav_uint32 u32;
  66451. float f32;
  66452. } value;
  66453. value.u32 = drwav_bytes_to_u32(data);
  66454. return value.f32;
  66455. }
  66456. DRWAV_API drwav_int32 drwav_bytes_to_s32(const drwav_uint8* data)
  66457. {
  66458. return (drwav_int32)drwav_bytes_to_u32(data);
  66459. }
  66460. DRWAV_API drwav_uint64 drwav_bytes_to_u64(const drwav_uint8* data)
  66461. {
  66462. return
  66463. ((drwav_uint64)data[0] << 0) | ((drwav_uint64)data[1] << 8) | ((drwav_uint64)data[2] << 16) | ((drwav_uint64)data[3] << 24) |
  66464. ((drwav_uint64)data[4] << 32) | ((drwav_uint64)data[5] << 40) | ((drwav_uint64)data[6] << 48) | ((drwav_uint64)data[7] << 56);
  66465. }
  66466. DRWAV_API drwav_int64 drwav_bytes_to_s64(const drwav_uint8* data)
  66467. {
  66468. return (drwav_int64)drwav_bytes_to_u64(data);
  66469. }
  66470. DRWAV_API drwav_bool32 drwav_guid_equal(const drwav_uint8 a[16], const drwav_uint8 b[16])
  66471. {
  66472. int i;
  66473. for (i = 0; i < 16; i += 1) {
  66474. if (a[i] != b[i]) {
  66475. return DRWAV_FALSE;
  66476. }
  66477. }
  66478. return DRWAV_TRUE;
  66479. }
  66480. DRWAV_API drwav_bool32 drwav_fourcc_equal(const drwav_uint8* a, const char* b)
  66481. {
  66482. return
  66483. a[0] == b[0] &&
  66484. a[1] == b[1] &&
  66485. a[2] == b[2] &&
  66486. a[3] == b[3];
  66487. }
  66488. #ifdef __MRC__
  66489. #pragma options opt reset
  66490. #endif
  66491. #endif
  66492. /* dr_wav_c end */
  66493. #endif /* DRWAV_IMPLEMENTATION */
  66494. #endif /* MA_NO_WAV */
  66495. #if !defined(MA_NO_FLAC) && !defined(MA_NO_DECODING)
  66496. #if !defined(DR_FLAC_IMPLEMENTATION) && !defined(DRFLAC_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  66497. /* dr_flac_c begin */
  66498. #ifndef dr_flac_c
  66499. #define dr_flac_c
  66500. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  66501. #pragma GCC diagnostic push
  66502. #if __GNUC__ >= 7
  66503. #pragma GCC diagnostic ignored "-Wimplicit-fallthrough"
  66504. #endif
  66505. #endif
  66506. #ifdef __linux__
  66507. #ifndef _BSD_SOURCE
  66508. #define _BSD_SOURCE
  66509. #endif
  66510. #ifndef _DEFAULT_SOURCE
  66511. #define _DEFAULT_SOURCE
  66512. #endif
  66513. #ifndef __USE_BSD
  66514. #define __USE_BSD
  66515. #endif
  66516. #include <endian.h>
  66517. #endif
  66518. #include <stdlib.h>
  66519. #include <string.h>
  66520. #ifdef _MSC_VER
  66521. #define DRFLAC_INLINE __forceinline
  66522. #elif defined(__GNUC__)
  66523. #if defined(__STRICT_ANSI__)
  66524. #define DRFLAC_GNUC_INLINE_HINT __inline__
  66525. #else
  66526. #define DRFLAC_GNUC_INLINE_HINT inline
  66527. #endif
  66528. #if (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 2)) || defined(__clang__)
  66529. #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT __attribute__((always_inline))
  66530. #else
  66531. #define DRFLAC_INLINE DRFLAC_GNUC_INLINE_HINT
  66532. #endif
  66533. #elif defined(__WATCOMC__)
  66534. #define DRFLAC_INLINE __inline
  66535. #else
  66536. #define DRFLAC_INLINE
  66537. #endif
  66538. #if defined(__x86_64__) || defined(_M_X64)
  66539. #define DRFLAC_X64
  66540. #elif defined(__i386) || defined(_M_IX86)
  66541. #define DRFLAC_X86
  66542. #elif defined(__arm__) || defined(_M_ARM) || defined(__arm64) || defined(__arm64__) || defined(__aarch64__) || defined(_M_ARM64)
  66543. #define DRFLAC_ARM
  66544. #endif
  66545. #if !defined(DR_FLAC_NO_SIMD)
  66546. #if defined(DRFLAC_X64) || defined(DRFLAC_X86)
  66547. #if defined(_MSC_VER) && !defined(__clang__)
  66548. #if _MSC_VER >= 1400 && !defined(DRFLAC_NO_SSE2)
  66549. #define DRFLAC_SUPPORT_SSE2
  66550. #endif
  66551. #if _MSC_VER >= 1600 && !defined(DRFLAC_NO_SSE41)
  66552. #define DRFLAC_SUPPORT_SSE41
  66553. #endif
  66554. #elif defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)))
  66555. #if defined(__SSE2__) && !defined(DRFLAC_NO_SSE2)
  66556. #define DRFLAC_SUPPORT_SSE2
  66557. #endif
  66558. #if defined(__SSE4_1__) && !defined(DRFLAC_NO_SSE41)
  66559. #define DRFLAC_SUPPORT_SSE41
  66560. #endif
  66561. #endif
  66562. #if !defined(__GNUC__) && !defined(__clang__) && defined(__has_include)
  66563. #if !defined(DRFLAC_SUPPORT_SSE2) && !defined(DRFLAC_NO_SSE2) && __has_include(<emmintrin.h>)
  66564. #define DRFLAC_SUPPORT_SSE2
  66565. #endif
  66566. #if !defined(DRFLAC_SUPPORT_SSE41) && !defined(DRFLAC_NO_SSE41) && __has_include(<smmintrin.h>)
  66567. #define DRFLAC_SUPPORT_SSE41
  66568. #endif
  66569. #endif
  66570. #if defined(DRFLAC_SUPPORT_SSE41)
  66571. #include <smmintrin.h>
  66572. #elif defined(DRFLAC_SUPPORT_SSE2)
  66573. #include <emmintrin.h>
  66574. #endif
  66575. #endif
  66576. #if defined(DRFLAC_ARM)
  66577. #if !defined(DRFLAC_NO_NEON) && (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  66578. #define DRFLAC_SUPPORT_NEON
  66579. #include <arm_neon.h>
  66580. #endif
  66581. #endif
  66582. #endif
  66583. #if !defined(DR_FLAC_NO_SIMD) && (defined(DRFLAC_X86) || defined(DRFLAC_X64))
  66584. #if defined(_MSC_VER) && !defined(__clang__)
  66585. #if _MSC_VER >= 1400
  66586. #include <intrin.h>
  66587. static void drflac__cpuid(int info[4], int fid)
  66588. {
  66589. __cpuid(info, fid);
  66590. }
  66591. #else
  66592. #define DRFLAC_NO_CPUID
  66593. #endif
  66594. #else
  66595. #if defined(__GNUC__) || defined(__clang__)
  66596. static void drflac__cpuid(int info[4], int fid)
  66597. {
  66598. #if defined(DRFLAC_X86) && defined(__PIC__)
  66599. __asm__ __volatile__ (
  66600. "xchg{l} {%%}ebx, %k1;"
  66601. "cpuid;"
  66602. "xchg{l} {%%}ebx, %k1;"
  66603. : "=a"(info[0]), "=&r"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  66604. );
  66605. #else
  66606. __asm__ __volatile__ (
  66607. "cpuid" : "=a"(info[0]), "=b"(info[1]), "=c"(info[2]), "=d"(info[3]) : "a"(fid), "c"(0)
  66608. );
  66609. #endif
  66610. }
  66611. #else
  66612. #define DRFLAC_NO_CPUID
  66613. #endif
  66614. #endif
  66615. #else
  66616. #define DRFLAC_NO_CPUID
  66617. #endif
  66618. static DRFLAC_INLINE drflac_bool32 drflac_has_sse2(void)
  66619. {
  66620. #if defined(DRFLAC_SUPPORT_SSE2)
  66621. #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE2)
  66622. #if defined(DRFLAC_X64)
  66623. return DRFLAC_TRUE;
  66624. #elif (defined(_M_IX86_FP) && _M_IX86_FP == 2) || defined(__SSE2__)
  66625. return DRFLAC_TRUE;
  66626. #else
  66627. #if defined(DRFLAC_NO_CPUID)
  66628. return DRFLAC_FALSE;
  66629. #else
  66630. int info[4];
  66631. drflac__cpuid(info, 1);
  66632. return (info[3] & (1 << 26)) != 0;
  66633. #endif
  66634. #endif
  66635. #else
  66636. return DRFLAC_FALSE;
  66637. #endif
  66638. #else
  66639. return DRFLAC_FALSE;
  66640. #endif
  66641. }
  66642. static DRFLAC_INLINE drflac_bool32 drflac_has_sse41(void)
  66643. {
  66644. #if defined(DRFLAC_SUPPORT_SSE41)
  66645. #if (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(DRFLAC_NO_SSE41)
  66646. #if defined(__SSE4_1__) || defined(__AVX__)
  66647. return DRFLAC_TRUE;
  66648. #else
  66649. #if defined(DRFLAC_NO_CPUID)
  66650. return DRFLAC_FALSE;
  66651. #else
  66652. int info[4];
  66653. drflac__cpuid(info, 1);
  66654. return (info[2] & (1 << 19)) != 0;
  66655. #endif
  66656. #endif
  66657. #else
  66658. return DRFLAC_FALSE;
  66659. #endif
  66660. #else
  66661. return DRFLAC_FALSE;
  66662. #endif
  66663. }
  66664. #if defined(_MSC_VER) && _MSC_VER >= 1500 && (defined(DRFLAC_X86) || defined(DRFLAC_X64)) && !defined(__clang__)
  66665. #define DRFLAC_HAS_LZCNT_INTRINSIC
  66666. #elif (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)))
  66667. #define DRFLAC_HAS_LZCNT_INTRINSIC
  66668. #elif defined(__clang__)
  66669. #if defined(__has_builtin)
  66670. #if __has_builtin(__builtin_clzll) || __has_builtin(__builtin_clzl)
  66671. #define DRFLAC_HAS_LZCNT_INTRINSIC
  66672. #endif
  66673. #endif
  66674. #endif
  66675. #if defined(_MSC_VER) && _MSC_VER >= 1400 && !defined(__clang__)
  66676. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  66677. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  66678. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  66679. #elif defined(__clang__)
  66680. #if defined(__has_builtin)
  66681. #if __has_builtin(__builtin_bswap16)
  66682. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  66683. #endif
  66684. #if __has_builtin(__builtin_bswap32)
  66685. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  66686. #endif
  66687. #if __has_builtin(__builtin_bswap64)
  66688. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  66689. #endif
  66690. #endif
  66691. #elif defined(__GNUC__)
  66692. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3))
  66693. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  66694. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  66695. #endif
  66696. #if ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8))
  66697. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  66698. #endif
  66699. #elif defined(__WATCOMC__) && defined(__386__)
  66700. #define DRFLAC_HAS_BYTESWAP16_INTRINSIC
  66701. #define DRFLAC_HAS_BYTESWAP32_INTRINSIC
  66702. #define DRFLAC_HAS_BYTESWAP64_INTRINSIC
  66703. extern __inline drflac_uint16 _watcom_bswap16(drflac_uint16);
  66704. extern __inline drflac_uint32 _watcom_bswap32(drflac_uint32);
  66705. extern __inline drflac_uint64 _watcom_bswap64(drflac_uint64);
  66706. #pragma aux _watcom_bswap16 = \
  66707. "xchg al, ah" \
  66708. parm [ax] \
  66709. value [ax] \
  66710. modify nomemory;
  66711. #pragma aux _watcom_bswap32 = \
  66712. "bswap eax" \
  66713. parm [eax] \
  66714. value [eax] \
  66715. modify nomemory;
  66716. #pragma aux _watcom_bswap64 = \
  66717. "bswap eax" \
  66718. "bswap edx" \
  66719. "xchg eax,edx" \
  66720. parm [eax edx] \
  66721. value [eax edx] \
  66722. modify nomemory;
  66723. #endif
  66724. #ifndef DRFLAC_ASSERT
  66725. #include <assert.h>
  66726. #define DRFLAC_ASSERT(expression) assert(expression)
  66727. #endif
  66728. #ifndef DRFLAC_MALLOC
  66729. #define DRFLAC_MALLOC(sz) malloc((sz))
  66730. #endif
  66731. #ifndef DRFLAC_REALLOC
  66732. #define DRFLAC_REALLOC(p, sz) realloc((p), (sz))
  66733. #endif
  66734. #ifndef DRFLAC_FREE
  66735. #define DRFLAC_FREE(p) free((p))
  66736. #endif
  66737. #ifndef DRFLAC_COPY_MEMORY
  66738. #define DRFLAC_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  66739. #endif
  66740. #ifndef DRFLAC_ZERO_MEMORY
  66741. #define DRFLAC_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  66742. #endif
  66743. #ifndef DRFLAC_ZERO_OBJECT
  66744. #define DRFLAC_ZERO_OBJECT(p) DRFLAC_ZERO_MEMORY((p), sizeof(*(p)))
  66745. #endif
  66746. #define DRFLAC_MAX_SIMD_VECTOR_SIZE 64
  66747. typedef drflac_int32 drflac_result;
  66748. #define DRFLAC_SUCCESS 0
  66749. #define DRFLAC_ERROR -1
  66750. #define DRFLAC_INVALID_ARGS -2
  66751. #define DRFLAC_INVALID_OPERATION -3
  66752. #define DRFLAC_OUT_OF_MEMORY -4
  66753. #define DRFLAC_OUT_OF_RANGE -5
  66754. #define DRFLAC_ACCESS_DENIED -6
  66755. #define DRFLAC_DOES_NOT_EXIST -7
  66756. #define DRFLAC_ALREADY_EXISTS -8
  66757. #define DRFLAC_TOO_MANY_OPEN_FILES -9
  66758. #define DRFLAC_INVALID_FILE -10
  66759. #define DRFLAC_TOO_BIG -11
  66760. #define DRFLAC_PATH_TOO_LONG -12
  66761. #define DRFLAC_NAME_TOO_LONG -13
  66762. #define DRFLAC_NOT_DIRECTORY -14
  66763. #define DRFLAC_IS_DIRECTORY -15
  66764. #define DRFLAC_DIRECTORY_NOT_EMPTY -16
  66765. #define DRFLAC_END_OF_FILE -17
  66766. #define DRFLAC_NO_SPACE -18
  66767. #define DRFLAC_BUSY -19
  66768. #define DRFLAC_IO_ERROR -20
  66769. #define DRFLAC_INTERRUPT -21
  66770. #define DRFLAC_UNAVAILABLE -22
  66771. #define DRFLAC_ALREADY_IN_USE -23
  66772. #define DRFLAC_BAD_ADDRESS -24
  66773. #define DRFLAC_BAD_SEEK -25
  66774. #define DRFLAC_BAD_PIPE -26
  66775. #define DRFLAC_DEADLOCK -27
  66776. #define DRFLAC_TOO_MANY_LINKS -28
  66777. #define DRFLAC_NOT_IMPLEMENTED -29
  66778. #define DRFLAC_NO_MESSAGE -30
  66779. #define DRFLAC_BAD_MESSAGE -31
  66780. #define DRFLAC_NO_DATA_AVAILABLE -32
  66781. #define DRFLAC_INVALID_DATA -33
  66782. #define DRFLAC_TIMEOUT -34
  66783. #define DRFLAC_NO_NETWORK -35
  66784. #define DRFLAC_NOT_UNIQUE -36
  66785. #define DRFLAC_NOT_SOCKET -37
  66786. #define DRFLAC_NO_ADDRESS -38
  66787. #define DRFLAC_BAD_PROTOCOL -39
  66788. #define DRFLAC_PROTOCOL_UNAVAILABLE -40
  66789. #define DRFLAC_PROTOCOL_NOT_SUPPORTED -41
  66790. #define DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED -42
  66791. #define DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED -43
  66792. #define DRFLAC_SOCKET_NOT_SUPPORTED -44
  66793. #define DRFLAC_CONNECTION_RESET -45
  66794. #define DRFLAC_ALREADY_CONNECTED -46
  66795. #define DRFLAC_NOT_CONNECTED -47
  66796. #define DRFLAC_CONNECTION_REFUSED -48
  66797. #define DRFLAC_NO_HOST -49
  66798. #define DRFLAC_IN_PROGRESS -50
  66799. #define DRFLAC_CANCELLED -51
  66800. #define DRFLAC_MEMORY_ALREADY_MAPPED -52
  66801. #define DRFLAC_AT_END -53
  66802. #define DRFLAC_CRC_MISMATCH -128
  66803. #define DRFLAC_SUBFRAME_CONSTANT 0
  66804. #define DRFLAC_SUBFRAME_VERBATIM 1
  66805. #define DRFLAC_SUBFRAME_FIXED 8
  66806. #define DRFLAC_SUBFRAME_LPC 32
  66807. #define DRFLAC_SUBFRAME_RESERVED 255
  66808. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE 0
  66809. #define DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2 1
  66810. #define DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT 0
  66811. #define DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE 8
  66812. #define DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE 9
  66813. #define DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE 10
  66814. #define DRFLAC_SEEKPOINT_SIZE_IN_BYTES 18
  66815. #define DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES 36
  66816. #define DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES 12
  66817. #define drflac_align(x, a) ((((x) + (a) - 1) / (a)) * (a))
  66818. DRFLAC_API void drflac_version(drflac_uint32* pMajor, drflac_uint32* pMinor, drflac_uint32* pRevision)
  66819. {
  66820. if (pMajor) {
  66821. *pMajor = DRFLAC_VERSION_MAJOR;
  66822. }
  66823. if (pMinor) {
  66824. *pMinor = DRFLAC_VERSION_MINOR;
  66825. }
  66826. if (pRevision) {
  66827. *pRevision = DRFLAC_VERSION_REVISION;
  66828. }
  66829. }
  66830. DRFLAC_API const char* drflac_version_string(void)
  66831. {
  66832. return DRFLAC_VERSION_STRING;
  66833. }
  66834. #if defined(__has_feature)
  66835. #if __has_feature(thread_sanitizer)
  66836. #define DRFLAC_NO_THREAD_SANITIZE __attribute__((no_sanitize("thread")))
  66837. #else
  66838. #define DRFLAC_NO_THREAD_SANITIZE
  66839. #endif
  66840. #else
  66841. #define DRFLAC_NO_THREAD_SANITIZE
  66842. #endif
  66843. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  66844. static drflac_bool32 drflac__gIsLZCNTSupported = DRFLAC_FALSE;
  66845. #endif
  66846. #ifndef DRFLAC_NO_CPUID
  66847. static drflac_bool32 drflac__gIsSSE2Supported = DRFLAC_FALSE;
  66848. static drflac_bool32 drflac__gIsSSE41Supported = DRFLAC_FALSE;
  66849. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  66850. {
  66851. static drflac_bool32 isCPUCapsInitialized = DRFLAC_FALSE;
  66852. if (!isCPUCapsInitialized) {
  66853. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  66854. int info[4] = {0};
  66855. drflac__cpuid(info, 0x80000001);
  66856. drflac__gIsLZCNTSupported = (info[2] & (1 << 5)) != 0;
  66857. #endif
  66858. drflac__gIsSSE2Supported = drflac_has_sse2();
  66859. drflac__gIsSSE41Supported = drflac_has_sse41();
  66860. isCPUCapsInitialized = DRFLAC_TRUE;
  66861. }
  66862. }
  66863. #else
  66864. static drflac_bool32 drflac__gIsNEONSupported = DRFLAC_FALSE;
  66865. static DRFLAC_INLINE drflac_bool32 drflac__has_neon(void)
  66866. {
  66867. #if defined(DRFLAC_SUPPORT_NEON)
  66868. #if defined(DRFLAC_ARM) && !defined(DRFLAC_NO_NEON)
  66869. #if (defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64))
  66870. return DRFLAC_TRUE;
  66871. #else
  66872. return DRFLAC_FALSE;
  66873. #endif
  66874. #else
  66875. return DRFLAC_FALSE;
  66876. #endif
  66877. #else
  66878. return DRFLAC_FALSE;
  66879. #endif
  66880. }
  66881. DRFLAC_NO_THREAD_SANITIZE static void drflac__init_cpu_caps(void)
  66882. {
  66883. drflac__gIsNEONSupported = drflac__has_neon();
  66884. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  66885. drflac__gIsLZCNTSupported = DRFLAC_TRUE;
  66886. #endif
  66887. }
  66888. #endif
  66889. static DRFLAC_INLINE drflac_bool32 drflac__is_little_endian(void)
  66890. {
  66891. #if defined(DRFLAC_X86) || defined(DRFLAC_X64)
  66892. return DRFLAC_TRUE;
  66893. #elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && __BYTE_ORDER == __LITTLE_ENDIAN
  66894. return DRFLAC_TRUE;
  66895. #else
  66896. int n = 1;
  66897. return (*(char*)&n) == 1;
  66898. #endif
  66899. }
  66900. static DRFLAC_INLINE drflac_uint16 drflac__swap_endian_uint16(drflac_uint16 n)
  66901. {
  66902. #ifdef DRFLAC_HAS_BYTESWAP16_INTRINSIC
  66903. #if defined(_MSC_VER) && !defined(__clang__)
  66904. return _byteswap_ushort(n);
  66905. #elif defined(__GNUC__) || defined(__clang__)
  66906. return __builtin_bswap16(n);
  66907. #elif defined(__WATCOMC__) && defined(__386__)
  66908. return _watcom_bswap16(n);
  66909. #else
  66910. #error "This compiler does not support the byte swap intrinsic."
  66911. #endif
  66912. #else
  66913. return ((n & 0xFF00) >> 8) |
  66914. ((n & 0x00FF) << 8);
  66915. #endif
  66916. }
  66917. static DRFLAC_INLINE drflac_uint32 drflac__swap_endian_uint32(drflac_uint32 n)
  66918. {
  66919. #ifdef DRFLAC_HAS_BYTESWAP32_INTRINSIC
  66920. #if defined(_MSC_VER) && !defined(__clang__)
  66921. return _byteswap_ulong(n);
  66922. #elif defined(__GNUC__) || defined(__clang__)
  66923. #if defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 6) && !defined(DRFLAC_64BIT)
  66924. drflac_uint32 r;
  66925. __asm__ __volatile__ (
  66926. #if defined(DRFLAC_64BIT)
  66927. "rev %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(n)
  66928. #else
  66929. "rev %[out], %[in]" : [out]"=r"(r) : [in]"r"(n)
  66930. #endif
  66931. );
  66932. return r;
  66933. #else
  66934. return __builtin_bswap32(n);
  66935. #endif
  66936. #elif defined(__WATCOMC__) && defined(__386__)
  66937. return _watcom_bswap32(n);
  66938. #else
  66939. #error "This compiler does not support the byte swap intrinsic."
  66940. #endif
  66941. #else
  66942. return ((n & 0xFF000000) >> 24) |
  66943. ((n & 0x00FF0000) >> 8) |
  66944. ((n & 0x0000FF00) << 8) |
  66945. ((n & 0x000000FF) << 24);
  66946. #endif
  66947. }
  66948. static DRFLAC_INLINE drflac_uint64 drflac__swap_endian_uint64(drflac_uint64 n)
  66949. {
  66950. #ifdef DRFLAC_HAS_BYTESWAP64_INTRINSIC
  66951. #if defined(_MSC_VER) && !defined(__clang__)
  66952. return _byteswap_uint64(n);
  66953. #elif defined(__GNUC__) || defined(__clang__)
  66954. return __builtin_bswap64(n);
  66955. #elif defined(__WATCOMC__) && defined(__386__)
  66956. return _watcom_bswap64(n);
  66957. #else
  66958. #error "This compiler does not support the byte swap intrinsic."
  66959. #endif
  66960. #else
  66961. return ((n & ((drflac_uint64)0xFF000000 << 32)) >> 56) |
  66962. ((n & ((drflac_uint64)0x00FF0000 << 32)) >> 40) |
  66963. ((n & ((drflac_uint64)0x0000FF00 << 32)) >> 24) |
  66964. ((n & ((drflac_uint64)0x000000FF << 32)) >> 8) |
  66965. ((n & ((drflac_uint64)0xFF000000 )) << 8) |
  66966. ((n & ((drflac_uint64)0x00FF0000 )) << 24) |
  66967. ((n & ((drflac_uint64)0x0000FF00 )) << 40) |
  66968. ((n & ((drflac_uint64)0x000000FF )) << 56);
  66969. #endif
  66970. }
  66971. static DRFLAC_INLINE drflac_uint16 drflac__be2host_16(drflac_uint16 n)
  66972. {
  66973. if (drflac__is_little_endian()) {
  66974. return drflac__swap_endian_uint16(n);
  66975. }
  66976. return n;
  66977. }
  66978. static DRFLAC_INLINE drflac_uint32 drflac__be2host_32(drflac_uint32 n)
  66979. {
  66980. if (drflac__is_little_endian()) {
  66981. return drflac__swap_endian_uint32(n);
  66982. }
  66983. return n;
  66984. }
  66985. static DRFLAC_INLINE drflac_uint32 drflac__be2host_32_ptr_unaligned(const void* pData)
  66986. {
  66987. const drflac_uint8* pNum = (drflac_uint8*)pData;
  66988. return *(pNum) << 24 | *(pNum+1) << 16 | *(pNum+2) << 8 | *(pNum+3);
  66989. }
  66990. static DRFLAC_INLINE drflac_uint64 drflac__be2host_64(drflac_uint64 n)
  66991. {
  66992. if (drflac__is_little_endian()) {
  66993. return drflac__swap_endian_uint64(n);
  66994. }
  66995. return n;
  66996. }
  66997. static DRFLAC_INLINE drflac_uint32 drflac__le2host_32(drflac_uint32 n)
  66998. {
  66999. if (!drflac__is_little_endian()) {
  67000. return drflac__swap_endian_uint32(n);
  67001. }
  67002. return n;
  67003. }
  67004. static DRFLAC_INLINE drflac_uint32 drflac__le2host_32_ptr_unaligned(const void* pData)
  67005. {
  67006. const drflac_uint8* pNum = (drflac_uint8*)pData;
  67007. return *pNum | *(pNum+1) << 8 | *(pNum+2) << 16 | *(pNum+3) << 24;
  67008. }
  67009. static DRFLAC_INLINE drflac_uint32 drflac__unsynchsafe_32(drflac_uint32 n)
  67010. {
  67011. drflac_uint32 result = 0;
  67012. result |= (n & 0x7F000000) >> 3;
  67013. result |= (n & 0x007F0000) >> 2;
  67014. result |= (n & 0x00007F00) >> 1;
  67015. result |= (n & 0x0000007F) >> 0;
  67016. return result;
  67017. }
  67018. static drflac_uint8 drflac__crc8_table[] = {
  67019. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15, 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  67020. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65, 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  67021. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5, 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  67022. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85, 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  67023. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2, 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  67024. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2, 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  67025. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32, 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  67026. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42, 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  67027. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C, 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  67028. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC, 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  67029. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C, 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  67030. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C, 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  67031. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B, 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  67032. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B, 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  67033. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB, 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  67034. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB, 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  67035. };
  67036. static drflac_uint16 drflac__crc16_table[] = {
  67037. 0x0000, 0x8005, 0x800F, 0x000A, 0x801B, 0x001E, 0x0014, 0x8011,
  67038. 0x8033, 0x0036, 0x003C, 0x8039, 0x0028, 0x802D, 0x8027, 0x0022,
  67039. 0x8063, 0x0066, 0x006C, 0x8069, 0x0078, 0x807D, 0x8077, 0x0072,
  67040. 0x0050, 0x8055, 0x805F, 0x005A, 0x804B, 0x004E, 0x0044, 0x8041,
  67041. 0x80C3, 0x00C6, 0x00CC, 0x80C9, 0x00D8, 0x80DD, 0x80D7, 0x00D2,
  67042. 0x00F0, 0x80F5, 0x80FF, 0x00FA, 0x80EB, 0x00EE, 0x00E4, 0x80E1,
  67043. 0x00A0, 0x80A5, 0x80AF, 0x00AA, 0x80BB, 0x00BE, 0x00B4, 0x80B1,
  67044. 0x8093, 0x0096, 0x009C, 0x8099, 0x0088, 0x808D, 0x8087, 0x0082,
  67045. 0x8183, 0x0186, 0x018C, 0x8189, 0x0198, 0x819D, 0x8197, 0x0192,
  67046. 0x01B0, 0x81B5, 0x81BF, 0x01BA, 0x81AB, 0x01AE, 0x01A4, 0x81A1,
  67047. 0x01E0, 0x81E5, 0x81EF, 0x01EA, 0x81FB, 0x01FE, 0x01F4, 0x81F1,
  67048. 0x81D3, 0x01D6, 0x01DC, 0x81D9, 0x01C8, 0x81CD, 0x81C7, 0x01C2,
  67049. 0x0140, 0x8145, 0x814F, 0x014A, 0x815B, 0x015E, 0x0154, 0x8151,
  67050. 0x8173, 0x0176, 0x017C, 0x8179, 0x0168, 0x816D, 0x8167, 0x0162,
  67051. 0x8123, 0x0126, 0x012C, 0x8129, 0x0138, 0x813D, 0x8137, 0x0132,
  67052. 0x0110, 0x8115, 0x811F, 0x011A, 0x810B, 0x010E, 0x0104, 0x8101,
  67053. 0x8303, 0x0306, 0x030C, 0x8309, 0x0318, 0x831D, 0x8317, 0x0312,
  67054. 0x0330, 0x8335, 0x833F, 0x033A, 0x832B, 0x032E, 0x0324, 0x8321,
  67055. 0x0360, 0x8365, 0x836F, 0x036A, 0x837B, 0x037E, 0x0374, 0x8371,
  67056. 0x8353, 0x0356, 0x035C, 0x8359, 0x0348, 0x834D, 0x8347, 0x0342,
  67057. 0x03C0, 0x83C5, 0x83CF, 0x03CA, 0x83DB, 0x03DE, 0x03D4, 0x83D1,
  67058. 0x83F3, 0x03F6, 0x03FC, 0x83F9, 0x03E8, 0x83ED, 0x83E7, 0x03E2,
  67059. 0x83A3, 0x03A6, 0x03AC, 0x83A9, 0x03B8, 0x83BD, 0x83B7, 0x03B2,
  67060. 0x0390, 0x8395, 0x839F, 0x039A, 0x838B, 0x038E, 0x0384, 0x8381,
  67061. 0x0280, 0x8285, 0x828F, 0x028A, 0x829B, 0x029E, 0x0294, 0x8291,
  67062. 0x82B3, 0x02B6, 0x02BC, 0x82B9, 0x02A8, 0x82AD, 0x82A7, 0x02A2,
  67063. 0x82E3, 0x02E6, 0x02EC, 0x82E9, 0x02F8, 0x82FD, 0x82F7, 0x02F2,
  67064. 0x02D0, 0x82D5, 0x82DF, 0x02DA, 0x82CB, 0x02CE, 0x02C4, 0x82C1,
  67065. 0x8243, 0x0246, 0x024C, 0x8249, 0x0258, 0x825D, 0x8257, 0x0252,
  67066. 0x0270, 0x8275, 0x827F, 0x027A, 0x826B, 0x026E, 0x0264, 0x8261,
  67067. 0x0220, 0x8225, 0x822F, 0x022A, 0x823B, 0x023E, 0x0234, 0x8231,
  67068. 0x8213, 0x0216, 0x021C, 0x8219, 0x0208, 0x820D, 0x8207, 0x0202
  67069. };
  67070. static DRFLAC_INLINE drflac_uint8 drflac_crc8_byte(drflac_uint8 crc, drflac_uint8 data)
  67071. {
  67072. return drflac__crc8_table[crc ^ data];
  67073. }
  67074. static DRFLAC_INLINE drflac_uint8 drflac_crc8(drflac_uint8 crc, drflac_uint32 data, drflac_uint32 count)
  67075. {
  67076. #ifdef DR_FLAC_NO_CRC
  67077. (void)crc;
  67078. (void)data;
  67079. (void)count;
  67080. return 0;
  67081. #else
  67082. #if 0
  67083. drflac_uint8 p = 0x07;
  67084. for (int i = count-1; i >= 0; --i) {
  67085. drflac_uint8 bit = (data & (1 << i)) >> i;
  67086. if (crc & 0x80) {
  67087. crc = ((crc << 1) | bit) ^ p;
  67088. } else {
  67089. crc = ((crc << 1) | bit);
  67090. }
  67091. }
  67092. return crc;
  67093. #else
  67094. drflac_uint32 wholeBytes;
  67095. drflac_uint32 leftoverBits;
  67096. drflac_uint64 leftoverDataMask;
  67097. static drflac_uint64 leftoverDataMaskTable[8] = {
  67098. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  67099. };
  67100. DRFLAC_ASSERT(count <= 32);
  67101. wholeBytes = count >> 3;
  67102. leftoverBits = count - (wholeBytes*8);
  67103. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  67104. switch (wholeBytes) {
  67105. case 4: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  67106. case 3: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  67107. case 2: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  67108. case 1: crc = drflac_crc8_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  67109. case 0: if (leftoverBits > 0) crc = (drflac_uint8)((crc << leftoverBits) ^ drflac__crc8_table[(crc >> (8 - leftoverBits)) ^ (data & leftoverDataMask)]);
  67110. }
  67111. return crc;
  67112. #endif
  67113. #endif
  67114. }
  67115. static DRFLAC_INLINE drflac_uint16 drflac_crc16_byte(drflac_uint16 crc, drflac_uint8 data)
  67116. {
  67117. return (crc << 8) ^ drflac__crc16_table[(drflac_uint8)(crc >> 8) ^ data];
  67118. }
  67119. static DRFLAC_INLINE drflac_uint16 drflac_crc16_cache(drflac_uint16 crc, drflac_cache_t data)
  67120. {
  67121. #ifdef DRFLAC_64BIT
  67122. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  67123. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  67124. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  67125. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  67126. #endif
  67127. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  67128. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  67129. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
  67130. crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
  67131. return crc;
  67132. }
  67133. static DRFLAC_INLINE drflac_uint16 drflac_crc16_bytes(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 byteCount)
  67134. {
  67135. switch (byteCount)
  67136. {
  67137. #ifdef DRFLAC_64BIT
  67138. case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 56) & 0xFF));
  67139. case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 48) & 0xFF));
  67140. case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 40) & 0xFF));
  67141. case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 32) & 0xFF));
  67142. #endif
  67143. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 24) & 0xFF));
  67144. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 16) & 0xFF));
  67145. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 8) & 0xFF));
  67146. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data >> 0) & 0xFF));
  67147. }
  67148. return crc;
  67149. }
  67150. #if 0
  67151. static DRFLAC_INLINE drflac_uint16 drflac_crc16__32bit(drflac_uint16 crc, drflac_uint32 data, drflac_uint32 count)
  67152. {
  67153. #ifdef DR_FLAC_NO_CRC
  67154. (void)crc;
  67155. (void)data;
  67156. (void)count;
  67157. return 0;
  67158. #else
  67159. #if 0
  67160. drflac_uint16 p = 0x8005;
  67161. for (int i = count-1; i >= 0; --i) {
  67162. drflac_uint16 bit = (data & (1ULL << i)) >> i;
  67163. if (r & 0x8000) {
  67164. r = ((r << 1) | bit) ^ p;
  67165. } else {
  67166. r = ((r << 1) | bit);
  67167. }
  67168. }
  67169. return crc;
  67170. #else
  67171. drflac_uint32 wholeBytes;
  67172. drflac_uint32 leftoverBits;
  67173. drflac_uint64 leftoverDataMask;
  67174. static drflac_uint64 leftoverDataMaskTable[8] = {
  67175. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  67176. };
  67177. DRFLAC_ASSERT(count <= 64);
  67178. wholeBytes = count >> 3;
  67179. leftoverBits = count & 7;
  67180. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  67181. switch (wholeBytes) {
  67182. default:
  67183. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0xFF000000UL << leftoverBits)) >> (24 + leftoverBits)));
  67184. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x00FF0000UL << leftoverBits)) >> (16 + leftoverBits)));
  67185. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x0000FF00UL << leftoverBits)) >> ( 8 + leftoverBits)));
  67186. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (0x000000FFUL << leftoverBits)) >> ( 0 + leftoverBits)));
  67187. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  67188. }
  67189. return crc;
  67190. #endif
  67191. #endif
  67192. }
  67193. static DRFLAC_INLINE drflac_uint16 drflac_crc16__64bit(drflac_uint16 crc, drflac_uint64 data, drflac_uint32 count)
  67194. {
  67195. #ifdef DR_FLAC_NO_CRC
  67196. (void)crc;
  67197. (void)data;
  67198. (void)count;
  67199. return 0;
  67200. #else
  67201. drflac_uint32 wholeBytes;
  67202. drflac_uint32 leftoverBits;
  67203. drflac_uint64 leftoverDataMask;
  67204. static drflac_uint64 leftoverDataMaskTable[8] = {
  67205. 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F
  67206. };
  67207. DRFLAC_ASSERT(count <= 64);
  67208. wholeBytes = count >> 3;
  67209. leftoverBits = count & 7;
  67210. leftoverDataMask = leftoverDataMaskTable[leftoverBits];
  67211. switch (wholeBytes) {
  67212. default:
  67213. case 8: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 << 32) << leftoverBits)) >> (56 + leftoverBits)));
  67214. case 7: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 << 32) << leftoverBits)) >> (48 + leftoverBits)));
  67215. case 6: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 << 32) << leftoverBits)) >> (40 + leftoverBits)));
  67216. case 5: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF << 32) << leftoverBits)) >> (32 + leftoverBits)));
  67217. case 4: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0xFF000000 ) << leftoverBits)) >> (24 + leftoverBits)));
  67218. case 3: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x00FF0000 ) << leftoverBits)) >> (16 + leftoverBits)));
  67219. case 2: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x0000FF00 ) << leftoverBits)) >> ( 8 + leftoverBits)));
  67220. case 1: crc = drflac_crc16_byte(crc, (drflac_uint8)((data & (((drflac_uint64)0x000000FF ) << leftoverBits)) >> ( 0 + leftoverBits)));
  67221. case 0: if (leftoverBits > 0) crc = (crc << leftoverBits) ^ drflac__crc16_table[(crc >> (16 - leftoverBits)) ^ (data & leftoverDataMask)];
  67222. }
  67223. return crc;
  67224. #endif
  67225. }
  67226. static DRFLAC_INLINE drflac_uint16 drflac_crc16(drflac_uint16 crc, drflac_cache_t data, drflac_uint32 count)
  67227. {
  67228. #ifdef DRFLAC_64BIT
  67229. return drflac_crc16__64bit(crc, data, count);
  67230. #else
  67231. return drflac_crc16__32bit(crc, data, count);
  67232. #endif
  67233. }
  67234. #endif
  67235. #ifdef DRFLAC_64BIT
  67236. #define drflac__be2host__cache_line drflac__be2host_64
  67237. #else
  67238. #define drflac__be2host__cache_line drflac__be2host_32
  67239. #endif
  67240. #define DRFLAC_CACHE_L1_SIZE_BYTES(bs) (sizeof((bs)->cache))
  67241. #define DRFLAC_CACHE_L1_SIZE_BITS(bs) (sizeof((bs)->cache)*8)
  67242. #define DRFLAC_CACHE_L1_BITS_REMAINING(bs) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (bs)->consumedBits)
  67243. #define DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount) (~((~(drflac_cache_t)0) >> (_bitCount)))
  67244. #define DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SIZE_BITS(bs) - (_bitCount))
  67245. #define DRFLAC_CACHE_L1_SELECT(bs, _bitCount) (((bs)->cache) & DRFLAC_CACHE_L1_SELECTION_MASK(_bitCount))
  67246. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, _bitCount) (DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)))
  67247. #define DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, _bitCount)(DRFLAC_CACHE_L1_SELECT((bs), (_bitCount)) >> (DRFLAC_CACHE_L1_SELECTION_SHIFT((bs), (_bitCount)) & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1)))
  67248. #define DRFLAC_CACHE_L2_SIZE_BYTES(bs) (sizeof((bs)->cacheL2))
  67249. #define DRFLAC_CACHE_L2_LINE_COUNT(bs) (DRFLAC_CACHE_L2_SIZE_BYTES(bs) / sizeof((bs)->cacheL2[0]))
  67250. #define DRFLAC_CACHE_L2_LINES_REMAINING(bs) (DRFLAC_CACHE_L2_LINE_COUNT(bs) - (bs)->nextL2Line)
  67251. #ifndef DR_FLAC_NO_CRC
  67252. static DRFLAC_INLINE void drflac__reset_crc16(drflac_bs* bs)
  67253. {
  67254. bs->crc16 = 0;
  67255. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  67256. }
  67257. static DRFLAC_INLINE void drflac__update_crc16(drflac_bs* bs)
  67258. {
  67259. if (bs->crc16CacheIgnoredBytes == 0) {
  67260. bs->crc16 = drflac_crc16_cache(bs->crc16, bs->crc16Cache);
  67261. } else {
  67262. bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache, DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bs->crc16CacheIgnoredBytes);
  67263. bs->crc16CacheIgnoredBytes = 0;
  67264. }
  67265. }
  67266. static DRFLAC_INLINE drflac_uint16 drflac__flush_crc16(drflac_bs* bs)
  67267. {
  67268. DRFLAC_ASSERT((DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7) == 0);
  67269. if (DRFLAC_CACHE_L1_BITS_REMAINING(bs) == 0) {
  67270. drflac__update_crc16(bs);
  67271. } else {
  67272. bs->crc16 = drflac_crc16_bytes(bs->crc16, bs->crc16Cache >> DRFLAC_CACHE_L1_BITS_REMAINING(bs), (bs->consumedBits >> 3) - bs->crc16CacheIgnoredBytes);
  67273. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  67274. }
  67275. return bs->crc16;
  67276. }
  67277. #endif
  67278. static DRFLAC_INLINE drflac_bool32 drflac__reload_l1_cache_from_l2(drflac_bs* bs)
  67279. {
  67280. size_t bytesRead;
  67281. size_t alignedL1LineCount;
  67282. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  67283. bs->cache = bs->cacheL2[bs->nextL2Line++];
  67284. return DRFLAC_TRUE;
  67285. }
  67286. if (bs->unalignedByteCount > 0) {
  67287. return DRFLAC_FALSE;
  67288. }
  67289. bytesRead = bs->onRead(bs->pUserData, bs->cacheL2, DRFLAC_CACHE_L2_SIZE_BYTES(bs));
  67290. bs->nextL2Line = 0;
  67291. if (bytesRead == DRFLAC_CACHE_L2_SIZE_BYTES(bs)) {
  67292. bs->cache = bs->cacheL2[bs->nextL2Line++];
  67293. return DRFLAC_TRUE;
  67294. }
  67295. alignedL1LineCount = bytesRead / DRFLAC_CACHE_L1_SIZE_BYTES(bs);
  67296. bs->unalignedByteCount = bytesRead - (alignedL1LineCount * DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  67297. if (bs->unalignedByteCount > 0) {
  67298. bs->unalignedCache = bs->cacheL2[alignedL1LineCount];
  67299. }
  67300. if (alignedL1LineCount > 0) {
  67301. size_t offset = DRFLAC_CACHE_L2_LINE_COUNT(bs) - alignedL1LineCount;
  67302. size_t i;
  67303. for (i = alignedL1LineCount; i > 0; --i) {
  67304. bs->cacheL2[i-1 + offset] = bs->cacheL2[i-1];
  67305. }
  67306. bs->nextL2Line = (drflac_uint32)offset;
  67307. bs->cache = bs->cacheL2[bs->nextL2Line++];
  67308. return DRFLAC_TRUE;
  67309. } else {
  67310. bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
  67311. return DRFLAC_FALSE;
  67312. }
  67313. }
  67314. static drflac_bool32 drflac__reload_cache(drflac_bs* bs)
  67315. {
  67316. size_t bytesRead;
  67317. #ifndef DR_FLAC_NO_CRC
  67318. drflac__update_crc16(bs);
  67319. #endif
  67320. if (drflac__reload_l1_cache_from_l2(bs)) {
  67321. bs->cache = drflac__be2host__cache_line(bs->cache);
  67322. bs->consumedBits = 0;
  67323. #ifndef DR_FLAC_NO_CRC
  67324. bs->crc16Cache = bs->cache;
  67325. #endif
  67326. return DRFLAC_TRUE;
  67327. }
  67328. bytesRead = bs->unalignedByteCount;
  67329. if (bytesRead == 0) {
  67330. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  67331. return DRFLAC_FALSE;
  67332. }
  67333. DRFLAC_ASSERT(bytesRead < DRFLAC_CACHE_L1_SIZE_BYTES(bs));
  67334. bs->consumedBits = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BYTES(bs) - bytesRead) * 8;
  67335. bs->cache = drflac__be2host__cache_line(bs->unalignedCache);
  67336. bs->cache &= DRFLAC_CACHE_L1_SELECTION_MASK(DRFLAC_CACHE_L1_BITS_REMAINING(bs));
  67337. bs->unalignedByteCount = 0;
  67338. #ifndef DR_FLAC_NO_CRC
  67339. bs->crc16Cache = bs->cache >> bs->consumedBits;
  67340. bs->crc16CacheIgnoredBytes = bs->consumedBits >> 3;
  67341. #endif
  67342. return DRFLAC_TRUE;
  67343. }
  67344. static void drflac__reset_cache(drflac_bs* bs)
  67345. {
  67346. bs->nextL2Line = DRFLAC_CACHE_L2_LINE_COUNT(bs);
  67347. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  67348. bs->cache = 0;
  67349. bs->unalignedByteCount = 0;
  67350. bs->unalignedCache = 0;
  67351. #ifndef DR_FLAC_NO_CRC
  67352. bs->crc16Cache = 0;
  67353. bs->crc16CacheIgnoredBytes = 0;
  67354. #endif
  67355. }
  67356. static DRFLAC_INLINE drflac_bool32 drflac__read_uint32(drflac_bs* bs, unsigned int bitCount, drflac_uint32* pResultOut)
  67357. {
  67358. DRFLAC_ASSERT(bs != NULL);
  67359. DRFLAC_ASSERT(pResultOut != NULL);
  67360. DRFLAC_ASSERT(bitCount > 0);
  67361. DRFLAC_ASSERT(bitCount <= 32);
  67362. if (bs->consumedBits == DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  67363. if (!drflac__reload_cache(bs)) {
  67364. return DRFLAC_FALSE;
  67365. }
  67366. }
  67367. if (bitCount <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  67368. #ifdef DRFLAC_64BIT
  67369. *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  67370. bs->consumedBits += bitCount;
  67371. bs->cache <<= bitCount;
  67372. #else
  67373. if (bitCount < DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  67374. *pResultOut = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCount);
  67375. bs->consumedBits += bitCount;
  67376. bs->cache <<= bitCount;
  67377. } else {
  67378. *pResultOut = (drflac_uint32)bs->cache;
  67379. bs->consumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs);
  67380. bs->cache = 0;
  67381. }
  67382. #endif
  67383. return DRFLAC_TRUE;
  67384. } else {
  67385. drflac_uint32 bitCountHi = DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  67386. drflac_uint32 bitCountLo = bitCount - bitCountHi;
  67387. drflac_uint32 resultHi;
  67388. DRFLAC_ASSERT(bitCountHi > 0);
  67389. DRFLAC_ASSERT(bitCountHi < 32);
  67390. resultHi = (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountHi);
  67391. if (!drflac__reload_cache(bs)) {
  67392. return DRFLAC_FALSE;
  67393. }
  67394. if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  67395. return DRFLAC_FALSE;
  67396. }
  67397. *pResultOut = (resultHi << bitCountLo) | (drflac_uint32)DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, bitCountLo);
  67398. bs->consumedBits += bitCountLo;
  67399. bs->cache <<= bitCountLo;
  67400. return DRFLAC_TRUE;
  67401. }
  67402. }
  67403. static drflac_bool32 drflac__read_int32(drflac_bs* bs, unsigned int bitCount, drflac_int32* pResult)
  67404. {
  67405. drflac_uint32 result;
  67406. DRFLAC_ASSERT(bs != NULL);
  67407. DRFLAC_ASSERT(pResult != NULL);
  67408. DRFLAC_ASSERT(bitCount > 0);
  67409. DRFLAC_ASSERT(bitCount <= 32);
  67410. if (!drflac__read_uint32(bs, bitCount, &result)) {
  67411. return DRFLAC_FALSE;
  67412. }
  67413. if (bitCount < 32) {
  67414. drflac_uint32 signbit;
  67415. signbit = ((result >> (bitCount-1)) & 0x01);
  67416. result |= (~signbit + 1) << bitCount;
  67417. }
  67418. *pResult = (drflac_int32)result;
  67419. return DRFLAC_TRUE;
  67420. }
  67421. #ifdef DRFLAC_64BIT
  67422. static drflac_bool32 drflac__read_uint64(drflac_bs* bs, unsigned int bitCount, drflac_uint64* pResultOut)
  67423. {
  67424. drflac_uint32 resultHi;
  67425. drflac_uint32 resultLo;
  67426. DRFLAC_ASSERT(bitCount <= 64);
  67427. DRFLAC_ASSERT(bitCount > 32);
  67428. if (!drflac__read_uint32(bs, bitCount - 32, &resultHi)) {
  67429. return DRFLAC_FALSE;
  67430. }
  67431. if (!drflac__read_uint32(bs, 32, &resultLo)) {
  67432. return DRFLAC_FALSE;
  67433. }
  67434. *pResultOut = (((drflac_uint64)resultHi) << 32) | ((drflac_uint64)resultLo);
  67435. return DRFLAC_TRUE;
  67436. }
  67437. #endif
  67438. #if 0
  67439. static drflac_bool32 drflac__read_int64(drflac_bs* bs, unsigned int bitCount, drflac_int64* pResultOut)
  67440. {
  67441. drflac_uint64 result;
  67442. drflac_uint64 signbit;
  67443. DRFLAC_ASSERT(bitCount <= 64);
  67444. if (!drflac__read_uint64(bs, bitCount, &result)) {
  67445. return DRFLAC_FALSE;
  67446. }
  67447. signbit = ((result >> (bitCount-1)) & 0x01);
  67448. result |= (~signbit + 1) << bitCount;
  67449. *pResultOut = (drflac_int64)result;
  67450. return DRFLAC_TRUE;
  67451. }
  67452. #endif
  67453. static drflac_bool32 drflac__read_uint16(drflac_bs* bs, unsigned int bitCount, drflac_uint16* pResult)
  67454. {
  67455. drflac_uint32 result;
  67456. DRFLAC_ASSERT(bs != NULL);
  67457. DRFLAC_ASSERT(pResult != NULL);
  67458. DRFLAC_ASSERT(bitCount > 0);
  67459. DRFLAC_ASSERT(bitCount <= 16);
  67460. if (!drflac__read_uint32(bs, bitCount, &result)) {
  67461. return DRFLAC_FALSE;
  67462. }
  67463. *pResult = (drflac_uint16)result;
  67464. return DRFLAC_TRUE;
  67465. }
  67466. #if 0
  67467. static drflac_bool32 drflac__read_int16(drflac_bs* bs, unsigned int bitCount, drflac_int16* pResult)
  67468. {
  67469. drflac_int32 result;
  67470. DRFLAC_ASSERT(bs != NULL);
  67471. DRFLAC_ASSERT(pResult != NULL);
  67472. DRFLAC_ASSERT(bitCount > 0);
  67473. DRFLAC_ASSERT(bitCount <= 16);
  67474. if (!drflac__read_int32(bs, bitCount, &result)) {
  67475. return DRFLAC_FALSE;
  67476. }
  67477. *pResult = (drflac_int16)result;
  67478. return DRFLAC_TRUE;
  67479. }
  67480. #endif
  67481. static drflac_bool32 drflac__read_uint8(drflac_bs* bs, unsigned int bitCount, drflac_uint8* pResult)
  67482. {
  67483. drflac_uint32 result;
  67484. DRFLAC_ASSERT(bs != NULL);
  67485. DRFLAC_ASSERT(pResult != NULL);
  67486. DRFLAC_ASSERT(bitCount > 0);
  67487. DRFLAC_ASSERT(bitCount <= 8);
  67488. if (!drflac__read_uint32(bs, bitCount, &result)) {
  67489. return DRFLAC_FALSE;
  67490. }
  67491. *pResult = (drflac_uint8)result;
  67492. return DRFLAC_TRUE;
  67493. }
  67494. static drflac_bool32 drflac__read_int8(drflac_bs* bs, unsigned int bitCount, drflac_int8* pResult)
  67495. {
  67496. drflac_int32 result;
  67497. DRFLAC_ASSERT(bs != NULL);
  67498. DRFLAC_ASSERT(pResult != NULL);
  67499. DRFLAC_ASSERT(bitCount > 0);
  67500. DRFLAC_ASSERT(bitCount <= 8);
  67501. if (!drflac__read_int32(bs, bitCount, &result)) {
  67502. return DRFLAC_FALSE;
  67503. }
  67504. *pResult = (drflac_int8)result;
  67505. return DRFLAC_TRUE;
  67506. }
  67507. static drflac_bool32 drflac__seek_bits(drflac_bs* bs, size_t bitsToSeek)
  67508. {
  67509. if (bitsToSeek <= DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  67510. bs->consumedBits += (drflac_uint32)bitsToSeek;
  67511. bs->cache <<= bitsToSeek;
  67512. return DRFLAC_TRUE;
  67513. } else {
  67514. bitsToSeek -= DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  67515. bs->consumedBits += DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  67516. bs->cache = 0;
  67517. #ifdef DRFLAC_64BIT
  67518. while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  67519. drflac_uint64 bin;
  67520. if (!drflac__read_uint64(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  67521. return DRFLAC_FALSE;
  67522. }
  67523. bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  67524. }
  67525. #else
  67526. while (bitsToSeek >= DRFLAC_CACHE_L1_SIZE_BITS(bs)) {
  67527. drflac_uint32 bin;
  67528. if (!drflac__read_uint32(bs, DRFLAC_CACHE_L1_SIZE_BITS(bs), &bin)) {
  67529. return DRFLAC_FALSE;
  67530. }
  67531. bitsToSeek -= DRFLAC_CACHE_L1_SIZE_BITS(bs);
  67532. }
  67533. #endif
  67534. while (bitsToSeek >= 8) {
  67535. drflac_uint8 bin;
  67536. if (!drflac__read_uint8(bs, 8, &bin)) {
  67537. return DRFLAC_FALSE;
  67538. }
  67539. bitsToSeek -= 8;
  67540. }
  67541. if (bitsToSeek > 0) {
  67542. drflac_uint8 bin;
  67543. if (!drflac__read_uint8(bs, (drflac_uint32)bitsToSeek, &bin)) {
  67544. return DRFLAC_FALSE;
  67545. }
  67546. bitsToSeek = 0;
  67547. }
  67548. DRFLAC_ASSERT(bitsToSeek == 0);
  67549. return DRFLAC_TRUE;
  67550. }
  67551. }
  67552. static drflac_bool32 drflac__find_and_seek_to_next_sync_code(drflac_bs* bs)
  67553. {
  67554. DRFLAC_ASSERT(bs != NULL);
  67555. if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  67556. return DRFLAC_FALSE;
  67557. }
  67558. for (;;) {
  67559. drflac_uint8 hi;
  67560. #ifndef DR_FLAC_NO_CRC
  67561. drflac__reset_crc16(bs);
  67562. #endif
  67563. if (!drflac__read_uint8(bs, 8, &hi)) {
  67564. return DRFLAC_FALSE;
  67565. }
  67566. if (hi == 0xFF) {
  67567. drflac_uint8 lo;
  67568. if (!drflac__read_uint8(bs, 6, &lo)) {
  67569. return DRFLAC_FALSE;
  67570. }
  67571. if (lo == 0x3E) {
  67572. return DRFLAC_TRUE;
  67573. } else {
  67574. if (!drflac__seek_bits(bs, DRFLAC_CACHE_L1_BITS_REMAINING(bs) & 7)) {
  67575. return DRFLAC_FALSE;
  67576. }
  67577. }
  67578. }
  67579. }
  67580. }
  67581. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC)
  67582. #define DRFLAC_IMPLEMENT_CLZ_LZCNT
  67583. #endif
  67584. #if defined(_MSC_VER) && _MSC_VER >= 1400 && (defined(DRFLAC_X64) || defined(DRFLAC_X86)) && !defined(__clang__)
  67585. #define DRFLAC_IMPLEMENT_CLZ_MSVC
  67586. #endif
  67587. #if defined(__WATCOMC__) && defined(__386__)
  67588. #define DRFLAC_IMPLEMENT_CLZ_WATCOM
  67589. #endif
  67590. #ifdef __MRC__
  67591. #include <intrinsics.h>
  67592. #define DRFLAC_IMPLEMENT_CLZ_MRC
  67593. #endif
  67594. static DRFLAC_INLINE drflac_uint32 drflac__clz_software(drflac_cache_t x)
  67595. {
  67596. drflac_uint32 n;
  67597. static drflac_uint32 clz_table_4[] = {
  67598. 0,
  67599. 4,
  67600. 3, 3,
  67601. 2, 2, 2, 2,
  67602. 1, 1, 1, 1, 1, 1, 1, 1
  67603. };
  67604. if (x == 0) {
  67605. return sizeof(x)*8;
  67606. }
  67607. n = clz_table_4[x >> (sizeof(x)*8 - 4)];
  67608. if (n == 0) {
  67609. #ifdef DRFLAC_64BIT
  67610. if ((x & ((drflac_uint64)0xFFFFFFFF << 32)) == 0) { n = 32; x <<= 32; }
  67611. if ((x & ((drflac_uint64)0xFFFF0000 << 32)) == 0) { n += 16; x <<= 16; }
  67612. if ((x & ((drflac_uint64)0xFF000000 << 32)) == 0) { n += 8; x <<= 8; }
  67613. if ((x & ((drflac_uint64)0xF0000000 << 32)) == 0) { n += 4; x <<= 4; }
  67614. #else
  67615. if ((x & 0xFFFF0000) == 0) { n = 16; x <<= 16; }
  67616. if ((x & 0xFF000000) == 0) { n += 8; x <<= 8; }
  67617. if ((x & 0xF0000000) == 0) { n += 4; x <<= 4; }
  67618. #endif
  67619. n += clz_table_4[x >> (sizeof(x)*8 - 4)];
  67620. }
  67621. return n - 1;
  67622. }
  67623. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  67624. static DRFLAC_INLINE drflac_bool32 drflac__is_lzcnt_supported(void)
  67625. {
  67626. #if defined(DRFLAC_HAS_LZCNT_INTRINSIC) && defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5)
  67627. return DRFLAC_TRUE;
  67628. #elif defined(__MRC__)
  67629. return DRFLAC_TRUE;
  67630. #else
  67631. #ifdef DRFLAC_HAS_LZCNT_INTRINSIC
  67632. return drflac__gIsLZCNTSupported;
  67633. #else
  67634. return DRFLAC_FALSE;
  67635. #endif
  67636. #endif
  67637. }
  67638. static DRFLAC_INLINE drflac_uint32 drflac__clz_lzcnt(drflac_cache_t x)
  67639. {
  67640. #if defined(_MSC_VER)
  67641. #ifdef DRFLAC_64BIT
  67642. return (drflac_uint32)__lzcnt64(x);
  67643. #else
  67644. return (drflac_uint32)__lzcnt(x);
  67645. #endif
  67646. #else
  67647. #if defined(__GNUC__) || defined(__clang__)
  67648. #if defined(DRFLAC_X64)
  67649. {
  67650. drflac_uint64 r;
  67651. __asm__ __volatile__ (
  67652. "lzcnt{ %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  67653. );
  67654. return (drflac_uint32)r;
  67655. }
  67656. #elif defined(DRFLAC_X86)
  67657. {
  67658. drflac_uint32 r;
  67659. __asm__ __volatile__ (
  67660. "lzcnt{l %1, %0| %0, %1}" : "=r"(r) : "r"(x) : "cc"
  67661. );
  67662. return r;
  67663. }
  67664. #elif defined(DRFLAC_ARM) && (defined(__ARM_ARCH) && __ARM_ARCH >= 5) && !defined(DRFLAC_64BIT)
  67665. {
  67666. unsigned int r;
  67667. __asm__ __volatile__ (
  67668. #if defined(DRFLAC_64BIT)
  67669. "clz %w[out], %w[in]" : [out]"=r"(r) : [in]"r"(x)
  67670. #else
  67671. "clz %[out], %[in]" : [out]"=r"(r) : [in]"r"(x)
  67672. #endif
  67673. );
  67674. return r;
  67675. }
  67676. #else
  67677. if (x == 0) {
  67678. return sizeof(x)*8;
  67679. }
  67680. #ifdef DRFLAC_64BIT
  67681. return (drflac_uint32)__builtin_clzll((drflac_uint64)x);
  67682. #else
  67683. return (drflac_uint32)__builtin_clzl((drflac_uint32)x);
  67684. #endif
  67685. #endif
  67686. #else
  67687. #error "This compiler does not support the lzcnt intrinsic."
  67688. #endif
  67689. #endif
  67690. }
  67691. #endif
  67692. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  67693. #include <intrin.h>
  67694. static DRFLAC_INLINE drflac_uint32 drflac__clz_msvc(drflac_cache_t x)
  67695. {
  67696. drflac_uint32 n;
  67697. if (x == 0) {
  67698. return sizeof(x)*8;
  67699. }
  67700. #ifdef DRFLAC_64BIT
  67701. _BitScanReverse64((unsigned long*)&n, x);
  67702. #else
  67703. _BitScanReverse((unsigned long*)&n, x);
  67704. #endif
  67705. return sizeof(x)*8 - n - 1;
  67706. }
  67707. #endif
  67708. #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM
  67709. static __inline drflac_uint32 drflac__clz_watcom (drflac_uint32);
  67710. #ifdef DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT
  67711. #pragma aux drflac__clz_watcom_lzcnt = \
  67712. "db 0F3h, 0Fh, 0BDh, 0C0h" \
  67713. parm [eax] \
  67714. value [eax] \
  67715. modify nomemory;
  67716. #else
  67717. #pragma aux drflac__clz_watcom = \
  67718. "bsr eax, eax" \
  67719. "xor eax, 31" \
  67720. parm [eax] nomemory \
  67721. value [eax] \
  67722. modify exact [eax] nomemory;
  67723. #endif
  67724. #endif
  67725. static DRFLAC_INLINE drflac_uint32 drflac__clz(drflac_cache_t x)
  67726. {
  67727. #ifdef DRFLAC_IMPLEMENT_CLZ_LZCNT
  67728. if (drflac__is_lzcnt_supported()) {
  67729. return drflac__clz_lzcnt(x);
  67730. } else
  67731. #endif
  67732. {
  67733. #ifdef DRFLAC_IMPLEMENT_CLZ_MSVC
  67734. return drflac__clz_msvc(x);
  67735. #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM_LZCNT)
  67736. return drflac__clz_watcom_lzcnt(x);
  67737. #elif defined(DRFLAC_IMPLEMENT_CLZ_WATCOM)
  67738. return (x == 0) ? sizeof(x)*8 : drflac__clz_watcom(x);
  67739. #elif defined(__MRC__)
  67740. return __cntlzw(x);
  67741. #else
  67742. return drflac__clz_software(x);
  67743. #endif
  67744. }
  67745. }
  67746. static DRFLAC_INLINE drflac_bool32 drflac__seek_past_next_set_bit(drflac_bs* bs, unsigned int* pOffsetOut)
  67747. {
  67748. drflac_uint32 zeroCounter = 0;
  67749. drflac_uint32 setBitOffsetPlus1;
  67750. while (bs->cache == 0) {
  67751. zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  67752. if (!drflac__reload_cache(bs)) {
  67753. return DRFLAC_FALSE;
  67754. }
  67755. }
  67756. if (bs->cache == 1) {
  67757. *pOffsetOut = zeroCounter + (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs) - 1;
  67758. if (!drflac__reload_cache(bs)) {
  67759. return DRFLAC_FALSE;
  67760. }
  67761. return DRFLAC_TRUE;
  67762. }
  67763. setBitOffsetPlus1 = drflac__clz(bs->cache);
  67764. setBitOffsetPlus1 += 1;
  67765. if (setBitOffsetPlus1 > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  67766. return DRFLAC_FALSE;
  67767. }
  67768. bs->consumedBits += setBitOffsetPlus1;
  67769. bs->cache <<= setBitOffsetPlus1;
  67770. *pOffsetOut = zeroCounter + setBitOffsetPlus1 - 1;
  67771. return DRFLAC_TRUE;
  67772. }
  67773. static drflac_bool32 drflac__seek_to_byte(drflac_bs* bs, drflac_uint64 offsetFromStart)
  67774. {
  67775. DRFLAC_ASSERT(bs != NULL);
  67776. DRFLAC_ASSERT(offsetFromStart > 0);
  67777. if (offsetFromStart > 0x7FFFFFFF) {
  67778. drflac_uint64 bytesRemaining = offsetFromStart;
  67779. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  67780. return DRFLAC_FALSE;
  67781. }
  67782. bytesRemaining -= 0x7FFFFFFF;
  67783. while (bytesRemaining > 0x7FFFFFFF) {
  67784. if (!bs->onSeek(bs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  67785. return DRFLAC_FALSE;
  67786. }
  67787. bytesRemaining -= 0x7FFFFFFF;
  67788. }
  67789. if (bytesRemaining > 0) {
  67790. if (!bs->onSeek(bs->pUserData, (int)bytesRemaining, drflac_seek_origin_current)) {
  67791. return DRFLAC_FALSE;
  67792. }
  67793. }
  67794. } else {
  67795. if (!bs->onSeek(bs->pUserData, (int)offsetFromStart, drflac_seek_origin_start)) {
  67796. return DRFLAC_FALSE;
  67797. }
  67798. }
  67799. drflac__reset_cache(bs);
  67800. return DRFLAC_TRUE;
  67801. }
  67802. static drflac_result drflac__read_utf8_coded_number(drflac_bs* bs, drflac_uint64* pNumberOut, drflac_uint8* pCRCOut)
  67803. {
  67804. drflac_uint8 crc;
  67805. drflac_uint64 result;
  67806. drflac_uint8 utf8[7] = {0};
  67807. int byteCount;
  67808. int i;
  67809. DRFLAC_ASSERT(bs != NULL);
  67810. DRFLAC_ASSERT(pNumberOut != NULL);
  67811. DRFLAC_ASSERT(pCRCOut != NULL);
  67812. crc = *pCRCOut;
  67813. if (!drflac__read_uint8(bs, 8, utf8)) {
  67814. *pNumberOut = 0;
  67815. return DRFLAC_AT_END;
  67816. }
  67817. crc = drflac_crc8(crc, utf8[0], 8);
  67818. if ((utf8[0] & 0x80) == 0) {
  67819. *pNumberOut = utf8[0];
  67820. *pCRCOut = crc;
  67821. return DRFLAC_SUCCESS;
  67822. }
  67823. if ((utf8[0] & 0xE0) == 0xC0) {
  67824. byteCount = 2;
  67825. } else if ((utf8[0] & 0xF0) == 0xE0) {
  67826. byteCount = 3;
  67827. } else if ((utf8[0] & 0xF8) == 0xF0) {
  67828. byteCount = 4;
  67829. } else if ((utf8[0] & 0xFC) == 0xF8) {
  67830. byteCount = 5;
  67831. } else if ((utf8[0] & 0xFE) == 0xFC) {
  67832. byteCount = 6;
  67833. } else if ((utf8[0] & 0xFF) == 0xFE) {
  67834. byteCount = 7;
  67835. } else {
  67836. *pNumberOut = 0;
  67837. return DRFLAC_CRC_MISMATCH;
  67838. }
  67839. DRFLAC_ASSERT(byteCount > 1);
  67840. result = (drflac_uint64)(utf8[0] & (0xFF >> (byteCount + 1)));
  67841. for (i = 1; i < byteCount; ++i) {
  67842. if (!drflac__read_uint8(bs, 8, utf8 + i)) {
  67843. *pNumberOut = 0;
  67844. return DRFLAC_AT_END;
  67845. }
  67846. crc = drflac_crc8(crc, utf8[i], 8);
  67847. result = (result << 6) | (utf8[i] & 0x3F);
  67848. }
  67849. *pNumberOut = result;
  67850. *pCRCOut = crc;
  67851. return DRFLAC_SUCCESS;
  67852. }
  67853. static DRFLAC_INLINE drflac_uint32 drflac__ilog2_u32(drflac_uint32 x)
  67854. {
  67855. #if 1
  67856. drflac_uint32 result = 0;
  67857. while (x > 0) {
  67858. result += 1;
  67859. x >>= 1;
  67860. }
  67861. return result;
  67862. #endif
  67863. }
  67864. static DRFLAC_INLINE drflac_bool32 drflac__use_64_bit_prediction(drflac_uint32 bitsPerSample, drflac_uint32 order, drflac_uint32 precision)
  67865. {
  67866. return bitsPerSample + precision + drflac__ilog2_u32(order) > 32;
  67867. }
  67868. #if defined(__clang__)
  67869. __attribute__((no_sanitize("signed-integer-overflow")))
  67870. #endif
  67871. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_32(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  67872. {
  67873. drflac_int32 prediction = 0;
  67874. DRFLAC_ASSERT(order <= 32);
  67875. switch (order)
  67876. {
  67877. case 32: prediction += coefficients[31] * pDecodedSamples[-32];
  67878. case 31: prediction += coefficients[30] * pDecodedSamples[-31];
  67879. case 30: prediction += coefficients[29] * pDecodedSamples[-30];
  67880. case 29: prediction += coefficients[28] * pDecodedSamples[-29];
  67881. case 28: prediction += coefficients[27] * pDecodedSamples[-28];
  67882. case 27: prediction += coefficients[26] * pDecodedSamples[-27];
  67883. case 26: prediction += coefficients[25] * pDecodedSamples[-26];
  67884. case 25: prediction += coefficients[24] * pDecodedSamples[-25];
  67885. case 24: prediction += coefficients[23] * pDecodedSamples[-24];
  67886. case 23: prediction += coefficients[22] * pDecodedSamples[-23];
  67887. case 22: prediction += coefficients[21] * pDecodedSamples[-22];
  67888. case 21: prediction += coefficients[20] * pDecodedSamples[-21];
  67889. case 20: prediction += coefficients[19] * pDecodedSamples[-20];
  67890. case 19: prediction += coefficients[18] * pDecodedSamples[-19];
  67891. case 18: prediction += coefficients[17] * pDecodedSamples[-18];
  67892. case 17: prediction += coefficients[16] * pDecodedSamples[-17];
  67893. case 16: prediction += coefficients[15] * pDecodedSamples[-16];
  67894. case 15: prediction += coefficients[14] * pDecodedSamples[-15];
  67895. case 14: prediction += coefficients[13] * pDecodedSamples[-14];
  67896. case 13: prediction += coefficients[12] * pDecodedSamples[-13];
  67897. case 12: prediction += coefficients[11] * pDecodedSamples[-12];
  67898. case 11: prediction += coefficients[10] * pDecodedSamples[-11];
  67899. case 10: prediction += coefficients[ 9] * pDecodedSamples[-10];
  67900. case 9: prediction += coefficients[ 8] * pDecodedSamples[- 9];
  67901. case 8: prediction += coefficients[ 7] * pDecodedSamples[- 8];
  67902. case 7: prediction += coefficients[ 6] * pDecodedSamples[- 7];
  67903. case 6: prediction += coefficients[ 5] * pDecodedSamples[- 6];
  67904. case 5: prediction += coefficients[ 4] * pDecodedSamples[- 5];
  67905. case 4: prediction += coefficients[ 3] * pDecodedSamples[- 4];
  67906. case 3: prediction += coefficients[ 2] * pDecodedSamples[- 3];
  67907. case 2: prediction += coefficients[ 1] * pDecodedSamples[- 2];
  67908. case 1: prediction += coefficients[ 0] * pDecodedSamples[- 1];
  67909. }
  67910. return (drflac_int32)(prediction >> shift);
  67911. }
  67912. static DRFLAC_INLINE drflac_int32 drflac__calculate_prediction_64(drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  67913. {
  67914. drflac_int64 prediction;
  67915. DRFLAC_ASSERT(order <= 32);
  67916. #ifndef DRFLAC_64BIT
  67917. if (order == 8)
  67918. {
  67919. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67920. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67921. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67922. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67923. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67924. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  67925. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  67926. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  67927. }
  67928. else if (order == 7)
  67929. {
  67930. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67931. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67932. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67933. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67934. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67935. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  67936. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  67937. }
  67938. else if (order == 3)
  67939. {
  67940. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67941. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67942. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67943. }
  67944. else if (order == 6)
  67945. {
  67946. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67947. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67948. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67949. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67950. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67951. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  67952. }
  67953. else if (order == 5)
  67954. {
  67955. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67956. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67957. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67958. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67959. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67960. }
  67961. else if (order == 4)
  67962. {
  67963. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67964. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67965. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67966. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67967. }
  67968. else if (order == 12)
  67969. {
  67970. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67971. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67972. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67973. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67974. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67975. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  67976. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  67977. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  67978. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  67979. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  67980. prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  67981. prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  67982. }
  67983. else if (order == 2)
  67984. {
  67985. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67986. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67987. }
  67988. else if (order == 1)
  67989. {
  67990. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67991. }
  67992. else if (order == 10)
  67993. {
  67994. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  67995. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  67996. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  67997. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  67998. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  67999. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  68000. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  68001. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  68002. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  68003. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  68004. }
  68005. else if (order == 9)
  68006. {
  68007. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  68008. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  68009. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  68010. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  68011. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  68012. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  68013. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  68014. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  68015. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  68016. }
  68017. else if (order == 11)
  68018. {
  68019. prediction = coefficients[0] * (drflac_int64)pDecodedSamples[-1];
  68020. prediction += coefficients[1] * (drflac_int64)pDecodedSamples[-2];
  68021. prediction += coefficients[2] * (drflac_int64)pDecodedSamples[-3];
  68022. prediction += coefficients[3] * (drflac_int64)pDecodedSamples[-4];
  68023. prediction += coefficients[4] * (drflac_int64)pDecodedSamples[-5];
  68024. prediction += coefficients[5] * (drflac_int64)pDecodedSamples[-6];
  68025. prediction += coefficients[6] * (drflac_int64)pDecodedSamples[-7];
  68026. prediction += coefficients[7] * (drflac_int64)pDecodedSamples[-8];
  68027. prediction += coefficients[8] * (drflac_int64)pDecodedSamples[-9];
  68028. prediction += coefficients[9] * (drflac_int64)pDecodedSamples[-10];
  68029. prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  68030. }
  68031. else
  68032. {
  68033. int j;
  68034. prediction = 0;
  68035. for (j = 0; j < (int)order; ++j) {
  68036. prediction += coefficients[j] * (drflac_int64)pDecodedSamples[-j-1];
  68037. }
  68038. }
  68039. #endif
  68040. #ifdef DRFLAC_64BIT
  68041. prediction = 0;
  68042. switch (order)
  68043. {
  68044. case 32: prediction += coefficients[31] * (drflac_int64)pDecodedSamples[-32];
  68045. case 31: prediction += coefficients[30] * (drflac_int64)pDecodedSamples[-31];
  68046. case 30: prediction += coefficients[29] * (drflac_int64)pDecodedSamples[-30];
  68047. case 29: prediction += coefficients[28] * (drflac_int64)pDecodedSamples[-29];
  68048. case 28: prediction += coefficients[27] * (drflac_int64)pDecodedSamples[-28];
  68049. case 27: prediction += coefficients[26] * (drflac_int64)pDecodedSamples[-27];
  68050. case 26: prediction += coefficients[25] * (drflac_int64)pDecodedSamples[-26];
  68051. case 25: prediction += coefficients[24] * (drflac_int64)pDecodedSamples[-25];
  68052. case 24: prediction += coefficients[23] * (drflac_int64)pDecodedSamples[-24];
  68053. case 23: prediction += coefficients[22] * (drflac_int64)pDecodedSamples[-23];
  68054. case 22: prediction += coefficients[21] * (drflac_int64)pDecodedSamples[-22];
  68055. case 21: prediction += coefficients[20] * (drflac_int64)pDecodedSamples[-21];
  68056. case 20: prediction += coefficients[19] * (drflac_int64)pDecodedSamples[-20];
  68057. case 19: prediction += coefficients[18] * (drflac_int64)pDecodedSamples[-19];
  68058. case 18: prediction += coefficients[17] * (drflac_int64)pDecodedSamples[-18];
  68059. case 17: prediction += coefficients[16] * (drflac_int64)pDecodedSamples[-17];
  68060. case 16: prediction += coefficients[15] * (drflac_int64)pDecodedSamples[-16];
  68061. case 15: prediction += coefficients[14] * (drflac_int64)pDecodedSamples[-15];
  68062. case 14: prediction += coefficients[13] * (drflac_int64)pDecodedSamples[-14];
  68063. case 13: prediction += coefficients[12] * (drflac_int64)pDecodedSamples[-13];
  68064. case 12: prediction += coefficients[11] * (drflac_int64)pDecodedSamples[-12];
  68065. case 11: prediction += coefficients[10] * (drflac_int64)pDecodedSamples[-11];
  68066. case 10: prediction += coefficients[ 9] * (drflac_int64)pDecodedSamples[-10];
  68067. case 9: prediction += coefficients[ 8] * (drflac_int64)pDecodedSamples[- 9];
  68068. case 8: prediction += coefficients[ 7] * (drflac_int64)pDecodedSamples[- 8];
  68069. case 7: prediction += coefficients[ 6] * (drflac_int64)pDecodedSamples[- 7];
  68070. case 6: prediction += coefficients[ 5] * (drflac_int64)pDecodedSamples[- 6];
  68071. case 5: prediction += coefficients[ 4] * (drflac_int64)pDecodedSamples[- 5];
  68072. case 4: prediction += coefficients[ 3] * (drflac_int64)pDecodedSamples[- 4];
  68073. case 3: prediction += coefficients[ 2] * (drflac_int64)pDecodedSamples[- 3];
  68074. case 2: prediction += coefficients[ 1] * (drflac_int64)pDecodedSamples[- 2];
  68075. case 1: prediction += coefficients[ 0] * (drflac_int64)pDecodedSamples[- 1];
  68076. }
  68077. #endif
  68078. return (drflac_int32)(prediction >> shift);
  68079. }
  68080. #if 0
  68081. static drflac_bool32 drflac__decode_samples_with_residual__rice__reference(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68082. {
  68083. drflac_uint32 i;
  68084. DRFLAC_ASSERT(bs != NULL);
  68085. DRFLAC_ASSERT(pSamplesOut != NULL);
  68086. for (i = 0; i < count; ++i) {
  68087. drflac_uint32 zeroCounter = 0;
  68088. for (;;) {
  68089. drflac_uint8 bit;
  68090. if (!drflac__read_uint8(bs, 1, &bit)) {
  68091. return DRFLAC_FALSE;
  68092. }
  68093. if (bit == 0) {
  68094. zeroCounter += 1;
  68095. } else {
  68096. break;
  68097. }
  68098. }
  68099. drflac_uint32 decodedRice;
  68100. if (riceParam > 0) {
  68101. if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  68102. return DRFLAC_FALSE;
  68103. }
  68104. } else {
  68105. decodedRice = 0;
  68106. }
  68107. decodedRice |= (zeroCounter << riceParam);
  68108. if ((decodedRice & 0x01)) {
  68109. decodedRice = ~(decodedRice >> 1);
  68110. } else {
  68111. decodedRice = (decodedRice >> 1);
  68112. }
  68113. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  68114. pSamplesOut[i] = decodedRice + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  68115. } else {
  68116. pSamplesOut[i] = decodedRice + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  68117. }
  68118. }
  68119. return DRFLAC_TRUE;
  68120. }
  68121. #endif
  68122. #if 0
  68123. static drflac_bool32 drflac__read_rice_parts__reference(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  68124. {
  68125. drflac_uint32 zeroCounter = 0;
  68126. drflac_uint32 decodedRice;
  68127. for (;;) {
  68128. drflac_uint8 bit;
  68129. if (!drflac__read_uint8(bs, 1, &bit)) {
  68130. return DRFLAC_FALSE;
  68131. }
  68132. if (bit == 0) {
  68133. zeroCounter += 1;
  68134. } else {
  68135. break;
  68136. }
  68137. }
  68138. if (riceParam > 0) {
  68139. if (!drflac__read_uint32(bs, riceParam, &decodedRice)) {
  68140. return DRFLAC_FALSE;
  68141. }
  68142. } else {
  68143. decodedRice = 0;
  68144. }
  68145. *pZeroCounterOut = zeroCounter;
  68146. *pRiceParamPartOut = decodedRice;
  68147. return DRFLAC_TRUE;
  68148. }
  68149. #endif
  68150. #if 0
  68151. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  68152. {
  68153. drflac_cache_t riceParamMask;
  68154. drflac_uint32 zeroCounter;
  68155. drflac_uint32 setBitOffsetPlus1;
  68156. drflac_uint32 riceParamPart;
  68157. drflac_uint32 riceLength;
  68158. DRFLAC_ASSERT(riceParam > 0);
  68159. riceParamMask = DRFLAC_CACHE_L1_SELECTION_MASK(riceParam);
  68160. zeroCounter = 0;
  68161. while (bs->cache == 0) {
  68162. zeroCounter += (drflac_uint32)DRFLAC_CACHE_L1_BITS_REMAINING(bs);
  68163. if (!drflac__reload_cache(bs)) {
  68164. return DRFLAC_FALSE;
  68165. }
  68166. }
  68167. setBitOffsetPlus1 = drflac__clz(bs->cache);
  68168. zeroCounter += setBitOffsetPlus1;
  68169. setBitOffsetPlus1 += 1;
  68170. riceLength = setBitOffsetPlus1 + riceParam;
  68171. if (riceLength < DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  68172. riceParamPart = (drflac_uint32)((bs->cache & (riceParamMask >> setBitOffsetPlus1)) >> DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceLength));
  68173. bs->consumedBits += riceLength;
  68174. bs->cache <<= riceLength;
  68175. } else {
  68176. drflac_uint32 bitCountLo;
  68177. drflac_cache_t resultHi;
  68178. bs->consumedBits += riceLength;
  68179. bs->cache <<= setBitOffsetPlus1 & (DRFLAC_CACHE_L1_SIZE_BITS(bs)-1);
  68180. bitCountLo = bs->consumedBits - DRFLAC_CACHE_L1_SIZE_BITS(bs);
  68181. resultHi = DRFLAC_CACHE_L1_SELECT_AND_SHIFT(bs, riceParam);
  68182. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  68183. #ifndef DR_FLAC_NO_CRC
  68184. drflac__update_crc16(bs);
  68185. #endif
  68186. bs->cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  68187. bs->consumedBits = 0;
  68188. #ifndef DR_FLAC_NO_CRC
  68189. bs->crc16Cache = bs->cache;
  68190. #endif
  68191. } else {
  68192. if (!drflac__reload_cache(bs)) {
  68193. return DRFLAC_FALSE;
  68194. }
  68195. if (bitCountLo > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  68196. return DRFLAC_FALSE;
  68197. }
  68198. }
  68199. riceParamPart = (drflac_uint32)(resultHi | DRFLAC_CACHE_L1_SELECT_AND_SHIFT_SAFE(bs, bitCountLo));
  68200. bs->consumedBits += bitCountLo;
  68201. bs->cache <<= bitCountLo;
  68202. }
  68203. pZeroCounterOut[0] = zeroCounter;
  68204. pRiceParamPartOut[0] = riceParamPart;
  68205. return DRFLAC_TRUE;
  68206. }
  68207. #endif
  68208. static DRFLAC_INLINE drflac_bool32 drflac__read_rice_parts_x1(drflac_bs* bs, drflac_uint8 riceParam, drflac_uint32* pZeroCounterOut, drflac_uint32* pRiceParamPartOut)
  68209. {
  68210. drflac_uint32 riceParamPlus1 = riceParam + 1;
  68211. drflac_uint32 riceParamPlus1Shift = DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPlus1);
  68212. drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  68213. drflac_cache_t bs_cache = bs->cache;
  68214. drflac_uint32 bs_consumedBits = bs->consumedBits;
  68215. drflac_uint32 lzcount = drflac__clz(bs_cache);
  68216. if (lzcount < sizeof(bs_cache)*8) {
  68217. pZeroCounterOut[0] = lzcount;
  68218. extract_rice_param_part:
  68219. bs_cache <<= lzcount;
  68220. bs_consumedBits += lzcount;
  68221. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  68222. pRiceParamPartOut[0] = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  68223. bs_cache <<= riceParamPlus1;
  68224. bs_consumedBits += riceParamPlus1;
  68225. } else {
  68226. drflac_uint32 riceParamPartHi;
  68227. drflac_uint32 riceParamPartLo;
  68228. drflac_uint32 riceParamPartLoBitCount;
  68229. riceParamPartHi = (drflac_uint32)(bs_cache >> riceParamPlus1Shift);
  68230. riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  68231. DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  68232. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  68233. #ifndef DR_FLAC_NO_CRC
  68234. drflac__update_crc16(bs);
  68235. #endif
  68236. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  68237. bs_consumedBits = riceParamPartLoBitCount;
  68238. #ifndef DR_FLAC_NO_CRC
  68239. bs->crc16Cache = bs_cache;
  68240. #endif
  68241. } else {
  68242. if (!drflac__reload_cache(bs)) {
  68243. return DRFLAC_FALSE;
  68244. }
  68245. if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  68246. return DRFLAC_FALSE;
  68247. }
  68248. bs_cache = bs->cache;
  68249. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  68250. }
  68251. riceParamPartLo = (drflac_uint32)(bs_cache >> (DRFLAC_CACHE_L1_SELECTION_SHIFT(bs, riceParamPartLoBitCount)));
  68252. pRiceParamPartOut[0] = riceParamPartHi | riceParamPartLo;
  68253. bs_cache <<= riceParamPartLoBitCount;
  68254. }
  68255. } else {
  68256. drflac_uint32 zeroCounter = (drflac_uint32)(DRFLAC_CACHE_L1_SIZE_BITS(bs) - bs_consumedBits);
  68257. for (;;) {
  68258. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  68259. #ifndef DR_FLAC_NO_CRC
  68260. drflac__update_crc16(bs);
  68261. #endif
  68262. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  68263. bs_consumedBits = 0;
  68264. #ifndef DR_FLAC_NO_CRC
  68265. bs->crc16Cache = bs_cache;
  68266. #endif
  68267. } else {
  68268. if (!drflac__reload_cache(bs)) {
  68269. return DRFLAC_FALSE;
  68270. }
  68271. bs_cache = bs->cache;
  68272. bs_consumedBits = bs->consumedBits;
  68273. }
  68274. lzcount = drflac__clz(bs_cache);
  68275. zeroCounter += lzcount;
  68276. if (lzcount < sizeof(bs_cache)*8) {
  68277. break;
  68278. }
  68279. }
  68280. pZeroCounterOut[0] = zeroCounter;
  68281. goto extract_rice_param_part;
  68282. }
  68283. bs->cache = bs_cache;
  68284. bs->consumedBits = bs_consumedBits;
  68285. return DRFLAC_TRUE;
  68286. }
  68287. static DRFLAC_INLINE drflac_bool32 drflac__seek_rice_parts(drflac_bs* bs, drflac_uint8 riceParam)
  68288. {
  68289. drflac_uint32 riceParamPlus1 = riceParam + 1;
  68290. drflac_uint32 riceParamPlus1MaxConsumedBits = DRFLAC_CACHE_L1_SIZE_BITS(bs) - riceParamPlus1;
  68291. drflac_cache_t bs_cache = bs->cache;
  68292. drflac_uint32 bs_consumedBits = bs->consumedBits;
  68293. drflac_uint32 lzcount = drflac__clz(bs_cache);
  68294. if (lzcount < sizeof(bs_cache)*8) {
  68295. extract_rice_param_part:
  68296. bs_cache <<= lzcount;
  68297. bs_consumedBits += lzcount;
  68298. if (bs_consumedBits <= riceParamPlus1MaxConsumedBits) {
  68299. bs_cache <<= riceParamPlus1;
  68300. bs_consumedBits += riceParamPlus1;
  68301. } else {
  68302. drflac_uint32 riceParamPartLoBitCount = bs_consumedBits - riceParamPlus1MaxConsumedBits;
  68303. DRFLAC_ASSERT(riceParamPartLoBitCount > 0 && riceParamPartLoBitCount < 32);
  68304. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  68305. #ifndef DR_FLAC_NO_CRC
  68306. drflac__update_crc16(bs);
  68307. #endif
  68308. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  68309. bs_consumedBits = riceParamPartLoBitCount;
  68310. #ifndef DR_FLAC_NO_CRC
  68311. bs->crc16Cache = bs_cache;
  68312. #endif
  68313. } else {
  68314. if (!drflac__reload_cache(bs)) {
  68315. return DRFLAC_FALSE;
  68316. }
  68317. if (riceParamPartLoBitCount > DRFLAC_CACHE_L1_BITS_REMAINING(bs)) {
  68318. return DRFLAC_FALSE;
  68319. }
  68320. bs_cache = bs->cache;
  68321. bs_consumedBits = bs->consumedBits + riceParamPartLoBitCount;
  68322. }
  68323. bs_cache <<= riceParamPartLoBitCount;
  68324. }
  68325. } else {
  68326. for (;;) {
  68327. if (bs->nextL2Line < DRFLAC_CACHE_L2_LINE_COUNT(bs)) {
  68328. #ifndef DR_FLAC_NO_CRC
  68329. drflac__update_crc16(bs);
  68330. #endif
  68331. bs_cache = drflac__be2host__cache_line(bs->cacheL2[bs->nextL2Line++]);
  68332. bs_consumedBits = 0;
  68333. #ifndef DR_FLAC_NO_CRC
  68334. bs->crc16Cache = bs_cache;
  68335. #endif
  68336. } else {
  68337. if (!drflac__reload_cache(bs)) {
  68338. return DRFLAC_FALSE;
  68339. }
  68340. bs_cache = bs->cache;
  68341. bs_consumedBits = bs->consumedBits;
  68342. }
  68343. lzcount = drflac__clz(bs_cache);
  68344. if (lzcount < sizeof(bs_cache)*8) {
  68345. break;
  68346. }
  68347. }
  68348. goto extract_rice_param_part;
  68349. }
  68350. bs->cache = bs_cache;
  68351. bs->consumedBits = bs_consumedBits;
  68352. return DRFLAC_TRUE;
  68353. }
  68354. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar_zeroorder(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68355. {
  68356. drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  68357. drflac_uint32 zeroCountPart0;
  68358. drflac_uint32 riceParamPart0;
  68359. drflac_uint32 riceParamMask;
  68360. drflac_uint32 i;
  68361. DRFLAC_ASSERT(bs != NULL);
  68362. DRFLAC_ASSERT(pSamplesOut != NULL);
  68363. (void)bitsPerSample;
  68364. (void)order;
  68365. (void)shift;
  68366. (void)coefficients;
  68367. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  68368. i = 0;
  68369. while (i < count) {
  68370. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  68371. return DRFLAC_FALSE;
  68372. }
  68373. riceParamPart0 &= riceParamMask;
  68374. riceParamPart0 |= (zeroCountPart0 << riceParam);
  68375. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  68376. pSamplesOut[i] = riceParamPart0;
  68377. i += 1;
  68378. }
  68379. return DRFLAC_TRUE;
  68380. }
  68381. static drflac_bool32 drflac__decode_samples_with_residual__rice__scalar(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68382. {
  68383. drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  68384. drflac_uint32 zeroCountPart0 = 0;
  68385. drflac_uint32 zeroCountPart1 = 0;
  68386. drflac_uint32 zeroCountPart2 = 0;
  68387. drflac_uint32 zeroCountPart3 = 0;
  68388. drflac_uint32 riceParamPart0 = 0;
  68389. drflac_uint32 riceParamPart1 = 0;
  68390. drflac_uint32 riceParamPart2 = 0;
  68391. drflac_uint32 riceParamPart3 = 0;
  68392. drflac_uint32 riceParamMask;
  68393. const drflac_int32* pSamplesOutEnd;
  68394. drflac_uint32 i;
  68395. DRFLAC_ASSERT(bs != NULL);
  68396. DRFLAC_ASSERT(pSamplesOut != NULL);
  68397. if (lpcOrder == 0) {
  68398. return drflac__decode_samples_with_residual__rice__scalar_zeroorder(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  68399. }
  68400. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  68401. pSamplesOutEnd = pSamplesOut + (count & ~3);
  68402. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  68403. while (pSamplesOut < pSamplesOutEnd) {
  68404. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  68405. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  68406. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  68407. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  68408. return DRFLAC_FALSE;
  68409. }
  68410. riceParamPart0 &= riceParamMask;
  68411. riceParamPart1 &= riceParamMask;
  68412. riceParamPart2 &= riceParamMask;
  68413. riceParamPart3 &= riceParamMask;
  68414. riceParamPart0 |= (zeroCountPart0 << riceParam);
  68415. riceParamPart1 |= (zeroCountPart1 << riceParam);
  68416. riceParamPart2 |= (zeroCountPart2 << riceParam);
  68417. riceParamPart3 |= (zeroCountPart3 << riceParam);
  68418. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  68419. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  68420. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  68421. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  68422. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  68423. pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  68424. pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  68425. pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  68426. pSamplesOut += 4;
  68427. }
  68428. } else {
  68429. while (pSamplesOut < pSamplesOutEnd) {
  68430. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0) ||
  68431. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart1, &riceParamPart1) ||
  68432. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart2, &riceParamPart2) ||
  68433. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart3, &riceParamPart3)) {
  68434. return DRFLAC_FALSE;
  68435. }
  68436. riceParamPart0 &= riceParamMask;
  68437. riceParamPart1 &= riceParamMask;
  68438. riceParamPart2 &= riceParamMask;
  68439. riceParamPart3 &= riceParamMask;
  68440. riceParamPart0 |= (zeroCountPart0 << riceParam);
  68441. riceParamPart1 |= (zeroCountPart1 << riceParam);
  68442. riceParamPart2 |= (zeroCountPart2 << riceParam);
  68443. riceParamPart3 |= (zeroCountPart3 << riceParam);
  68444. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  68445. riceParamPart1 = (riceParamPart1 >> 1) ^ t[riceParamPart1 & 0x01];
  68446. riceParamPart2 = (riceParamPart2 >> 1) ^ t[riceParamPart2 & 0x01];
  68447. riceParamPart3 = (riceParamPart3 >> 1) ^ t[riceParamPart3 & 0x01];
  68448. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  68449. pSamplesOut[1] = riceParamPart1 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 1);
  68450. pSamplesOut[2] = riceParamPart2 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 2);
  68451. pSamplesOut[3] = riceParamPart3 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 3);
  68452. pSamplesOut += 4;
  68453. }
  68454. }
  68455. i = (count & ~3);
  68456. while (i < count) {
  68457. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountPart0, &riceParamPart0)) {
  68458. return DRFLAC_FALSE;
  68459. }
  68460. riceParamPart0 &= riceParamMask;
  68461. riceParamPart0 |= (zeroCountPart0 << riceParam);
  68462. riceParamPart0 = (riceParamPart0 >> 1) ^ t[riceParamPart0 & 0x01];
  68463. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  68464. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  68465. } else {
  68466. pSamplesOut[0] = riceParamPart0 + drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + 0);
  68467. }
  68468. i += 1;
  68469. pSamplesOut += 1;
  68470. }
  68471. return DRFLAC_TRUE;
  68472. }
  68473. #if defined(DRFLAC_SUPPORT_SSE2)
  68474. static DRFLAC_INLINE __m128i drflac__mm_packs_interleaved_epi32(__m128i a, __m128i b)
  68475. {
  68476. __m128i r;
  68477. r = _mm_packs_epi32(a, b);
  68478. r = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 1, 2, 0));
  68479. r = _mm_shufflehi_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  68480. r = _mm_shufflelo_epi16(r, _MM_SHUFFLE(3, 1, 2, 0));
  68481. return r;
  68482. }
  68483. #endif
  68484. #if defined(DRFLAC_SUPPORT_SSE41)
  68485. static DRFLAC_INLINE __m128i drflac__mm_not_si128(__m128i a)
  68486. {
  68487. return _mm_xor_si128(a, _mm_cmpeq_epi32(_mm_setzero_si128(), _mm_setzero_si128()));
  68488. }
  68489. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi32(__m128i x)
  68490. {
  68491. __m128i x64 = _mm_add_epi32(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  68492. __m128i x32 = _mm_shufflelo_epi16(x64, _MM_SHUFFLE(1, 0, 3, 2));
  68493. return _mm_add_epi32(x64, x32);
  68494. }
  68495. static DRFLAC_INLINE __m128i drflac__mm_hadd_epi64(__m128i x)
  68496. {
  68497. return _mm_add_epi64(x, _mm_shuffle_epi32(x, _MM_SHUFFLE(1, 0, 3, 2)));
  68498. }
  68499. static DRFLAC_INLINE __m128i drflac__mm_srai_epi64(__m128i x, int count)
  68500. {
  68501. __m128i lo = _mm_srli_epi64(x, count);
  68502. __m128i hi = _mm_srai_epi32(x, count);
  68503. hi = _mm_and_si128(hi, _mm_set_epi32(0xFFFFFFFF, 0, 0xFFFFFFFF, 0));
  68504. return _mm_or_si128(lo, hi);
  68505. }
  68506. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68507. {
  68508. int i;
  68509. drflac_uint32 riceParamMask;
  68510. drflac_int32* pDecodedSamples = pSamplesOut;
  68511. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  68512. drflac_uint32 zeroCountParts0 = 0;
  68513. drflac_uint32 zeroCountParts1 = 0;
  68514. drflac_uint32 zeroCountParts2 = 0;
  68515. drflac_uint32 zeroCountParts3 = 0;
  68516. drflac_uint32 riceParamParts0 = 0;
  68517. drflac_uint32 riceParamParts1 = 0;
  68518. drflac_uint32 riceParamParts2 = 0;
  68519. drflac_uint32 riceParamParts3 = 0;
  68520. __m128i coefficients128_0;
  68521. __m128i coefficients128_4;
  68522. __m128i coefficients128_8;
  68523. __m128i samples128_0;
  68524. __m128i samples128_4;
  68525. __m128i samples128_8;
  68526. __m128i riceParamMask128;
  68527. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  68528. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  68529. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  68530. coefficients128_0 = _mm_setzero_si128();
  68531. coefficients128_4 = _mm_setzero_si128();
  68532. coefficients128_8 = _mm_setzero_si128();
  68533. samples128_0 = _mm_setzero_si128();
  68534. samples128_4 = _mm_setzero_si128();
  68535. samples128_8 = _mm_setzero_si128();
  68536. #if 1
  68537. {
  68538. int runningOrder = order;
  68539. if (runningOrder >= 4) {
  68540. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  68541. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  68542. runningOrder -= 4;
  68543. } else {
  68544. switch (runningOrder) {
  68545. 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;
  68546. 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;
  68547. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  68548. }
  68549. runningOrder = 0;
  68550. }
  68551. if (runningOrder >= 4) {
  68552. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  68553. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  68554. runningOrder -= 4;
  68555. } else {
  68556. switch (runningOrder) {
  68557. 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;
  68558. 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;
  68559. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  68560. }
  68561. runningOrder = 0;
  68562. }
  68563. if (runningOrder == 4) {
  68564. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  68565. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  68566. runningOrder -= 4;
  68567. } else {
  68568. switch (runningOrder) {
  68569. 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;
  68570. 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;
  68571. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  68572. }
  68573. runningOrder = 0;
  68574. }
  68575. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  68576. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  68577. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  68578. }
  68579. #else
  68580. switch (order)
  68581. {
  68582. case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  68583. case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  68584. case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  68585. case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  68586. case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  68587. case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  68588. case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  68589. case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  68590. case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  68591. case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  68592. case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  68593. case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  68594. }
  68595. #endif
  68596. while (pDecodedSamples < pDecodedSamplesEnd) {
  68597. __m128i prediction128;
  68598. __m128i zeroCountPart128;
  68599. __m128i riceParamPart128;
  68600. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  68601. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  68602. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  68603. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  68604. return DRFLAC_FALSE;
  68605. }
  68606. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  68607. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  68608. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  68609. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  68610. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(0x01))), _mm_set1_epi32(0x01)));
  68611. if (order <= 4) {
  68612. for (i = 0; i < 4; i += 1) {
  68613. prediction128 = _mm_mullo_epi32(coefficients128_0, samples128_0);
  68614. prediction128 = drflac__mm_hadd_epi32(prediction128);
  68615. prediction128 = _mm_srai_epi32(prediction128, shift);
  68616. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  68617. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  68618. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  68619. }
  68620. } else if (order <= 8) {
  68621. for (i = 0; i < 4; i += 1) {
  68622. prediction128 = _mm_mullo_epi32(coefficients128_4, samples128_4);
  68623. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  68624. prediction128 = drflac__mm_hadd_epi32(prediction128);
  68625. prediction128 = _mm_srai_epi32(prediction128, shift);
  68626. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  68627. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  68628. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  68629. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  68630. }
  68631. } else {
  68632. for (i = 0; i < 4; i += 1) {
  68633. prediction128 = _mm_mullo_epi32(coefficients128_8, samples128_8);
  68634. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_4, samples128_4));
  68635. prediction128 = _mm_add_epi32(prediction128, _mm_mullo_epi32(coefficients128_0, samples128_0));
  68636. prediction128 = drflac__mm_hadd_epi32(prediction128);
  68637. prediction128 = _mm_srai_epi32(prediction128, shift);
  68638. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  68639. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  68640. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  68641. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  68642. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  68643. }
  68644. }
  68645. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  68646. pDecodedSamples += 4;
  68647. }
  68648. i = (count & ~3);
  68649. while (i < (int)count) {
  68650. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  68651. return DRFLAC_FALSE;
  68652. }
  68653. riceParamParts0 &= riceParamMask;
  68654. riceParamParts0 |= (zeroCountParts0 << riceParam);
  68655. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  68656. pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  68657. i += 1;
  68658. pDecodedSamples += 1;
  68659. }
  68660. return DRFLAC_TRUE;
  68661. }
  68662. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68663. {
  68664. int i;
  68665. drflac_uint32 riceParamMask;
  68666. drflac_int32* pDecodedSamples = pSamplesOut;
  68667. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  68668. drflac_uint32 zeroCountParts0 = 0;
  68669. drflac_uint32 zeroCountParts1 = 0;
  68670. drflac_uint32 zeroCountParts2 = 0;
  68671. drflac_uint32 zeroCountParts3 = 0;
  68672. drflac_uint32 riceParamParts0 = 0;
  68673. drflac_uint32 riceParamParts1 = 0;
  68674. drflac_uint32 riceParamParts2 = 0;
  68675. drflac_uint32 riceParamParts3 = 0;
  68676. __m128i coefficients128_0;
  68677. __m128i coefficients128_4;
  68678. __m128i coefficients128_8;
  68679. __m128i samples128_0;
  68680. __m128i samples128_4;
  68681. __m128i samples128_8;
  68682. __m128i prediction128;
  68683. __m128i riceParamMask128;
  68684. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  68685. DRFLAC_ASSERT(order <= 12);
  68686. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  68687. riceParamMask128 = _mm_set1_epi32(riceParamMask);
  68688. prediction128 = _mm_setzero_si128();
  68689. coefficients128_0 = _mm_setzero_si128();
  68690. coefficients128_4 = _mm_setzero_si128();
  68691. coefficients128_8 = _mm_setzero_si128();
  68692. samples128_0 = _mm_setzero_si128();
  68693. samples128_4 = _mm_setzero_si128();
  68694. samples128_8 = _mm_setzero_si128();
  68695. #if 1
  68696. {
  68697. int runningOrder = order;
  68698. if (runningOrder >= 4) {
  68699. coefficients128_0 = _mm_loadu_si128((const __m128i*)(coefficients + 0));
  68700. samples128_0 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 4));
  68701. runningOrder -= 4;
  68702. } else {
  68703. switch (runningOrder) {
  68704. 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;
  68705. 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;
  68706. case 1: coefficients128_0 = _mm_set_epi32(0, 0, 0, coefficients[0]); samples128_0 = _mm_set_epi32(pSamplesOut[-1], 0, 0, 0); break;
  68707. }
  68708. runningOrder = 0;
  68709. }
  68710. if (runningOrder >= 4) {
  68711. coefficients128_4 = _mm_loadu_si128((const __m128i*)(coefficients + 4));
  68712. samples128_4 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 8));
  68713. runningOrder -= 4;
  68714. } else {
  68715. switch (runningOrder) {
  68716. 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;
  68717. 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;
  68718. case 1: coefficients128_4 = _mm_set_epi32(0, 0, 0, coefficients[4]); samples128_4 = _mm_set_epi32(pSamplesOut[-5], 0, 0, 0); break;
  68719. }
  68720. runningOrder = 0;
  68721. }
  68722. if (runningOrder == 4) {
  68723. coefficients128_8 = _mm_loadu_si128((const __m128i*)(coefficients + 8));
  68724. samples128_8 = _mm_loadu_si128((const __m128i*)(pSamplesOut - 12));
  68725. runningOrder -= 4;
  68726. } else {
  68727. switch (runningOrder) {
  68728. 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;
  68729. 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;
  68730. case 1: coefficients128_8 = _mm_set_epi32(0, 0, 0, coefficients[8]); samples128_8 = _mm_set_epi32(pSamplesOut[-9], 0, 0, 0); break;
  68731. }
  68732. runningOrder = 0;
  68733. }
  68734. coefficients128_0 = _mm_shuffle_epi32(coefficients128_0, _MM_SHUFFLE(0, 1, 2, 3));
  68735. coefficients128_4 = _mm_shuffle_epi32(coefficients128_4, _MM_SHUFFLE(0, 1, 2, 3));
  68736. coefficients128_8 = _mm_shuffle_epi32(coefficients128_8, _MM_SHUFFLE(0, 1, 2, 3));
  68737. }
  68738. #else
  68739. switch (order)
  68740. {
  68741. case 12: ((drflac_int32*)&coefficients128_8)[0] = coefficients[11]; ((drflac_int32*)&samples128_8)[0] = pDecodedSamples[-12];
  68742. case 11: ((drflac_int32*)&coefficients128_8)[1] = coefficients[10]; ((drflac_int32*)&samples128_8)[1] = pDecodedSamples[-11];
  68743. case 10: ((drflac_int32*)&coefficients128_8)[2] = coefficients[ 9]; ((drflac_int32*)&samples128_8)[2] = pDecodedSamples[-10];
  68744. case 9: ((drflac_int32*)&coefficients128_8)[3] = coefficients[ 8]; ((drflac_int32*)&samples128_8)[3] = pDecodedSamples[- 9];
  68745. case 8: ((drflac_int32*)&coefficients128_4)[0] = coefficients[ 7]; ((drflac_int32*)&samples128_4)[0] = pDecodedSamples[- 8];
  68746. case 7: ((drflac_int32*)&coefficients128_4)[1] = coefficients[ 6]; ((drflac_int32*)&samples128_4)[1] = pDecodedSamples[- 7];
  68747. case 6: ((drflac_int32*)&coefficients128_4)[2] = coefficients[ 5]; ((drflac_int32*)&samples128_4)[2] = pDecodedSamples[- 6];
  68748. case 5: ((drflac_int32*)&coefficients128_4)[3] = coefficients[ 4]; ((drflac_int32*)&samples128_4)[3] = pDecodedSamples[- 5];
  68749. case 4: ((drflac_int32*)&coefficients128_0)[0] = coefficients[ 3]; ((drflac_int32*)&samples128_0)[0] = pDecodedSamples[- 4];
  68750. case 3: ((drflac_int32*)&coefficients128_0)[1] = coefficients[ 2]; ((drflac_int32*)&samples128_0)[1] = pDecodedSamples[- 3];
  68751. case 2: ((drflac_int32*)&coefficients128_0)[2] = coefficients[ 1]; ((drflac_int32*)&samples128_0)[2] = pDecodedSamples[- 2];
  68752. case 1: ((drflac_int32*)&coefficients128_0)[3] = coefficients[ 0]; ((drflac_int32*)&samples128_0)[3] = pDecodedSamples[- 1];
  68753. }
  68754. #endif
  68755. while (pDecodedSamples < pDecodedSamplesEnd) {
  68756. __m128i zeroCountPart128;
  68757. __m128i riceParamPart128;
  68758. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0) ||
  68759. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts1, &riceParamParts1) ||
  68760. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts2, &riceParamParts2) ||
  68761. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts3, &riceParamParts3)) {
  68762. return DRFLAC_FALSE;
  68763. }
  68764. zeroCountPart128 = _mm_set_epi32(zeroCountParts3, zeroCountParts2, zeroCountParts1, zeroCountParts0);
  68765. riceParamPart128 = _mm_set_epi32(riceParamParts3, riceParamParts2, riceParamParts1, riceParamParts0);
  68766. riceParamPart128 = _mm_and_si128(riceParamPart128, riceParamMask128);
  68767. riceParamPart128 = _mm_or_si128(riceParamPart128, _mm_slli_epi32(zeroCountPart128, riceParam));
  68768. riceParamPart128 = _mm_xor_si128(_mm_srli_epi32(riceParamPart128, 1), _mm_add_epi32(drflac__mm_not_si128(_mm_and_si128(riceParamPart128, _mm_set1_epi32(1))), _mm_set1_epi32(1)));
  68769. for (i = 0; i < 4; i += 1) {
  68770. prediction128 = _mm_xor_si128(prediction128, prediction128);
  68771. switch (order)
  68772. {
  68773. case 12:
  68774. 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))));
  68775. case 10:
  68776. 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))));
  68777. case 8:
  68778. 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))));
  68779. case 6:
  68780. 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))));
  68781. case 4:
  68782. 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))));
  68783. case 2:
  68784. 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))));
  68785. }
  68786. prediction128 = drflac__mm_hadd_epi64(prediction128);
  68787. prediction128 = drflac__mm_srai_epi64(prediction128, shift);
  68788. prediction128 = _mm_add_epi32(riceParamPart128, prediction128);
  68789. samples128_8 = _mm_alignr_epi8(samples128_4, samples128_8, 4);
  68790. samples128_4 = _mm_alignr_epi8(samples128_0, samples128_4, 4);
  68791. samples128_0 = _mm_alignr_epi8(prediction128, samples128_0, 4);
  68792. riceParamPart128 = _mm_alignr_epi8(_mm_setzero_si128(), riceParamPart128, 4);
  68793. }
  68794. _mm_storeu_si128((__m128i*)pDecodedSamples, samples128_0);
  68795. pDecodedSamples += 4;
  68796. }
  68797. i = (count & ~3);
  68798. while (i < (int)count) {
  68799. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts0, &riceParamParts0)) {
  68800. return DRFLAC_FALSE;
  68801. }
  68802. riceParamParts0 &= riceParamMask;
  68803. riceParamParts0 |= (zeroCountParts0 << riceParam);
  68804. riceParamParts0 = (riceParamParts0 >> 1) ^ t[riceParamParts0 & 0x01];
  68805. pDecodedSamples[0] = riceParamParts0 + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  68806. i += 1;
  68807. pDecodedSamples += 1;
  68808. }
  68809. return DRFLAC_TRUE;
  68810. }
  68811. static drflac_bool32 drflac__decode_samples_with_residual__rice__sse41(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68812. {
  68813. DRFLAC_ASSERT(bs != NULL);
  68814. DRFLAC_ASSERT(pSamplesOut != NULL);
  68815. if (lpcOrder > 0 && lpcOrder <= 12) {
  68816. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  68817. return drflac__decode_samples_with_residual__rice__sse41_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  68818. } else {
  68819. return drflac__decode_samples_with_residual__rice__sse41_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  68820. }
  68821. } else {
  68822. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  68823. }
  68824. }
  68825. #endif
  68826. #if defined(DRFLAC_SUPPORT_NEON)
  68827. static DRFLAC_INLINE void drflac__vst2q_s32(drflac_int32* p, int32x4x2_t x)
  68828. {
  68829. vst1q_s32(p+0, x.val[0]);
  68830. vst1q_s32(p+4, x.val[1]);
  68831. }
  68832. static DRFLAC_INLINE void drflac__vst2q_u32(drflac_uint32* p, uint32x4x2_t x)
  68833. {
  68834. vst1q_u32(p+0, x.val[0]);
  68835. vst1q_u32(p+4, x.val[1]);
  68836. }
  68837. static DRFLAC_INLINE void drflac__vst2q_f32(float* p, float32x4x2_t x)
  68838. {
  68839. vst1q_f32(p+0, x.val[0]);
  68840. vst1q_f32(p+4, x.val[1]);
  68841. }
  68842. static DRFLAC_INLINE void drflac__vst2q_s16(drflac_int16* p, int16x4x2_t x)
  68843. {
  68844. vst1q_s16(p, vcombine_s16(x.val[0], x.val[1]));
  68845. }
  68846. static DRFLAC_INLINE void drflac__vst2q_u16(drflac_uint16* p, uint16x4x2_t x)
  68847. {
  68848. vst1q_u16(p, vcombine_u16(x.val[0], x.val[1]));
  68849. }
  68850. static DRFLAC_INLINE int32x4_t drflac__vdupq_n_s32x4(drflac_int32 x3, drflac_int32 x2, drflac_int32 x1, drflac_int32 x0)
  68851. {
  68852. drflac_int32 x[4];
  68853. x[3] = x3;
  68854. x[2] = x2;
  68855. x[1] = x1;
  68856. x[0] = x0;
  68857. return vld1q_s32(x);
  68858. }
  68859. static DRFLAC_INLINE int32x4_t drflac__valignrq_s32_1(int32x4_t a, int32x4_t b)
  68860. {
  68861. return vextq_s32(b, a, 1);
  68862. }
  68863. static DRFLAC_INLINE uint32x4_t drflac__valignrq_u32_1(uint32x4_t a, uint32x4_t b)
  68864. {
  68865. return vextq_u32(b, a, 1);
  68866. }
  68867. static DRFLAC_INLINE int32x2_t drflac__vhaddq_s32(int32x4_t x)
  68868. {
  68869. int32x2_t r = vadd_s32(vget_high_s32(x), vget_low_s32(x));
  68870. return vpadd_s32(r, r);
  68871. }
  68872. static DRFLAC_INLINE int64x1_t drflac__vhaddq_s64(int64x2_t x)
  68873. {
  68874. return vadd_s64(vget_high_s64(x), vget_low_s64(x));
  68875. }
  68876. static DRFLAC_INLINE int32x4_t drflac__vrevq_s32(int32x4_t x)
  68877. {
  68878. return vrev64q_s32(vcombine_s32(vget_high_s32(x), vget_low_s32(x)));
  68879. }
  68880. static DRFLAC_INLINE int32x4_t drflac__vnotq_s32(int32x4_t x)
  68881. {
  68882. return veorq_s32(x, vdupq_n_s32(0xFFFFFFFF));
  68883. }
  68884. static DRFLAC_INLINE uint32x4_t drflac__vnotq_u32(uint32x4_t x)
  68885. {
  68886. return veorq_u32(x, vdupq_n_u32(0xFFFFFFFF));
  68887. }
  68888. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_32(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  68889. {
  68890. int i;
  68891. drflac_uint32 riceParamMask;
  68892. drflac_int32* pDecodedSamples = pSamplesOut;
  68893. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  68894. drflac_uint32 zeroCountParts[4];
  68895. drflac_uint32 riceParamParts[4];
  68896. int32x4_t coefficients128_0;
  68897. int32x4_t coefficients128_4;
  68898. int32x4_t coefficients128_8;
  68899. int32x4_t samples128_0;
  68900. int32x4_t samples128_4;
  68901. int32x4_t samples128_8;
  68902. uint32x4_t riceParamMask128;
  68903. int32x4_t riceParam128;
  68904. int32x2_t shift64;
  68905. uint32x4_t one128;
  68906. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  68907. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  68908. riceParamMask128 = vdupq_n_u32(riceParamMask);
  68909. riceParam128 = vdupq_n_s32(riceParam);
  68910. shift64 = vdup_n_s32(-shift);
  68911. one128 = vdupq_n_u32(1);
  68912. {
  68913. int runningOrder = order;
  68914. drflac_int32 tempC[4] = {0, 0, 0, 0};
  68915. drflac_int32 tempS[4] = {0, 0, 0, 0};
  68916. if (runningOrder >= 4) {
  68917. coefficients128_0 = vld1q_s32(coefficients + 0);
  68918. samples128_0 = vld1q_s32(pSamplesOut - 4);
  68919. runningOrder -= 4;
  68920. } else {
  68921. switch (runningOrder) {
  68922. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  68923. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  68924. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  68925. }
  68926. coefficients128_0 = vld1q_s32(tempC);
  68927. samples128_0 = vld1q_s32(tempS);
  68928. runningOrder = 0;
  68929. }
  68930. if (runningOrder >= 4) {
  68931. coefficients128_4 = vld1q_s32(coefficients + 4);
  68932. samples128_4 = vld1q_s32(pSamplesOut - 8);
  68933. runningOrder -= 4;
  68934. } else {
  68935. switch (runningOrder) {
  68936. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  68937. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  68938. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  68939. }
  68940. coefficients128_4 = vld1q_s32(tempC);
  68941. samples128_4 = vld1q_s32(tempS);
  68942. runningOrder = 0;
  68943. }
  68944. if (runningOrder == 4) {
  68945. coefficients128_8 = vld1q_s32(coefficients + 8);
  68946. samples128_8 = vld1q_s32(pSamplesOut - 12);
  68947. runningOrder -= 4;
  68948. } else {
  68949. switch (runningOrder) {
  68950. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  68951. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  68952. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  68953. }
  68954. coefficients128_8 = vld1q_s32(tempC);
  68955. samples128_8 = vld1q_s32(tempS);
  68956. runningOrder = 0;
  68957. }
  68958. coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  68959. coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  68960. coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  68961. }
  68962. while (pDecodedSamples < pDecodedSamplesEnd) {
  68963. int32x4_t prediction128;
  68964. int32x2_t prediction64;
  68965. uint32x4_t zeroCountPart128;
  68966. uint32x4_t riceParamPart128;
  68967. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  68968. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  68969. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  68970. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  68971. return DRFLAC_FALSE;
  68972. }
  68973. zeroCountPart128 = vld1q_u32(zeroCountParts);
  68974. riceParamPart128 = vld1q_u32(riceParamParts);
  68975. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  68976. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  68977. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  68978. if (order <= 4) {
  68979. for (i = 0; i < 4; i += 1) {
  68980. prediction128 = vmulq_s32(coefficients128_0, samples128_0);
  68981. prediction64 = drflac__vhaddq_s32(prediction128);
  68982. prediction64 = vshl_s32(prediction64, shift64);
  68983. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  68984. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  68985. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  68986. }
  68987. } else if (order <= 8) {
  68988. for (i = 0; i < 4; i += 1) {
  68989. prediction128 = vmulq_s32(coefficients128_4, samples128_4);
  68990. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  68991. prediction64 = drflac__vhaddq_s32(prediction128);
  68992. prediction64 = vshl_s32(prediction64, shift64);
  68993. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  68994. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  68995. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  68996. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  68997. }
  68998. } else {
  68999. for (i = 0; i < 4; i += 1) {
  69000. prediction128 = vmulq_s32(coefficients128_8, samples128_8);
  69001. prediction128 = vmlaq_s32(prediction128, coefficients128_4, samples128_4);
  69002. prediction128 = vmlaq_s32(prediction128, coefficients128_0, samples128_0);
  69003. prediction64 = drflac__vhaddq_s32(prediction128);
  69004. prediction64 = vshl_s32(prediction64, shift64);
  69005. prediction64 = vadd_s32(prediction64, vget_low_s32(vreinterpretq_s32_u32(riceParamPart128)));
  69006. samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  69007. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  69008. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(prediction64, vdup_n_s32(0)), samples128_0);
  69009. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  69010. }
  69011. }
  69012. vst1q_s32(pDecodedSamples, samples128_0);
  69013. pDecodedSamples += 4;
  69014. }
  69015. i = (count & ~3);
  69016. while (i < (int)count) {
  69017. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  69018. return DRFLAC_FALSE;
  69019. }
  69020. riceParamParts[0] &= riceParamMask;
  69021. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  69022. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  69023. pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_32(order, shift, coefficients, pDecodedSamples);
  69024. i += 1;
  69025. pDecodedSamples += 1;
  69026. }
  69027. return DRFLAC_TRUE;
  69028. }
  69029. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon_64(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 order, drflac_int32 shift, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  69030. {
  69031. int i;
  69032. drflac_uint32 riceParamMask;
  69033. drflac_int32* pDecodedSamples = pSamplesOut;
  69034. drflac_int32* pDecodedSamplesEnd = pSamplesOut + (count & ~3);
  69035. drflac_uint32 zeroCountParts[4];
  69036. drflac_uint32 riceParamParts[4];
  69037. int32x4_t coefficients128_0;
  69038. int32x4_t coefficients128_4;
  69039. int32x4_t coefficients128_8;
  69040. int32x4_t samples128_0;
  69041. int32x4_t samples128_4;
  69042. int32x4_t samples128_8;
  69043. uint32x4_t riceParamMask128;
  69044. int32x4_t riceParam128;
  69045. int64x1_t shift64;
  69046. uint32x4_t one128;
  69047. int64x2_t prediction128 = { 0 };
  69048. uint32x4_t zeroCountPart128;
  69049. uint32x4_t riceParamPart128;
  69050. const drflac_uint32 t[2] = {0x00000000, 0xFFFFFFFF};
  69051. riceParamMask = (drflac_uint32)~((~0UL) << riceParam);
  69052. riceParamMask128 = vdupq_n_u32(riceParamMask);
  69053. riceParam128 = vdupq_n_s32(riceParam);
  69054. shift64 = vdup_n_s64(-shift);
  69055. one128 = vdupq_n_u32(1);
  69056. {
  69057. int runningOrder = order;
  69058. drflac_int32 tempC[4] = {0, 0, 0, 0};
  69059. drflac_int32 tempS[4] = {0, 0, 0, 0};
  69060. if (runningOrder >= 4) {
  69061. coefficients128_0 = vld1q_s32(coefficients + 0);
  69062. samples128_0 = vld1q_s32(pSamplesOut - 4);
  69063. runningOrder -= 4;
  69064. } else {
  69065. switch (runningOrder) {
  69066. case 3: tempC[2] = coefficients[2]; tempS[1] = pSamplesOut[-3];
  69067. case 2: tempC[1] = coefficients[1]; tempS[2] = pSamplesOut[-2];
  69068. case 1: tempC[0] = coefficients[0]; tempS[3] = pSamplesOut[-1];
  69069. }
  69070. coefficients128_0 = vld1q_s32(tempC);
  69071. samples128_0 = vld1q_s32(tempS);
  69072. runningOrder = 0;
  69073. }
  69074. if (runningOrder >= 4) {
  69075. coefficients128_4 = vld1q_s32(coefficients + 4);
  69076. samples128_4 = vld1q_s32(pSamplesOut - 8);
  69077. runningOrder -= 4;
  69078. } else {
  69079. switch (runningOrder) {
  69080. case 3: tempC[2] = coefficients[6]; tempS[1] = pSamplesOut[-7];
  69081. case 2: tempC[1] = coefficients[5]; tempS[2] = pSamplesOut[-6];
  69082. case 1: tempC[0] = coefficients[4]; tempS[3] = pSamplesOut[-5];
  69083. }
  69084. coefficients128_4 = vld1q_s32(tempC);
  69085. samples128_4 = vld1q_s32(tempS);
  69086. runningOrder = 0;
  69087. }
  69088. if (runningOrder == 4) {
  69089. coefficients128_8 = vld1q_s32(coefficients + 8);
  69090. samples128_8 = vld1q_s32(pSamplesOut - 12);
  69091. runningOrder -= 4;
  69092. } else {
  69093. switch (runningOrder) {
  69094. case 3: tempC[2] = coefficients[10]; tempS[1] = pSamplesOut[-11];
  69095. case 2: tempC[1] = coefficients[ 9]; tempS[2] = pSamplesOut[-10];
  69096. case 1: tempC[0] = coefficients[ 8]; tempS[3] = pSamplesOut[- 9];
  69097. }
  69098. coefficients128_8 = vld1q_s32(tempC);
  69099. samples128_8 = vld1q_s32(tempS);
  69100. runningOrder = 0;
  69101. }
  69102. coefficients128_0 = drflac__vrevq_s32(coefficients128_0);
  69103. coefficients128_4 = drflac__vrevq_s32(coefficients128_4);
  69104. coefficients128_8 = drflac__vrevq_s32(coefficients128_8);
  69105. }
  69106. while (pDecodedSamples < pDecodedSamplesEnd) {
  69107. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0]) ||
  69108. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[1], &riceParamParts[1]) ||
  69109. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[2], &riceParamParts[2]) ||
  69110. !drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[3], &riceParamParts[3])) {
  69111. return DRFLAC_FALSE;
  69112. }
  69113. zeroCountPart128 = vld1q_u32(zeroCountParts);
  69114. riceParamPart128 = vld1q_u32(riceParamParts);
  69115. riceParamPart128 = vandq_u32(riceParamPart128, riceParamMask128);
  69116. riceParamPart128 = vorrq_u32(riceParamPart128, vshlq_u32(zeroCountPart128, riceParam128));
  69117. riceParamPart128 = veorq_u32(vshrq_n_u32(riceParamPart128, 1), vaddq_u32(drflac__vnotq_u32(vandq_u32(riceParamPart128, one128)), one128));
  69118. for (i = 0; i < 4; i += 1) {
  69119. int64x1_t prediction64;
  69120. prediction128 = veorq_s64(prediction128, prediction128);
  69121. switch (order)
  69122. {
  69123. case 12:
  69124. case 11: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_8), vget_low_s32(samples128_8)));
  69125. case 10:
  69126. case 9: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_8), vget_high_s32(samples128_8)));
  69127. case 8:
  69128. case 7: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_4), vget_low_s32(samples128_4)));
  69129. case 6:
  69130. case 5: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_4), vget_high_s32(samples128_4)));
  69131. case 4:
  69132. case 3: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_low_s32(coefficients128_0), vget_low_s32(samples128_0)));
  69133. case 2:
  69134. case 1: prediction128 = vaddq_s64(prediction128, vmull_s32(vget_high_s32(coefficients128_0), vget_high_s32(samples128_0)));
  69135. }
  69136. prediction64 = drflac__vhaddq_s64(prediction128);
  69137. prediction64 = vshl_s64(prediction64, shift64);
  69138. prediction64 = vadd_s64(prediction64, vdup_n_s64(vgetq_lane_u32(riceParamPart128, 0)));
  69139. samples128_8 = drflac__valignrq_s32_1(samples128_4, samples128_8);
  69140. samples128_4 = drflac__valignrq_s32_1(samples128_0, samples128_4);
  69141. samples128_0 = drflac__valignrq_s32_1(vcombine_s32(vreinterpret_s32_s64(prediction64), vdup_n_s32(0)), samples128_0);
  69142. riceParamPart128 = drflac__valignrq_u32_1(vdupq_n_u32(0), riceParamPart128);
  69143. }
  69144. vst1q_s32(pDecodedSamples, samples128_0);
  69145. pDecodedSamples += 4;
  69146. }
  69147. i = (count & ~3);
  69148. while (i < (int)count) {
  69149. if (!drflac__read_rice_parts_x1(bs, riceParam, &zeroCountParts[0], &riceParamParts[0])) {
  69150. return DRFLAC_FALSE;
  69151. }
  69152. riceParamParts[0] &= riceParamMask;
  69153. riceParamParts[0] |= (zeroCountParts[0] << riceParam);
  69154. riceParamParts[0] = (riceParamParts[0] >> 1) ^ t[riceParamParts[0] & 0x01];
  69155. pDecodedSamples[0] = riceParamParts[0] + drflac__calculate_prediction_64(order, shift, coefficients, pDecodedSamples);
  69156. i += 1;
  69157. pDecodedSamples += 1;
  69158. }
  69159. return DRFLAC_TRUE;
  69160. }
  69161. static drflac_bool32 drflac__decode_samples_with_residual__rice__neon(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  69162. {
  69163. DRFLAC_ASSERT(bs != NULL);
  69164. DRFLAC_ASSERT(pSamplesOut != NULL);
  69165. if (lpcOrder > 0 && lpcOrder <= 12) {
  69166. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  69167. return drflac__decode_samples_with_residual__rice__neon_64(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  69168. } else {
  69169. return drflac__decode_samples_with_residual__rice__neon_32(bs, count, riceParam, lpcOrder, lpcShift, coefficients, pSamplesOut);
  69170. }
  69171. } else {
  69172. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  69173. }
  69174. }
  69175. #endif
  69176. static drflac_bool32 drflac__decode_samples_with_residual__rice(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 riceParam, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  69177. {
  69178. #if defined(DRFLAC_SUPPORT_SSE41)
  69179. if (drflac__gIsSSE41Supported) {
  69180. return drflac__decode_samples_with_residual__rice__sse41(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  69181. } else
  69182. #elif defined(DRFLAC_SUPPORT_NEON)
  69183. if (drflac__gIsNEONSupported) {
  69184. return drflac__decode_samples_with_residual__rice__neon(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  69185. } else
  69186. #endif
  69187. {
  69188. #if 0
  69189. return drflac__decode_samples_with_residual__rice__reference(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  69190. #else
  69191. return drflac__decode_samples_with_residual__rice__scalar(bs, bitsPerSample, count, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pSamplesOut);
  69192. #endif
  69193. }
  69194. }
  69195. static drflac_bool32 drflac__read_and_seek_residual__rice(drflac_bs* bs, drflac_uint32 count, drflac_uint8 riceParam)
  69196. {
  69197. drflac_uint32 i;
  69198. DRFLAC_ASSERT(bs != NULL);
  69199. for (i = 0; i < count; ++i) {
  69200. if (!drflac__seek_rice_parts(bs, riceParam)) {
  69201. return DRFLAC_FALSE;
  69202. }
  69203. }
  69204. return DRFLAC_TRUE;
  69205. }
  69206. #if defined(__clang__)
  69207. __attribute__((no_sanitize("signed-integer-overflow")))
  69208. #endif
  69209. static drflac_bool32 drflac__decode_samples_with_residual__unencoded(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 count, drflac_uint8 unencodedBitsPerSample, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pSamplesOut)
  69210. {
  69211. drflac_uint32 i;
  69212. DRFLAC_ASSERT(bs != NULL);
  69213. DRFLAC_ASSERT(unencodedBitsPerSample <= 31);
  69214. DRFLAC_ASSERT(pSamplesOut != NULL);
  69215. for (i = 0; i < count; ++i) {
  69216. if (unencodedBitsPerSample > 0) {
  69217. if (!drflac__read_int32(bs, unencodedBitsPerSample, pSamplesOut + i)) {
  69218. return DRFLAC_FALSE;
  69219. }
  69220. } else {
  69221. pSamplesOut[i] = 0;
  69222. }
  69223. if (drflac__use_64_bit_prediction(bitsPerSample, lpcOrder, lpcPrecision)) {
  69224. pSamplesOut[i] += drflac__calculate_prediction_64(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69225. } else {
  69226. pSamplesOut[i] += drflac__calculate_prediction_32(lpcOrder, lpcShift, coefficients, pSamplesOut + i);
  69227. }
  69228. }
  69229. return DRFLAC_TRUE;
  69230. }
  69231. static drflac_bool32 drflac__decode_samples_with_residual(drflac_bs* bs, drflac_uint32 bitsPerSample, drflac_uint32 blockSize, drflac_uint32 lpcOrder, drflac_int32 lpcShift, drflac_uint32 lpcPrecision, const drflac_int32* coefficients, drflac_int32* pDecodedSamples)
  69232. {
  69233. drflac_uint8 residualMethod;
  69234. drflac_uint8 partitionOrder;
  69235. drflac_uint32 samplesInPartition;
  69236. drflac_uint32 partitionsRemaining;
  69237. DRFLAC_ASSERT(bs != NULL);
  69238. DRFLAC_ASSERT(blockSize != 0);
  69239. DRFLAC_ASSERT(pDecodedSamples != NULL);
  69240. if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  69241. return DRFLAC_FALSE;
  69242. }
  69243. if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  69244. return DRFLAC_FALSE;
  69245. }
  69246. pDecodedSamples += lpcOrder;
  69247. if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  69248. return DRFLAC_FALSE;
  69249. }
  69250. if (partitionOrder > 8) {
  69251. return DRFLAC_FALSE;
  69252. }
  69253. if ((blockSize / (1 << partitionOrder)) < lpcOrder) {
  69254. return DRFLAC_FALSE;
  69255. }
  69256. samplesInPartition = (blockSize / (1 << partitionOrder)) - lpcOrder;
  69257. partitionsRemaining = (1 << partitionOrder);
  69258. for (;;) {
  69259. drflac_uint8 riceParam = 0;
  69260. if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  69261. if (!drflac__read_uint8(bs, 4, &riceParam)) {
  69262. return DRFLAC_FALSE;
  69263. }
  69264. if (riceParam == 15) {
  69265. riceParam = 0xFF;
  69266. }
  69267. } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  69268. if (!drflac__read_uint8(bs, 5, &riceParam)) {
  69269. return DRFLAC_FALSE;
  69270. }
  69271. if (riceParam == 31) {
  69272. riceParam = 0xFF;
  69273. }
  69274. }
  69275. if (riceParam != 0xFF) {
  69276. if (!drflac__decode_samples_with_residual__rice(bs, bitsPerSample, samplesInPartition, riceParam, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  69277. return DRFLAC_FALSE;
  69278. }
  69279. } else {
  69280. drflac_uint8 unencodedBitsPerSample = 0;
  69281. if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  69282. return DRFLAC_FALSE;
  69283. }
  69284. if (!drflac__decode_samples_with_residual__unencoded(bs, bitsPerSample, samplesInPartition, unencodedBitsPerSample, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  69285. return DRFLAC_FALSE;
  69286. }
  69287. }
  69288. pDecodedSamples += samplesInPartition;
  69289. if (partitionsRemaining == 1) {
  69290. break;
  69291. }
  69292. partitionsRemaining -= 1;
  69293. if (partitionOrder != 0) {
  69294. samplesInPartition = blockSize / (1 << partitionOrder);
  69295. }
  69296. }
  69297. return DRFLAC_TRUE;
  69298. }
  69299. static drflac_bool32 drflac__read_and_seek_residual(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 order)
  69300. {
  69301. drflac_uint8 residualMethod;
  69302. drflac_uint8 partitionOrder;
  69303. drflac_uint32 samplesInPartition;
  69304. drflac_uint32 partitionsRemaining;
  69305. DRFLAC_ASSERT(bs != NULL);
  69306. DRFLAC_ASSERT(blockSize != 0);
  69307. if (!drflac__read_uint8(bs, 2, &residualMethod)) {
  69308. return DRFLAC_FALSE;
  69309. }
  69310. if (residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE && residualMethod != DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  69311. return DRFLAC_FALSE;
  69312. }
  69313. if (!drflac__read_uint8(bs, 4, &partitionOrder)) {
  69314. return DRFLAC_FALSE;
  69315. }
  69316. if (partitionOrder > 8) {
  69317. return DRFLAC_FALSE;
  69318. }
  69319. if ((blockSize / (1 << partitionOrder)) <= order) {
  69320. return DRFLAC_FALSE;
  69321. }
  69322. samplesInPartition = (blockSize / (1 << partitionOrder)) - order;
  69323. partitionsRemaining = (1 << partitionOrder);
  69324. for (;;)
  69325. {
  69326. drflac_uint8 riceParam = 0;
  69327. if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE) {
  69328. if (!drflac__read_uint8(bs, 4, &riceParam)) {
  69329. return DRFLAC_FALSE;
  69330. }
  69331. if (riceParam == 15) {
  69332. riceParam = 0xFF;
  69333. }
  69334. } else if (residualMethod == DRFLAC_RESIDUAL_CODING_METHOD_PARTITIONED_RICE2) {
  69335. if (!drflac__read_uint8(bs, 5, &riceParam)) {
  69336. return DRFLAC_FALSE;
  69337. }
  69338. if (riceParam == 31) {
  69339. riceParam = 0xFF;
  69340. }
  69341. }
  69342. if (riceParam != 0xFF) {
  69343. if (!drflac__read_and_seek_residual__rice(bs, samplesInPartition, riceParam)) {
  69344. return DRFLAC_FALSE;
  69345. }
  69346. } else {
  69347. drflac_uint8 unencodedBitsPerSample = 0;
  69348. if (!drflac__read_uint8(bs, 5, &unencodedBitsPerSample)) {
  69349. return DRFLAC_FALSE;
  69350. }
  69351. if (!drflac__seek_bits(bs, unencodedBitsPerSample * samplesInPartition)) {
  69352. return DRFLAC_FALSE;
  69353. }
  69354. }
  69355. if (partitionsRemaining == 1) {
  69356. break;
  69357. }
  69358. partitionsRemaining -= 1;
  69359. samplesInPartition = blockSize / (1 << partitionOrder);
  69360. }
  69361. return DRFLAC_TRUE;
  69362. }
  69363. static drflac_bool32 drflac__decode_samples__constant(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  69364. {
  69365. drflac_uint32 i;
  69366. drflac_int32 sample;
  69367. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  69368. return DRFLAC_FALSE;
  69369. }
  69370. for (i = 0; i < blockSize; ++i) {
  69371. pDecodedSamples[i] = sample;
  69372. }
  69373. return DRFLAC_TRUE;
  69374. }
  69375. static drflac_bool32 drflac__decode_samples__verbatim(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_int32* pDecodedSamples)
  69376. {
  69377. drflac_uint32 i;
  69378. for (i = 0; i < blockSize; ++i) {
  69379. drflac_int32 sample;
  69380. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  69381. return DRFLAC_FALSE;
  69382. }
  69383. pDecodedSamples[i] = sample;
  69384. }
  69385. return DRFLAC_TRUE;
  69386. }
  69387. static drflac_bool32 drflac__decode_samples__fixed(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 subframeBitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  69388. {
  69389. drflac_uint32 i;
  69390. static drflac_int32 lpcCoefficientsTable[5][4] = {
  69391. {0, 0, 0, 0},
  69392. {1, 0, 0, 0},
  69393. {2, -1, 0, 0},
  69394. {3, -3, 1, 0},
  69395. {4, -6, 4, -1}
  69396. };
  69397. for (i = 0; i < lpcOrder; ++i) {
  69398. drflac_int32 sample;
  69399. if (!drflac__read_int32(bs, subframeBitsPerSample, &sample)) {
  69400. return DRFLAC_FALSE;
  69401. }
  69402. pDecodedSamples[i] = sample;
  69403. }
  69404. if (!drflac__decode_samples_with_residual(bs, subframeBitsPerSample, blockSize, lpcOrder, 0, 4, lpcCoefficientsTable[lpcOrder], pDecodedSamples)) {
  69405. return DRFLAC_FALSE;
  69406. }
  69407. return DRFLAC_TRUE;
  69408. }
  69409. static drflac_bool32 drflac__decode_samples__lpc(drflac_bs* bs, drflac_uint32 blockSize, drflac_uint32 bitsPerSample, drflac_uint8 lpcOrder, drflac_int32* pDecodedSamples)
  69410. {
  69411. drflac_uint8 i;
  69412. drflac_uint8 lpcPrecision;
  69413. drflac_int8 lpcShift;
  69414. drflac_int32 coefficients[32];
  69415. for (i = 0; i < lpcOrder; ++i) {
  69416. drflac_int32 sample;
  69417. if (!drflac__read_int32(bs, bitsPerSample, &sample)) {
  69418. return DRFLAC_FALSE;
  69419. }
  69420. pDecodedSamples[i] = sample;
  69421. }
  69422. if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  69423. return DRFLAC_FALSE;
  69424. }
  69425. if (lpcPrecision == 15) {
  69426. return DRFLAC_FALSE;
  69427. }
  69428. lpcPrecision += 1;
  69429. if (!drflac__read_int8(bs, 5, &lpcShift)) {
  69430. return DRFLAC_FALSE;
  69431. }
  69432. if (lpcShift < 0) {
  69433. return DRFLAC_FALSE;
  69434. }
  69435. DRFLAC_ZERO_MEMORY(coefficients, sizeof(coefficients));
  69436. for (i = 0; i < lpcOrder; ++i) {
  69437. if (!drflac__read_int32(bs, lpcPrecision, coefficients + i)) {
  69438. return DRFLAC_FALSE;
  69439. }
  69440. }
  69441. if (!drflac__decode_samples_with_residual(bs, bitsPerSample, blockSize, lpcOrder, lpcShift, lpcPrecision, coefficients, pDecodedSamples)) {
  69442. return DRFLAC_FALSE;
  69443. }
  69444. return DRFLAC_TRUE;
  69445. }
  69446. static drflac_bool32 drflac__read_next_flac_frame_header(drflac_bs* bs, drflac_uint8 streaminfoBitsPerSample, drflac_frame_header* header)
  69447. {
  69448. const drflac_uint32 sampleRateTable[12] = {0, 88200, 176400, 192000, 8000, 16000, 22050, 24000, 32000, 44100, 48000, 96000};
  69449. const drflac_uint8 bitsPerSampleTable[8] = {0, 8, 12, (drflac_uint8)-1, 16, 20, 24, (drflac_uint8)-1};
  69450. DRFLAC_ASSERT(bs != NULL);
  69451. DRFLAC_ASSERT(header != NULL);
  69452. for (;;) {
  69453. drflac_uint8 crc8 = 0xCE;
  69454. drflac_uint8 reserved = 0;
  69455. drflac_uint8 blockingStrategy = 0;
  69456. drflac_uint8 blockSize = 0;
  69457. drflac_uint8 sampleRate = 0;
  69458. drflac_uint8 channelAssignment = 0;
  69459. drflac_uint8 bitsPerSample = 0;
  69460. drflac_bool32 isVariableBlockSize;
  69461. if (!drflac__find_and_seek_to_next_sync_code(bs)) {
  69462. return DRFLAC_FALSE;
  69463. }
  69464. if (!drflac__read_uint8(bs, 1, &reserved)) {
  69465. return DRFLAC_FALSE;
  69466. }
  69467. if (reserved == 1) {
  69468. continue;
  69469. }
  69470. crc8 = drflac_crc8(crc8, reserved, 1);
  69471. if (!drflac__read_uint8(bs, 1, &blockingStrategy)) {
  69472. return DRFLAC_FALSE;
  69473. }
  69474. crc8 = drflac_crc8(crc8, blockingStrategy, 1);
  69475. if (!drflac__read_uint8(bs, 4, &blockSize)) {
  69476. return DRFLAC_FALSE;
  69477. }
  69478. if (blockSize == 0) {
  69479. continue;
  69480. }
  69481. crc8 = drflac_crc8(crc8, blockSize, 4);
  69482. if (!drflac__read_uint8(bs, 4, &sampleRate)) {
  69483. return DRFLAC_FALSE;
  69484. }
  69485. crc8 = drflac_crc8(crc8, sampleRate, 4);
  69486. if (!drflac__read_uint8(bs, 4, &channelAssignment)) {
  69487. return DRFLAC_FALSE;
  69488. }
  69489. if (channelAssignment > 10) {
  69490. continue;
  69491. }
  69492. crc8 = drflac_crc8(crc8, channelAssignment, 4);
  69493. if (!drflac__read_uint8(bs, 3, &bitsPerSample)) {
  69494. return DRFLAC_FALSE;
  69495. }
  69496. if (bitsPerSample == 3 || bitsPerSample == 7) {
  69497. continue;
  69498. }
  69499. crc8 = drflac_crc8(crc8, bitsPerSample, 3);
  69500. if (!drflac__read_uint8(bs, 1, &reserved)) {
  69501. return DRFLAC_FALSE;
  69502. }
  69503. if (reserved == 1) {
  69504. continue;
  69505. }
  69506. crc8 = drflac_crc8(crc8, reserved, 1);
  69507. isVariableBlockSize = blockingStrategy == 1;
  69508. if (isVariableBlockSize) {
  69509. drflac_uint64 pcmFrameNumber;
  69510. drflac_result result = drflac__read_utf8_coded_number(bs, &pcmFrameNumber, &crc8);
  69511. if (result != DRFLAC_SUCCESS) {
  69512. if (result == DRFLAC_AT_END) {
  69513. return DRFLAC_FALSE;
  69514. } else {
  69515. continue;
  69516. }
  69517. }
  69518. header->flacFrameNumber = 0;
  69519. header->pcmFrameNumber = pcmFrameNumber;
  69520. } else {
  69521. drflac_uint64 flacFrameNumber = 0;
  69522. drflac_result result = drflac__read_utf8_coded_number(bs, &flacFrameNumber, &crc8);
  69523. if (result != DRFLAC_SUCCESS) {
  69524. if (result == DRFLAC_AT_END) {
  69525. return DRFLAC_FALSE;
  69526. } else {
  69527. continue;
  69528. }
  69529. }
  69530. header->flacFrameNumber = (drflac_uint32)flacFrameNumber;
  69531. header->pcmFrameNumber = 0;
  69532. }
  69533. DRFLAC_ASSERT(blockSize > 0);
  69534. if (blockSize == 1) {
  69535. header->blockSizeInPCMFrames = 192;
  69536. } else if (blockSize <= 5) {
  69537. DRFLAC_ASSERT(blockSize >= 2);
  69538. header->blockSizeInPCMFrames = 576 * (1 << (blockSize - 2));
  69539. } else if (blockSize == 6) {
  69540. if (!drflac__read_uint16(bs, 8, &header->blockSizeInPCMFrames)) {
  69541. return DRFLAC_FALSE;
  69542. }
  69543. crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 8);
  69544. header->blockSizeInPCMFrames += 1;
  69545. } else if (blockSize == 7) {
  69546. if (!drflac__read_uint16(bs, 16, &header->blockSizeInPCMFrames)) {
  69547. return DRFLAC_FALSE;
  69548. }
  69549. crc8 = drflac_crc8(crc8, header->blockSizeInPCMFrames, 16);
  69550. if (header->blockSizeInPCMFrames == 0xFFFF) {
  69551. return DRFLAC_FALSE;
  69552. }
  69553. header->blockSizeInPCMFrames += 1;
  69554. } else {
  69555. DRFLAC_ASSERT(blockSize >= 8);
  69556. header->blockSizeInPCMFrames = 256 * (1 << (blockSize - 8));
  69557. }
  69558. if (sampleRate <= 11) {
  69559. header->sampleRate = sampleRateTable[sampleRate];
  69560. } else if (sampleRate == 12) {
  69561. if (!drflac__read_uint32(bs, 8, &header->sampleRate)) {
  69562. return DRFLAC_FALSE;
  69563. }
  69564. crc8 = drflac_crc8(crc8, header->sampleRate, 8);
  69565. header->sampleRate *= 1000;
  69566. } else if (sampleRate == 13) {
  69567. if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  69568. return DRFLAC_FALSE;
  69569. }
  69570. crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  69571. } else if (sampleRate == 14) {
  69572. if (!drflac__read_uint32(bs, 16, &header->sampleRate)) {
  69573. return DRFLAC_FALSE;
  69574. }
  69575. crc8 = drflac_crc8(crc8, header->sampleRate, 16);
  69576. header->sampleRate *= 10;
  69577. } else {
  69578. continue;
  69579. }
  69580. header->channelAssignment = channelAssignment;
  69581. header->bitsPerSample = bitsPerSampleTable[bitsPerSample];
  69582. if (header->bitsPerSample == 0) {
  69583. header->bitsPerSample = streaminfoBitsPerSample;
  69584. }
  69585. if (header->bitsPerSample != streaminfoBitsPerSample) {
  69586. return DRFLAC_FALSE;
  69587. }
  69588. if (!drflac__read_uint8(bs, 8, &header->crc8)) {
  69589. return DRFLAC_FALSE;
  69590. }
  69591. #ifndef DR_FLAC_NO_CRC
  69592. if (header->crc8 != crc8) {
  69593. continue;
  69594. }
  69595. #endif
  69596. return DRFLAC_TRUE;
  69597. }
  69598. }
  69599. static drflac_bool32 drflac__read_subframe_header(drflac_bs* bs, drflac_subframe* pSubframe)
  69600. {
  69601. drflac_uint8 header;
  69602. int type;
  69603. if (!drflac__read_uint8(bs, 8, &header)) {
  69604. return DRFLAC_FALSE;
  69605. }
  69606. if ((header & 0x80) != 0) {
  69607. return DRFLAC_FALSE;
  69608. }
  69609. type = (header & 0x7E) >> 1;
  69610. if (type == 0) {
  69611. pSubframe->subframeType = DRFLAC_SUBFRAME_CONSTANT;
  69612. } else if (type == 1) {
  69613. pSubframe->subframeType = DRFLAC_SUBFRAME_VERBATIM;
  69614. } else {
  69615. if ((type & 0x20) != 0) {
  69616. pSubframe->subframeType = DRFLAC_SUBFRAME_LPC;
  69617. pSubframe->lpcOrder = (drflac_uint8)(type & 0x1F) + 1;
  69618. } else if ((type & 0x08) != 0) {
  69619. pSubframe->subframeType = DRFLAC_SUBFRAME_FIXED;
  69620. pSubframe->lpcOrder = (drflac_uint8)(type & 0x07);
  69621. if (pSubframe->lpcOrder > 4) {
  69622. pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  69623. pSubframe->lpcOrder = 0;
  69624. }
  69625. } else {
  69626. pSubframe->subframeType = DRFLAC_SUBFRAME_RESERVED;
  69627. }
  69628. }
  69629. if (pSubframe->subframeType == DRFLAC_SUBFRAME_RESERVED) {
  69630. return DRFLAC_FALSE;
  69631. }
  69632. pSubframe->wastedBitsPerSample = 0;
  69633. if ((header & 0x01) == 1) {
  69634. unsigned int wastedBitsPerSample;
  69635. if (!drflac__seek_past_next_set_bit(bs, &wastedBitsPerSample)) {
  69636. return DRFLAC_FALSE;
  69637. }
  69638. pSubframe->wastedBitsPerSample = (drflac_uint8)wastedBitsPerSample + 1;
  69639. }
  69640. return DRFLAC_TRUE;
  69641. }
  69642. static drflac_bool32 drflac__decode_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex, drflac_int32* pDecodedSamplesOut)
  69643. {
  69644. drflac_subframe* pSubframe;
  69645. drflac_uint32 subframeBitsPerSample;
  69646. DRFLAC_ASSERT(bs != NULL);
  69647. DRFLAC_ASSERT(frame != NULL);
  69648. pSubframe = frame->subframes + subframeIndex;
  69649. if (!drflac__read_subframe_header(bs, pSubframe)) {
  69650. return DRFLAC_FALSE;
  69651. }
  69652. subframeBitsPerSample = frame->header.bitsPerSample;
  69653. if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  69654. subframeBitsPerSample += 1;
  69655. } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  69656. subframeBitsPerSample += 1;
  69657. }
  69658. if (subframeBitsPerSample > 32) {
  69659. return DRFLAC_FALSE;
  69660. }
  69661. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  69662. return DRFLAC_FALSE;
  69663. }
  69664. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  69665. pSubframe->pSamplesS32 = pDecodedSamplesOut;
  69666. switch (pSubframe->subframeType)
  69667. {
  69668. case DRFLAC_SUBFRAME_CONSTANT:
  69669. {
  69670. drflac__decode_samples__constant(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  69671. } break;
  69672. case DRFLAC_SUBFRAME_VERBATIM:
  69673. {
  69674. drflac__decode_samples__verbatim(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->pSamplesS32);
  69675. } break;
  69676. case DRFLAC_SUBFRAME_FIXED:
  69677. {
  69678. drflac__decode_samples__fixed(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  69679. } break;
  69680. case DRFLAC_SUBFRAME_LPC:
  69681. {
  69682. drflac__decode_samples__lpc(bs, frame->header.blockSizeInPCMFrames, subframeBitsPerSample, pSubframe->lpcOrder, pSubframe->pSamplesS32);
  69683. } break;
  69684. default: return DRFLAC_FALSE;
  69685. }
  69686. return DRFLAC_TRUE;
  69687. }
  69688. static drflac_bool32 drflac__seek_subframe(drflac_bs* bs, drflac_frame* frame, int subframeIndex)
  69689. {
  69690. drflac_subframe* pSubframe;
  69691. drflac_uint32 subframeBitsPerSample;
  69692. DRFLAC_ASSERT(bs != NULL);
  69693. DRFLAC_ASSERT(frame != NULL);
  69694. pSubframe = frame->subframes + subframeIndex;
  69695. if (!drflac__read_subframe_header(bs, pSubframe)) {
  69696. return DRFLAC_FALSE;
  69697. }
  69698. subframeBitsPerSample = frame->header.bitsPerSample;
  69699. if ((frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE || frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE) && subframeIndex == 1) {
  69700. subframeBitsPerSample += 1;
  69701. } else if (frame->header.channelAssignment == DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE && subframeIndex == 0) {
  69702. subframeBitsPerSample += 1;
  69703. }
  69704. if (pSubframe->wastedBitsPerSample >= subframeBitsPerSample) {
  69705. return DRFLAC_FALSE;
  69706. }
  69707. subframeBitsPerSample -= pSubframe->wastedBitsPerSample;
  69708. pSubframe->pSamplesS32 = NULL;
  69709. switch (pSubframe->subframeType)
  69710. {
  69711. case DRFLAC_SUBFRAME_CONSTANT:
  69712. {
  69713. if (!drflac__seek_bits(bs, subframeBitsPerSample)) {
  69714. return DRFLAC_FALSE;
  69715. }
  69716. } break;
  69717. case DRFLAC_SUBFRAME_VERBATIM:
  69718. {
  69719. unsigned int bitsToSeek = frame->header.blockSizeInPCMFrames * subframeBitsPerSample;
  69720. if (!drflac__seek_bits(bs, bitsToSeek)) {
  69721. return DRFLAC_FALSE;
  69722. }
  69723. } break;
  69724. case DRFLAC_SUBFRAME_FIXED:
  69725. {
  69726. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  69727. if (!drflac__seek_bits(bs, bitsToSeek)) {
  69728. return DRFLAC_FALSE;
  69729. }
  69730. if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  69731. return DRFLAC_FALSE;
  69732. }
  69733. } break;
  69734. case DRFLAC_SUBFRAME_LPC:
  69735. {
  69736. drflac_uint8 lpcPrecision;
  69737. unsigned int bitsToSeek = pSubframe->lpcOrder * subframeBitsPerSample;
  69738. if (!drflac__seek_bits(bs, bitsToSeek)) {
  69739. return DRFLAC_FALSE;
  69740. }
  69741. if (!drflac__read_uint8(bs, 4, &lpcPrecision)) {
  69742. return DRFLAC_FALSE;
  69743. }
  69744. if (lpcPrecision == 15) {
  69745. return DRFLAC_FALSE;
  69746. }
  69747. lpcPrecision += 1;
  69748. bitsToSeek = (pSubframe->lpcOrder * lpcPrecision) + 5;
  69749. if (!drflac__seek_bits(bs, bitsToSeek)) {
  69750. return DRFLAC_FALSE;
  69751. }
  69752. if (!drflac__read_and_seek_residual(bs, frame->header.blockSizeInPCMFrames, pSubframe->lpcOrder)) {
  69753. return DRFLAC_FALSE;
  69754. }
  69755. } break;
  69756. default: return DRFLAC_FALSE;
  69757. }
  69758. return DRFLAC_TRUE;
  69759. }
  69760. static DRFLAC_INLINE drflac_uint8 drflac__get_channel_count_from_channel_assignment(drflac_int8 channelAssignment)
  69761. {
  69762. drflac_uint8 lookup[] = {1, 2, 3, 4, 5, 6, 7, 8, 2, 2, 2};
  69763. DRFLAC_ASSERT(channelAssignment <= 10);
  69764. return lookup[channelAssignment];
  69765. }
  69766. static drflac_result drflac__decode_flac_frame(drflac* pFlac)
  69767. {
  69768. int channelCount;
  69769. int i;
  69770. drflac_uint8 paddingSizeInBits;
  69771. drflac_uint16 desiredCRC16;
  69772. #ifndef DR_FLAC_NO_CRC
  69773. drflac_uint16 actualCRC16;
  69774. #endif
  69775. DRFLAC_ZERO_MEMORY(pFlac->currentFLACFrame.subframes, sizeof(pFlac->currentFLACFrame.subframes));
  69776. if (pFlac->currentFLACFrame.header.blockSizeInPCMFrames > pFlac->maxBlockSizeInPCMFrames) {
  69777. return DRFLAC_ERROR;
  69778. }
  69779. channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  69780. if (channelCount != (int)pFlac->channels) {
  69781. return DRFLAC_ERROR;
  69782. }
  69783. for (i = 0; i < channelCount; ++i) {
  69784. if (!drflac__decode_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i, pFlac->pDecodedSamples + (pFlac->currentFLACFrame.header.blockSizeInPCMFrames * i))) {
  69785. return DRFLAC_ERROR;
  69786. }
  69787. }
  69788. paddingSizeInBits = (drflac_uint8)(DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7);
  69789. if (paddingSizeInBits > 0) {
  69790. drflac_uint8 padding = 0;
  69791. if (!drflac__read_uint8(&pFlac->bs, paddingSizeInBits, &padding)) {
  69792. return DRFLAC_AT_END;
  69793. }
  69794. }
  69795. #ifndef DR_FLAC_NO_CRC
  69796. actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  69797. #endif
  69798. if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  69799. return DRFLAC_AT_END;
  69800. }
  69801. #ifndef DR_FLAC_NO_CRC
  69802. if (actualCRC16 != desiredCRC16) {
  69803. return DRFLAC_CRC_MISMATCH;
  69804. }
  69805. #endif
  69806. pFlac->currentFLACFrame.pcmFramesRemaining = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  69807. return DRFLAC_SUCCESS;
  69808. }
  69809. static drflac_result drflac__seek_flac_frame(drflac* pFlac)
  69810. {
  69811. int channelCount;
  69812. int i;
  69813. drflac_uint16 desiredCRC16;
  69814. #ifndef DR_FLAC_NO_CRC
  69815. drflac_uint16 actualCRC16;
  69816. #endif
  69817. channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  69818. for (i = 0; i < channelCount; ++i) {
  69819. if (!drflac__seek_subframe(&pFlac->bs, &pFlac->currentFLACFrame, i)) {
  69820. return DRFLAC_ERROR;
  69821. }
  69822. }
  69823. if (!drflac__seek_bits(&pFlac->bs, DRFLAC_CACHE_L1_BITS_REMAINING(&pFlac->bs) & 7)) {
  69824. return DRFLAC_ERROR;
  69825. }
  69826. #ifndef DR_FLAC_NO_CRC
  69827. actualCRC16 = drflac__flush_crc16(&pFlac->bs);
  69828. #endif
  69829. if (!drflac__read_uint16(&pFlac->bs, 16, &desiredCRC16)) {
  69830. return DRFLAC_AT_END;
  69831. }
  69832. #ifndef DR_FLAC_NO_CRC
  69833. if (actualCRC16 != desiredCRC16) {
  69834. return DRFLAC_CRC_MISMATCH;
  69835. }
  69836. #endif
  69837. return DRFLAC_SUCCESS;
  69838. }
  69839. static drflac_bool32 drflac__read_and_decode_next_flac_frame(drflac* pFlac)
  69840. {
  69841. DRFLAC_ASSERT(pFlac != NULL);
  69842. for (;;) {
  69843. drflac_result result;
  69844. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  69845. return DRFLAC_FALSE;
  69846. }
  69847. result = drflac__decode_flac_frame(pFlac);
  69848. if (result != DRFLAC_SUCCESS) {
  69849. if (result == DRFLAC_CRC_MISMATCH) {
  69850. continue;
  69851. } else {
  69852. return DRFLAC_FALSE;
  69853. }
  69854. }
  69855. return DRFLAC_TRUE;
  69856. }
  69857. }
  69858. static void drflac__get_pcm_frame_range_of_current_flac_frame(drflac* pFlac, drflac_uint64* pFirstPCMFrame, drflac_uint64* pLastPCMFrame)
  69859. {
  69860. drflac_uint64 firstPCMFrame;
  69861. drflac_uint64 lastPCMFrame;
  69862. DRFLAC_ASSERT(pFlac != NULL);
  69863. firstPCMFrame = pFlac->currentFLACFrame.header.pcmFrameNumber;
  69864. if (firstPCMFrame == 0) {
  69865. firstPCMFrame = ((drflac_uint64)pFlac->currentFLACFrame.header.flacFrameNumber) * pFlac->maxBlockSizeInPCMFrames;
  69866. }
  69867. lastPCMFrame = firstPCMFrame + pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  69868. if (lastPCMFrame > 0) {
  69869. lastPCMFrame -= 1;
  69870. }
  69871. if (pFirstPCMFrame) {
  69872. *pFirstPCMFrame = firstPCMFrame;
  69873. }
  69874. if (pLastPCMFrame) {
  69875. *pLastPCMFrame = lastPCMFrame;
  69876. }
  69877. }
  69878. static drflac_bool32 drflac__seek_to_first_frame(drflac* pFlac)
  69879. {
  69880. drflac_bool32 result;
  69881. DRFLAC_ASSERT(pFlac != NULL);
  69882. result = drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes);
  69883. DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  69884. pFlac->currentPCMFrame = 0;
  69885. return result;
  69886. }
  69887. static DRFLAC_INLINE drflac_result drflac__seek_to_next_flac_frame(drflac* pFlac)
  69888. {
  69889. DRFLAC_ASSERT(pFlac != NULL);
  69890. return drflac__seek_flac_frame(pFlac);
  69891. }
  69892. static drflac_uint64 drflac__seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 pcmFramesToSeek)
  69893. {
  69894. drflac_uint64 pcmFramesRead = 0;
  69895. while (pcmFramesToSeek > 0) {
  69896. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  69897. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  69898. break;
  69899. }
  69900. } else {
  69901. if (pFlac->currentFLACFrame.pcmFramesRemaining > pcmFramesToSeek) {
  69902. pcmFramesRead += pcmFramesToSeek;
  69903. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)pcmFramesToSeek;
  69904. pcmFramesToSeek = 0;
  69905. } else {
  69906. pcmFramesRead += pFlac->currentFLACFrame.pcmFramesRemaining;
  69907. pcmFramesToSeek -= pFlac->currentFLACFrame.pcmFramesRemaining;
  69908. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  69909. }
  69910. }
  69911. }
  69912. pFlac->currentPCMFrame += pcmFramesRead;
  69913. return pcmFramesRead;
  69914. }
  69915. static drflac_bool32 drflac__seek_to_pcm_frame__brute_force(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  69916. {
  69917. drflac_bool32 isMidFrame = DRFLAC_FALSE;
  69918. drflac_uint64 runningPCMFrameCount;
  69919. DRFLAC_ASSERT(pFlac != NULL);
  69920. if (pcmFrameIndex >= pFlac->currentPCMFrame) {
  69921. runningPCMFrameCount = pFlac->currentPCMFrame;
  69922. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  69923. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  69924. return DRFLAC_FALSE;
  69925. }
  69926. } else {
  69927. isMidFrame = DRFLAC_TRUE;
  69928. }
  69929. } else {
  69930. runningPCMFrameCount = 0;
  69931. if (!drflac__seek_to_first_frame(pFlac)) {
  69932. return DRFLAC_FALSE;
  69933. }
  69934. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  69935. return DRFLAC_FALSE;
  69936. }
  69937. }
  69938. for (;;) {
  69939. drflac_uint64 pcmFrameCountInThisFLACFrame;
  69940. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  69941. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  69942. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  69943. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  69944. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  69945. drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  69946. if (!isMidFrame) {
  69947. drflac_result result = drflac__decode_flac_frame(pFlac);
  69948. if (result == DRFLAC_SUCCESS) {
  69949. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  69950. } else {
  69951. if (result == DRFLAC_CRC_MISMATCH) {
  69952. goto next_iteration;
  69953. } else {
  69954. return DRFLAC_FALSE;
  69955. }
  69956. }
  69957. } else {
  69958. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  69959. }
  69960. } else {
  69961. if (!isMidFrame) {
  69962. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  69963. if (result == DRFLAC_SUCCESS) {
  69964. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  69965. } else {
  69966. if (result == DRFLAC_CRC_MISMATCH) {
  69967. goto next_iteration;
  69968. } else {
  69969. return DRFLAC_FALSE;
  69970. }
  69971. }
  69972. } else {
  69973. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  69974. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  69975. isMidFrame = DRFLAC_FALSE;
  69976. }
  69977. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  69978. return DRFLAC_TRUE;
  69979. }
  69980. }
  69981. next_iteration:
  69982. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  69983. return DRFLAC_FALSE;
  69984. }
  69985. }
  69986. }
  69987. #if !defined(DR_FLAC_NO_CRC)
  69988. #define DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO 0.6f
  69989. static drflac_bool32 drflac__seek_to_approximate_flac_frame_to_byte(drflac* pFlac, drflac_uint64 targetByte, drflac_uint64 rangeLo, drflac_uint64 rangeHi, drflac_uint64* pLastSuccessfulSeekOffset)
  69990. {
  69991. DRFLAC_ASSERT(pFlac != NULL);
  69992. DRFLAC_ASSERT(pLastSuccessfulSeekOffset != NULL);
  69993. DRFLAC_ASSERT(targetByte >= rangeLo);
  69994. DRFLAC_ASSERT(targetByte <= rangeHi);
  69995. *pLastSuccessfulSeekOffset = pFlac->firstFLACFramePosInBytes;
  69996. for (;;) {
  69997. drflac_uint64 lastTargetByte = targetByte;
  69998. if (!drflac__seek_to_byte(&pFlac->bs, targetByte)) {
  69999. if (targetByte == 0) {
  70000. drflac__seek_to_first_frame(pFlac);
  70001. return DRFLAC_FALSE;
  70002. }
  70003. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  70004. rangeHi = targetByte;
  70005. } else {
  70006. DRFLAC_ZERO_MEMORY(&pFlac->currentFLACFrame, sizeof(pFlac->currentFLACFrame));
  70007. #if 1
  70008. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  70009. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  70010. rangeHi = targetByte;
  70011. } else {
  70012. break;
  70013. }
  70014. #else
  70015. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  70016. targetByte = rangeLo + ((rangeHi - rangeLo)/2);
  70017. rangeHi = targetByte;
  70018. } else {
  70019. break;
  70020. }
  70021. #endif
  70022. }
  70023. if(targetByte == lastTargetByte) {
  70024. return DRFLAC_FALSE;
  70025. }
  70026. }
  70027. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  70028. DRFLAC_ASSERT(targetByte <= rangeHi);
  70029. *pLastSuccessfulSeekOffset = targetByte;
  70030. return DRFLAC_TRUE;
  70031. }
  70032. static drflac_bool32 drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(drflac* pFlac, drflac_uint64 offset)
  70033. {
  70034. #if 0
  70035. if (drflac__decode_flac_frame(pFlac) != DRFLAC_SUCCESS) {
  70036. if (drflac__read_and_decode_next_flac_frame(pFlac) == DRFLAC_FALSE) {
  70037. return DRFLAC_FALSE;
  70038. }
  70039. }
  70040. #endif
  70041. return drflac__seek_forward_by_pcm_frames(pFlac, offset) == offset;
  70042. }
  70043. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search_internal(drflac* pFlac, drflac_uint64 pcmFrameIndex, drflac_uint64 byteRangeLo, drflac_uint64 byteRangeHi)
  70044. {
  70045. drflac_uint64 targetByte;
  70046. drflac_uint64 pcmRangeLo = pFlac->totalPCMFrameCount;
  70047. drflac_uint64 pcmRangeHi = 0;
  70048. drflac_uint64 lastSuccessfulSeekOffset = (drflac_uint64)-1;
  70049. drflac_uint64 closestSeekOffsetBeforeTargetPCMFrame = byteRangeLo;
  70050. drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  70051. targetByte = byteRangeLo + (drflac_uint64)(((drflac_int64)((pcmFrameIndex - pFlac->currentPCMFrame) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * DRFLAC_BINARY_SEARCH_APPROX_COMPRESSION_RATIO);
  70052. if (targetByte > byteRangeHi) {
  70053. targetByte = byteRangeHi;
  70054. }
  70055. for (;;) {
  70056. if (drflac__seek_to_approximate_flac_frame_to_byte(pFlac, targetByte, byteRangeLo, byteRangeHi, &lastSuccessfulSeekOffset)) {
  70057. drflac_uint64 newPCMRangeLo;
  70058. drflac_uint64 newPCMRangeHi;
  70059. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &newPCMRangeLo, &newPCMRangeHi);
  70060. if (pcmRangeLo == newPCMRangeLo) {
  70061. if (!drflac__seek_to_approximate_flac_frame_to_byte(pFlac, closestSeekOffsetBeforeTargetPCMFrame, closestSeekOffsetBeforeTargetPCMFrame, byteRangeHi, &lastSuccessfulSeekOffset)) {
  70062. break;
  70063. }
  70064. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  70065. return DRFLAC_TRUE;
  70066. } else {
  70067. break;
  70068. }
  70069. }
  70070. pcmRangeLo = newPCMRangeLo;
  70071. pcmRangeHi = newPCMRangeHi;
  70072. if (pcmRangeLo <= pcmFrameIndex && pcmRangeHi >= pcmFrameIndex) {
  70073. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame) ) {
  70074. return DRFLAC_TRUE;
  70075. } else {
  70076. break;
  70077. }
  70078. } else {
  70079. const float approxCompressionRatio = (drflac_int64)(lastSuccessfulSeekOffset - pFlac->firstFLACFramePosInBytes) / ((drflac_int64)(pcmRangeLo * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  70080. if (pcmRangeLo > pcmFrameIndex) {
  70081. byteRangeHi = lastSuccessfulSeekOffset;
  70082. if (byteRangeLo > byteRangeHi) {
  70083. byteRangeLo = byteRangeHi;
  70084. }
  70085. targetByte = byteRangeLo + ((byteRangeHi - byteRangeLo) / 2);
  70086. if (targetByte < byteRangeLo) {
  70087. targetByte = byteRangeLo;
  70088. }
  70089. } else {
  70090. if ((pcmFrameIndex - pcmRangeLo) < seekForwardThreshold) {
  70091. if (drflac__decode_flac_frame_and_seek_forward_by_pcm_frames(pFlac, pcmFrameIndex - pFlac->currentPCMFrame)) {
  70092. return DRFLAC_TRUE;
  70093. } else {
  70094. break;
  70095. }
  70096. } else {
  70097. byteRangeLo = lastSuccessfulSeekOffset;
  70098. if (byteRangeHi < byteRangeLo) {
  70099. byteRangeHi = byteRangeLo;
  70100. }
  70101. targetByte = lastSuccessfulSeekOffset + (drflac_uint64)(((drflac_int64)((pcmFrameIndex-pcmRangeLo) * pFlac->channels * pFlac->bitsPerSample)/8.0f) * approxCompressionRatio);
  70102. if (targetByte > byteRangeHi) {
  70103. targetByte = byteRangeHi;
  70104. }
  70105. if (closestSeekOffsetBeforeTargetPCMFrame < lastSuccessfulSeekOffset) {
  70106. closestSeekOffsetBeforeTargetPCMFrame = lastSuccessfulSeekOffset;
  70107. }
  70108. }
  70109. }
  70110. }
  70111. } else {
  70112. break;
  70113. }
  70114. }
  70115. drflac__seek_to_first_frame(pFlac);
  70116. return DRFLAC_FALSE;
  70117. }
  70118. static drflac_bool32 drflac__seek_to_pcm_frame__binary_search(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  70119. {
  70120. drflac_uint64 byteRangeLo;
  70121. drflac_uint64 byteRangeHi;
  70122. drflac_uint32 seekForwardThreshold = (pFlac->maxBlockSizeInPCMFrames != 0) ? pFlac->maxBlockSizeInPCMFrames*2 : 4096;
  70123. if (drflac__seek_to_first_frame(pFlac) == DRFLAC_FALSE) {
  70124. return DRFLAC_FALSE;
  70125. }
  70126. if (pcmFrameIndex < seekForwardThreshold) {
  70127. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFrameIndex) == pcmFrameIndex;
  70128. }
  70129. byteRangeLo = pFlac->firstFLACFramePosInBytes;
  70130. byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  70131. return drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi);
  70132. }
  70133. #endif
  70134. static drflac_bool32 drflac__seek_to_pcm_frame__seek_table(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  70135. {
  70136. drflac_uint32 iClosestSeekpoint = 0;
  70137. drflac_bool32 isMidFrame = DRFLAC_FALSE;
  70138. drflac_uint64 runningPCMFrameCount;
  70139. drflac_uint32 iSeekpoint;
  70140. DRFLAC_ASSERT(pFlac != NULL);
  70141. if (pFlac->pSeekpoints == NULL || pFlac->seekpointCount == 0) {
  70142. return DRFLAC_FALSE;
  70143. }
  70144. if (pFlac->pSeekpoints[0].firstPCMFrame > pcmFrameIndex) {
  70145. return DRFLAC_FALSE;
  70146. }
  70147. for (iSeekpoint = 0; iSeekpoint < pFlac->seekpointCount; ++iSeekpoint) {
  70148. if (pFlac->pSeekpoints[iSeekpoint].firstPCMFrame >= pcmFrameIndex) {
  70149. break;
  70150. }
  70151. iClosestSeekpoint = iSeekpoint;
  70152. }
  70153. if (pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount == 0 || pFlac->pSeekpoints[iClosestSeekpoint].pcmFrameCount > pFlac->maxBlockSizeInPCMFrames) {
  70154. return DRFLAC_FALSE;
  70155. }
  70156. if (pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame > pFlac->totalPCMFrameCount && pFlac->totalPCMFrameCount > 0) {
  70157. return DRFLAC_FALSE;
  70158. }
  70159. #if !defined(DR_FLAC_NO_CRC)
  70160. if (pFlac->totalPCMFrameCount > 0) {
  70161. drflac_uint64 byteRangeLo;
  70162. drflac_uint64 byteRangeHi;
  70163. byteRangeHi = pFlac->firstFLACFramePosInBytes + (drflac_uint64)((drflac_int64)(pFlac->totalPCMFrameCount * pFlac->channels * pFlac->bitsPerSample)/8.0f);
  70164. byteRangeLo = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset;
  70165. if (iClosestSeekpoint < pFlac->seekpointCount-1) {
  70166. drflac_uint32 iNextSeekpoint = iClosestSeekpoint + 1;
  70167. if (pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset >= pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset || pFlac->pSeekpoints[iNextSeekpoint].pcmFrameCount == 0) {
  70168. return DRFLAC_FALSE;
  70169. }
  70170. if (pFlac->pSeekpoints[iNextSeekpoint].firstPCMFrame != (((drflac_uint64)0xFFFFFFFF << 32) | 0xFFFFFFFF)) {
  70171. byteRangeHi = pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iNextSeekpoint].flacFrameOffset - 1;
  70172. }
  70173. }
  70174. if (drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  70175. if (drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  70176. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &pFlac->currentPCMFrame, NULL);
  70177. if (drflac__seek_to_pcm_frame__binary_search_internal(pFlac, pcmFrameIndex, byteRangeLo, byteRangeHi)) {
  70178. return DRFLAC_TRUE;
  70179. }
  70180. }
  70181. }
  70182. }
  70183. #endif
  70184. if (pcmFrameIndex >= pFlac->currentPCMFrame && pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame <= pFlac->currentPCMFrame) {
  70185. runningPCMFrameCount = pFlac->currentPCMFrame;
  70186. if (pFlac->currentPCMFrame == 0 && pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  70187. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  70188. return DRFLAC_FALSE;
  70189. }
  70190. } else {
  70191. isMidFrame = DRFLAC_TRUE;
  70192. }
  70193. } else {
  70194. runningPCMFrameCount = pFlac->pSeekpoints[iClosestSeekpoint].firstPCMFrame;
  70195. if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes + pFlac->pSeekpoints[iClosestSeekpoint].flacFrameOffset)) {
  70196. return DRFLAC_FALSE;
  70197. }
  70198. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  70199. return DRFLAC_FALSE;
  70200. }
  70201. }
  70202. for (;;) {
  70203. drflac_uint64 pcmFrameCountInThisFLACFrame;
  70204. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  70205. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  70206. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  70207. pcmFrameCountInThisFLACFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  70208. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFLACFrame)) {
  70209. drflac_uint64 pcmFramesToDecode = pcmFrameIndex - runningPCMFrameCount;
  70210. if (!isMidFrame) {
  70211. drflac_result result = drflac__decode_flac_frame(pFlac);
  70212. if (result == DRFLAC_SUCCESS) {
  70213. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  70214. } else {
  70215. if (result == DRFLAC_CRC_MISMATCH) {
  70216. goto next_iteration;
  70217. } else {
  70218. return DRFLAC_FALSE;
  70219. }
  70220. }
  70221. } else {
  70222. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  70223. }
  70224. } else {
  70225. if (!isMidFrame) {
  70226. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  70227. if (result == DRFLAC_SUCCESS) {
  70228. runningPCMFrameCount += pcmFrameCountInThisFLACFrame;
  70229. } else {
  70230. if (result == DRFLAC_CRC_MISMATCH) {
  70231. goto next_iteration;
  70232. } else {
  70233. return DRFLAC_FALSE;
  70234. }
  70235. }
  70236. } else {
  70237. runningPCMFrameCount += pFlac->currentFLACFrame.pcmFramesRemaining;
  70238. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  70239. isMidFrame = DRFLAC_FALSE;
  70240. }
  70241. if (pcmFrameIndex == pFlac->totalPCMFrameCount && runningPCMFrameCount == pFlac->totalPCMFrameCount) {
  70242. return DRFLAC_TRUE;
  70243. }
  70244. }
  70245. next_iteration:
  70246. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  70247. return DRFLAC_FALSE;
  70248. }
  70249. }
  70250. }
  70251. #ifndef DR_FLAC_NO_OGG
  70252. typedef struct
  70253. {
  70254. drflac_uint8 capturePattern[4];
  70255. drflac_uint8 structureVersion;
  70256. drflac_uint8 headerType;
  70257. drflac_uint64 granulePosition;
  70258. drflac_uint32 serialNumber;
  70259. drflac_uint32 sequenceNumber;
  70260. drflac_uint32 checksum;
  70261. drflac_uint8 segmentCount;
  70262. drflac_uint8 segmentTable[255];
  70263. } drflac_ogg_page_header;
  70264. #endif
  70265. typedef struct
  70266. {
  70267. drflac_read_proc onRead;
  70268. drflac_seek_proc onSeek;
  70269. drflac_meta_proc onMeta;
  70270. drflac_container container;
  70271. void* pUserData;
  70272. void* pUserDataMD;
  70273. drflac_uint32 sampleRate;
  70274. drflac_uint8 channels;
  70275. drflac_uint8 bitsPerSample;
  70276. drflac_uint64 totalPCMFrameCount;
  70277. drflac_uint16 maxBlockSizeInPCMFrames;
  70278. drflac_uint64 runningFilePos;
  70279. drflac_bool32 hasStreamInfoBlock;
  70280. drflac_bool32 hasMetadataBlocks;
  70281. drflac_bs bs;
  70282. drflac_frame_header firstFrameHeader;
  70283. #ifndef DR_FLAC_NO_OGG
  70284. drflac_uint32 oggSerial;
  70285. drflac_uint64 oggFirstBytePos;
  70286. drflac_ogg_page_header oggBosHeader;
  70287. #endif
  70288. } drflac_init_info;
  70289. static DRFLAC_INLINE void drflac__decode_block_header(drflac_uint32 blockHeader, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
  70290. {
  70291. blockHeader = drflac__be2host_32(blockHeader);
  70292. *isLastBlock = (drflac_uint8)((blockHeader & 0x80000000UL) >> 31);
  70293. *blockType = (drflac_uint8)((blockHeader & 0x7F000000UL) >> 24);
  70294. *blockSize = (blockHeader & 0x00FFFFFFUL);
  70295. }
  70296. static DRFLAC_INLINE drflac_bool32 drflac__read_and_decode_block_header(drflac_read_proc onRead, void* pUserData, drflac_uint8* isLastBlock, drflac_uint8* blockType, drflac_uint32* blockSize)
  70297. {
  70298. drflac_uint32 blockHeader;
  70299. *blockSize = 0;
  70300. if (onRead(pUserData, &blockHeader, 4) != 4) {
  70301. return DRFLAC_FALSE;
  70302. }
  70303. drflac__decode_block_header(blockHeader, isLastBlock, blockType, blockSize);
  70304. return DRFLAC_TRUE;
  70305. }
  70306. static drflac_bool32 drflac__read_streaminfo(drflac_read_proc onRead, void* pUserData, drflac_streaminfo* pStreamInfo)
  70307. {
  70308. drflac_uint32 blockSizes;
  70309. drflac_uint64 frameSizes = 0;
  70310. drflac_uint64 importantProps;
  70311. drflac_uint8 md5[16];
  70312. if (onRead(pUserData, &blockSizes, 4) != 4) {
  70313. return DRFLAC_FALSE;
  70314. }
  70315. if (onRead(pUserData, &frameSizes, 6) != 6) {
  70316. return DRFLAC_FALSE;
  70317. }
  70318. if (onRead(pUserData, &importantProps, 8) != 8) {
  70319. return DRFLAC_FALSE;
  70320. }
  70321. if (onRead(pUserData, md5, sizeof(md5)) != sizeof(md5)) {
  70322. return DRFLAC_FALSE;
  70323. }
  70324. blockSizes = drflac__be2host_32(blockSizes);
  70325. frameSizes = drflac__be2host_64(frameSizes);
  70326. importantProps = drflac__be2host_64(importantProps);
  70327. pStreamInfo->minBlockSizeInPCMFrames = (drflac_uint16)((blockSizes & 0xFFFF0000) >> 16);
  70328. pStreamInfo->maxBlockSizeInPCMFrames = (drflac_uint16) (blockSizes & 0x0000FFFF);
  70329. pStreamInfo->minFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 24)) >> 40);
  70330. pStreamInfo->maxFrameSizeInPCMFrames = (drflac_uint32)((frameSizes & (((drflac_uint64)0x00FFFFFF << 16) << 0)) >> 16);
  70331. pStreamInfo->sampleRate = (drflac_uint32)((importantProps & (((drflac_uint64)0x000FFFFF << 16) << 28)) >> 44);
  70332. pStreamInfo->channels = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000000E << 16) << 24)) >> 41) + 1;
  70333. pStreamInfo->bitsPerSample = (drflac_uint8 )((importantProps & (((drflac_uint64)0x0000001F << 16) << 20)) >> 36) + 1;
  70334. pStreamInfo->totalPCMFrameCount = ((importantProps & ((((drflac_uint64)0x0000000F << 16) << 16) | 0xFFFFFFFF)));
  70335. DRFLAC_COPY_MEMORY(pStreamInfo->md5, md5, sizeof(md5));
  70336. return DRFLAC_TRUE;
  70337. }
  70338. static void* drflac__malloc_default(size_t sz, void* pUserData)
  70339. {
  70340. (void)pUserData;
  70341. return DRFLAC_MALLOC(sz);
  70342. }
  70343. static void* drflac__realloc_default(void* p, size_t sz, void* pUserData)
  70344. {
  70345. (void)pUserData;
  70346. return DRFLAC_REALLOC(p, sz);
  70347. }
  70348. static void drflac__free_default(void* p, void* pUserData)
  70349. {
  70350. (void)pUserData;
  70351. DRFLAC_FREE(p);
  70352. }
  70353. static void* drflac__malloc_from_callbacks(size_t sz, const drflac_allocation_callbacks* pAllocationCallbacks)
  70354. {
  70355. if (pAllocationCallbacks == NULL) {
  70356. return NULL;
  70357. }
  70358. if (pAllocationCallbacks->onMalloc != NULL) {
  70359. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  70360. }
  70361. if (pAllocationCallbacks->onRealloc != NULL) {
  70362. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  70363. }
  70364. return NULL;
  70365. }
  70366. static void* drflac__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drflac_allocation_callbacks* pAllocationCallbacks)
  70367. {
  70368. if (pAllocationCallbacks == NULL) {
  70369. return NULL;
  70370. }
  70371. if (pAllocationCallbacks->onRealloc != NULL) {
  70372. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  70373. }
  70374. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  70375. void* p2;
  70376. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  70377. if (p2 == NULL) {
  70378. return NULL;
  70379. }
  70380. if (p != NULL) {
  70381. DRFLAC_COPY_MEMORY(p2, p, szOld);
  70382. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  70383. }
  70384. return p2;
  70385. }
  70386. return NULL;
  70387. }
  70388. static void drflac__free_from_callbacks(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  70389. {
  70390. if (p == NULL || pAllocationCallbacks == NULL) {
  70391. return;
  70392. }
  70393. if (pAllocationCallbacks->onFree != NULL) {
  70394. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  70395. }
  70396. }
  70397. static drflac_bool32 drflac__read_and_decode_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_uint64* pFirstFramePos, drflac_uint64* pSeektablePos, drflac_uint32* pSeekpointCount, drflac_allocation_callbacks* pAllocationCallbacks)
  70398. {
  70399. drflac_uint64 runningFilePos = 42;
  70400. drflac_uint64 seektablePos = 0;
  70401. drflac_uint32 seektableSize = 0;
  70402. for (;;) {
  70403. drflac_metadata metadata;
  70404. drflac_uint8 isLastBlock = 0;
  70405. drflac_uint8 blockType;
  70406. drflac_uint32 blockSize;
  70407. if (drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize) == DRFLAC_FALSE) {
  70408. return DRFLAC_FALSE;
  70409. }
  70410. runningFilePos += 4;
  70411. metadata.type = blockType;
  70412. metadata.pRawData = NULL;
  70413. metadata.rawDataSize = 0;
  70414. switch (blockType)
  70415. {
  70416. case DRFLAC_METADATA_BLOCK_TYPE_APPLICATION:
  70417. {
  70418. if (blockSize < 4) {
  70419. return DRFLAC_FALSE;
  70420. }
  70421. if (onMeta) {
  70422. void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  70423. if (pRawData == NULL) {
  70424. return DRFLAC_FALSE;
  70425. }
  70426. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  70427. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70428. return DRFLAC_FALSE;
  70429. }
  70430. metadata.pRawData = pRawData;
  70431. metadata.rawDataSize = blockSize;
  70432. metadata.data.application.id = drflac__be2host_32(*(drflac_uint32*)pRawData);
  70433. metadata.data.application.pData = (const void*)((drflac_uint8*)pRawData + sizeof(drflac_uint32));
  70434. metadata.data.application.dataSize = blockSize - sizeof(drflac_uint32);
  70435. onMeta(pUserDataMD, &metadata);
  70436. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70437. }
  70438. } break;
  70439. case DRFLAC_METADATA_BLOCK_TYPE_SEEKTABLE:
  70440. {
  70441. seektablePos = runningFilePos;
  70442. seektableSize = blockSize;
  70443. if (onMeta) {
  70444. drflac_uint32 seekpointCount;
  70445. drflac_uint32 iSeekpoint;
  70446. void* pRawData;
  70447. seekpointCount = blockSize/DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
  70448. pRawData = drflac__malloc_from_callbacks(seekpointCount * sizeof(drflac_seekpoint), pAllocationCallbacks);
  70449. if (pRawData == NULL) {
  70450. return DRFLAC_FALSE;
  70451. }
  70452. for (iSeekpoint = 0; iSeekpoint < seekpointCount; ++iSeekpoint) {
  70453. drflac_seekpoint* pSeekpoint = (drflac_seekpoint*)pRawData + iSeekpoint;
  70454. if (onRead(pUserData, pSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) != DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
  70455. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70456. return DRFLAC_FALSE;
  70457. }
  70458. pSeekpoint->firstPCMFrame = drflac__be2host_64(pSeekpoint->firstPCMFrame);
  70459. pSeekpoint->flacFrameOffset = drflac__be2host_64(pSeekpoint->flacFrameOffset);
  70460. pSeekpoint->pcmFrameCount = drflac__be2host_16(pSeekpoint->pcmFrameCount);
  70461. }
  70462. metadata.pRawData = pRawData;
  70463. metadata.rawDataSize = blockSize;
  70464. metadata.data.seektable.seekpointCount = seekpointCount;
  70465. metadata.data.seektable.pSeekpoints = (const drflac_seekpoint*)pRawData;
  70466. onMeta(pUserDataMD, &metadata);
  70467. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70468. }
  70469. } break;
  70470. case DRFLAC_METADATA_BLOCK_TYPE_VORBIS_COMMENT:
  70471. {
  70472. if (blockSize < 8) {
  70473. return DRFLAC_FALSE;
  70474. }
  70475. if (onMeta) {
  70476. void* pRawData;
  70477. const char* pRunningData;
  70478. const char* pRunningDataEnd;
  70479. drflac_uint32 i;
  70480. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  70481. if (pRawData == NULL) {
  70482. return DRFLAC_FALSE;
  70483. }
  70484. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  70485. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70486. return DRFLAC_FALSE;
  70487. }
  70488. metadata.pRawData = pRawData;
  70489. metadata.rawDataSize = blockSize;
  70490. pRunningData = (const char*)pRawData;
  70491. pRunningDataEnd = (const char*)pRawData + blockSize;
  70492. metadata.data.vorbis_comment.vendorLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70493. if ((pRunningDataEnd - pRunningData) - 4 < (drflac_int64)metadata.data.vorbis_comment.vendorLength) {
  70494. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70495. return DRFLAC_FALSE;
  70496. }
  70497. metadata.data.vorbis_comment.vendor = pRunningData; pRunningData += metadata.data.vorbis_comment.vendorLength;
  70498. metadata.data.vorbis_comment.commentCount = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70499. if ((pRunningDataEnd - pRunningData) / sizeof(drflac_uint32) < metadata.data.vorbis_comment.commentCount) {
  70500. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70501. return DRFLAC_FALSE;
  70502. }
  70503. metadata.data.vorbis_comment.pComments = pRunningData;
  70504. for (i = 0; i < metadata.data.vorbis_comment.commentCount; ++i) {
  70505. drflac_uint32 commentLength;
  70506. if (pRunningDataEnd - pRunningData < 4) {
  70507. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70508. return DRFLAC_FALSE;
  70509. }
  70510. commentLength = drflac__le2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70511. if (pRunningDataEnd - pRunningData < (drflac_int64)commentLength) {
  70512. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70513. return DRFLAC_FALSE;
  70514. }
  70515. pRunningData += commentLength;
  70516. }
  70517. onMeta(pUserDataMD, &metadata);
  70518. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70519. }
  70520. } break;
  70521. case DRFLAC_METADATA_BLOCK_TYPE_CUESHEET:
  70522. {
  70523. if (blockSize < 396) {
  70524. return DRFLAC_FALSE;
  70525. }
  70526. if (onMeta) {
  70527. void* pRawData;
  70528. const char* pRunningData;
  70529. const char* pRunningDataEnd;
  70530. size_t bufferSize;
  70531. drflac_uint8 iTrack;
  70532. drflac_uint8 iIndex;
  70533. void* pTrackData;
  70534. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  70535. if (pRawData == NULL) {
  70536. return DRFLAC_FALSE;
  70537. }
  70538. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  70539. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70540. return DRFLAC_FALSE;
  70541. }
  70542. metadata.pRawData = pRawData;
  70543. metadata.rawDataSize = blockSize;
  70544. pRunningData = (const char*)pRawData;
  70545. pRunningDataEnd = (const char*)pRawData + blockSize;
  70546. DRFLAC_COPY_MEMORY(metadata.data.cuesheet.catalog, pRunningData, 128); pRunningData += 128;
  70547. metadata.data.cuesheet.leadInSampleCount = drflac__be2host_64(*(const drflac_uint64*)pRunningData); pRunningData += 8;
  70548. metadata.data.cuesheet.isCD = (pRunningData[0] & 0x80) != 0; pRunningData += 259;
  70549. metadata.data.cuesheet.trackCount = pRunningData[0]; pRunningData += 1;
  70550. metadata.data.cuesheet.pTrackData = NULL;
  70551. {
  70552. const char* pRunningDataSaved = pRunningData;
  70553. bufferSize = metadata.data.cuesheet.trackCount * DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES;
  70554. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  70555. drflac_uint8 indexCount;
  70556. drflac_uint32 indexPointSize;
  70557. if (pRunningDataEnd - pRunningData < DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES) {
  70558. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70559. return DRFLAC_FALSE;
  70560. }
  70561. pRunningData += 35;
  70562. indexCount = pRunningData[0];
  70563. pRunningData += 1;
  70564. bufferSize += indexCount * sizeof(drflac_cuesheet_track_index);
  70565. indexPointSize = indexCount * DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  70566. if (pRunningDataEnd - pRunningData < (drflac_int64)indexPointSize) {
  70567. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70568. return DRFLAC_FALSE;
  70569. }
  70570. pRunningData += indexPointSize;
  70571. }
  70572. pRunningData = pRunningDataSaved;
  70573. }
  70574. {
  70575. char* pRunningTrackData;
  70576. pTrackData = drflac__malloc_from_callbacks(bufferSize, pAllocationCallbacks);
  70577. if (pTrackData == NULL) {
  70578. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70579. return DRFLAC_FALSE;
  70580. }
  70581. pRunningTrackData = (char*)pTrackData;
  70582. for (iTrack = 0; iTrack < metadata.data.cuesheet.trackCount; ++iTrack) {
  70583. drflac_uint8 indexCount;
  70584. DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES);
  70585. pRunningData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  70586. pRunningTrackData += DRFLAC_CUESHEET_TRACK_SIZE_IN_BYTES-1;
  70587. indexCount = pRunningData[0];
  70588. pRunningData += 1;
  70589. pRunningTrackData += 1;
  70590. for (iIndex = 0; iIndex < indexCount; ++iIndex) {
  70591. drflac_cuesheet_track_index* pTrackIndex = (drflac_cuesheet_track_index*)pRunningTrackData;
  70592. DRFLAC_COPY_MEMORY(pRunningTrackData, pRunningData, DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES);
  70593. pRunningData += DRFLAC_CUESHEET_TRACK_INDEX_SIZE_IN_BYTES;
  70594. pRunningTrackData += sizeof(drflac_cuesheet_track_index);
  70595. pTrackIndex->offset = drflac__be2host_64(pTrackIndex->offset);
  70596. }
  70597. }
  70598. metadata.data.cuesheet.pTrackData = pTrackData;
  70599. }
  70600. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70601. pRawData = NULL;
  70602. onMeta(pUserDataMD, &metadata);
  70603. drflac__free_from_callbacks(pTrackData, pAllocationCallbacks);
  70604. pTrackData = NULL;
  70605. }
  70606. } break;
  70607. case DRFLAC_METADATA_BLOCK_TYPE_PICTURE:
  70608. {
  70609. if (blockSize < 32) {
  70610. return DRFLAC_FALSE;
  70611. }
  70612. if (onMeta) {
  70613. void* pRawData;
  70614. const char* pRunningData;
  70615. const char* pRunningDataEnd;
  70616. pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  70617. if (pRawData == NULL) {
  70618. return DRFLAC_FALSE;
  70619. }
  70620. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  70621. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70622. return DRFLAC_FALSE;
  70623. }
  70624. metadata.pRawData = pRawData;
  70625. metadata.rawDataSize = blockSize;
  70626. pRunningData = (const char*)pRawData;
  70627. pRunningDataEnd = (const char*)pRawData + blockSize;
  70628. metadata.data.picture.type = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70629. metadata.data.picture.mimeLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70630. if ((pRunningDataEnd - pRunningData) - 24 < (drflac_int64)metadata.data.picture.mimeLength) {
  70631. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70632. return DRFLAC_FALSE;
  70633. }
  70634. metadata.data.picture.mime = pRunningData; pRunningData += metadata.data.picture.mimeLength;
  70635. metadata.data.picture.descriptionLength = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70636. if ((pRunningDataEnd - pRunningData) - 20 < (drflac_int64)metadata.data.picture.descriptionLength) {
  70637. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70638. return DRFLAC_FALSE;
  70639. }
  70640. metadata.data.picture.description = pRunningData; pRunningData += metadata.data.picture.descriptionLength;
  70641. metadata.data.picture.width = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70642. metadata.data.picture.height = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70643. metadata.data.picture.colorDepth = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70644. metadata.data.picture.indexColorCount = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70645. metadata.data.picture.pictureDataSize = drflac__be2host_32_ptr_unaligned(pRunningData); pRunningData += 4;
  70646. metadata.data.picture.pPictureData = (const drflac_uint8*)pRunningData;
  70647. if (pRunningDataEnd - pRunningData < (drflac_int64)metadata.data.picture.pictureDataSize) {
  70648. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70649. return DRFLAC_FALSE;
  70650. }
  70651. onMeta(pUserDataMD, &metadata);
  70652. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70653. }
  70654. } break;
  70655. case DRFLAC_METADATA_BLOCK_TYPE_PADDING:
  70656. {
  70657. if (onMeta) {
  70658. metadata.data.padding.unused = 0;
  70659. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  70660. isLastBlock = DRFLAC_TRUE;
  70661. } else {
  70662. onMeta(pUserDataMD, &metadata);
  70663. }
  70664. }
  70665. } break;
  70666. case DRFLAC_METADATA_BLOCK_TYPE_INVALID:
  70667. {
  70668. if (onMeta) {
  70669. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  70670. isLastBlock = DRFLAC_TRUE;
  70671. }
  70672. }
  70673. } break;
  70674. default:
  70675. {
  70676. if (onMeta) {
  70677. void* pRawData = drflac__malloc_from_callbacks(blockSize, pAllocationCallbacks);
  70678. if (pRawData == NULL) {
  70679. return DRFLAC_FALSE;
  70680. }
  70681. if (onRead(pUserData, pRawData, blockSize) != blockSize) {
  70682. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70683. return DRFLAC_FALSE;
  70684. }
  70685. metadata.pRawData = pRawData;
  70686. metadata.rawDataSize = blockSize;
  70687. onMeta(pUserDataMD, &metadata);
  70688. drflac__free_from_callbacks(pRawData, pAllocationCallbacks);
  70689. }
  70690. } break;
  70691. }
  70692. if (onMeta == NULL && blockSize > 0) {
  70693. if (!onSeek(pUserData, blockSize, drflac_seek_origin_current)) {
  70694. isLastBlock = DRFLAC_TRUE;
  70695. }
  70696. }
  70697. runningFilePos += blockSize;
  70698. if (isLastBlock) {
  70699. break;
  70700. }
  70701. }
  70702. *pSeektablePos = seektablePos;
  70703. *pSeekpointCount = seektableSize / DRFLAC_SEEKPOINT_SIZE_IN_BYTES;
  70704. *pFirstFramePos = runningFilePos;
  70705. return DRFLAC_TRUE;
  70706. }
  70707. static drflac_bool32 drflac__init_private__native(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
  70708. {
  70709. drflac_uint8 isLastBlock;
  70710. drflac_uint8 blockType;
  70711. drflac_uint32 blockSize;
  70712. (void)onSeek;
  70713. pInit->container = drflac_container_native;
  70714. if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  70715. return DRFLAC_FALSE;
  70716. }
  70717. if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  70718. if (!relaxed) {
  70719. return DRFLAC_FALSE;
  70720. } else {
  70721. pInit->hasStreamInfoBlock = DRFLAC_FALSE;
  70722. pInit->hasMetadataBlocks = DRFLAC_FALSE;
  70723. if (!drflac__read_next_flac_frame_header(&pInit->bs, 0, &pInit->firstFrameHeader)) {
  70724. return DRFLAC_FALSE;
  70725. }
  70726. if (pInit->firstFrameHeader.bitsPerSample == 0) {
  70727. return DRFLAC_FALSE;
  70728. }
  70729. pInit->sampleRate = pInit->firstFrameHeader.sampleRate;
  70730. pInit->channels = drflac__get_channel_count_from_channel_assignment(pInit->firstFrameHeader.channelAssignment);
  70731. pInit->bitsPerSample = pInit->firstFrameHeader.bitsPerSample;
  70732. pInit->maxBlockSizeInPCMFrames = 65535;
  70733. return DRFLAC_TRUE;
  70734. }
  70735. } else {
  70736. drflac_streaminfo streaminfo;
  70737. if (!drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  70738. return DRFLAC_FALSE;
  70739. }
  70740. pInit->hasStreamInfoBlock = DRFLAC_TRUE;
  70741. pInit->sampleRate = streaminfo.sampleRate;
  70742. pInit->channels = streaminfo.channels;
  70743. pInit->bitsPerSample = streaminfo.bitsPerSample;
  70744. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  70745. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  70746. pInit->hasMetadataBlocks = !isLastBlock;
  70747. if (onMeta) {
  70748. drflac_metadata metadata;
  70749. metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  70750. metadata.pRawData = NULL;
  70751. metadata.rawDataSize = 0;
  70752. metadata.data.streaminfo = streaminfo;
  70753. onMeta(pUserDataMD, &metadata);
  70754. }
  70755. return DRFLAC_TRUE;
  70756. }
  70757. }
  70758. #ifndef DR_FLAC_NO_OGG
  70759. #define DRFLAC_OGG_MAX_PAGE_SIZE 65307
  70760. #define DRFLAC_OGG_CAPTURE_PATTERN_CRC32 1605413199
  70761. typedef enum
  70762. {
  70763. drflac_ogg_recover_on_crc_mismatch,
  70764. drflac_ogg_fail_on_crc_mismatch
  70765. } drflac_ogg_crc_mismatch_recovery;
  70766. #ifndef DR_FLAC_NO_CRC
  70767. static drflac_uint32 drflac__crc32_table[] = {
  70768. 0x00000000L, 0x04C11DB7L, 0x09823B6EL, 0x0D4326D9L,
  70769. 0x130476DCL, 0x17C56B6BL, 0x1A864DB2L, 0x1E475005L,
  70770. 0x2608EDB8L, 0x22C9F00FL, 0x2F8AD6D6L, 0x2B4BCB61L,
  70771. 0x350C9B64L, 0x31CD86D3L, 0x3C8EA00AL, 0x384FBDBDL,
  70772. 0x4C11DB70L, 0x48D0C6C7L, 0x4593E01EL, 0x4152FDA9L,
  70773. 0x5F15ADACL, 0x5BD4B01BL, 0x569796C2L, 0x52568B75L,
  70774. 0x6A1936C8L, 0x6ED82B7FL, 0x639B0DA6L, 0x675A1011L,
  70775. 0x791D4014L, 0x7DDC5DA3L, 0x709F7B7AL, 0x745E66CDL,
  70776. 0x9823B6E0L, 0x9CE2AB57L, 0x91A18D8EL, 0x95609039L,
  70777. 0x8B27C03CL, 0x8FE6DD8BL, 0x82A5FB52L, 0x8664E6E5L,
  70778. 0xBE2B5B58L, 0xBAEA46EFL, 0xB7A96036L, 0xB3687D81L,
  70779. 0xAD2F2D84L, 0xA9EE3033L, 0xA4AD16EAL, 0xA06C0B5DL,
  70780. 0xD4326D90L, 0xD0F37027L, 0xDDB056FEL, 0xD9714B49L,
  70781. 0xC7361B4CL, 0xC3F706FBL, 0xCEB42022L, 0xCA753D95L,
  70782. 0xF23A8028L, 0xF6FB9D9FL, 0xFBB8BB46L, 0xFF79A6F1L,
  70783. 0xE13EF6F4L, 0xE5FFEB43L, 0xE8BCCD9AL, 0xEC7DD02DL,
  70784. 0x34867077L, 0x30476DC0L, 0x3D044B19L, 0x39C556AEL,
  70785. 0x278206ABL, 0x23431B1CL, 0x2E003DC5L, 0x2AC12072L,
  70786. 0x128E9DCFL, 0x164F8078L, 0x1B0CA6A1L, 0x1FCDBB16L,
  70787. 0x018AEB13L, 0x054BF6A4L, 0x0808D07DL, 0x0CC9CDCAL,
  70788. 0x7897AB07L, 0x7C56B6B0L, 0x71159069L, 0x75D48DDEL,
  70789. 0x6B93DDDBL, 0x6F52C06CL, 0x6211E6B5L, 0x66D0FB02L,
  70790. 0x5E9F46BFL, 0x5A5E5B08L, 0x571D7DD1L, 0x53DC6066L,
  70791. 0x4D9B3063L, 0x495A2DD4L, 0x44190B0DL, 0x40D816BAL,
  70792. 0xACA5C697L, 0xA864DB20L, 0xA527FDF9L, 0xA1E6E04EL,
  70793. 0xBFA1B04BL, 0xBB60ADFCL, 0xB6238B25L, 0xB2E29692L,
  70794. 0x8AAD2B2FL, 0x8E6C3698L, 0x832F1041L, 0x87EE0DF6L,
  70795. 0x99A95DF3L, 0x9D684044L, 0x902B669DL, 0x94EA7B2AL,
  70796. 0xE0B41DE7L, 0xE4750050L, 0xE9362689L, 0xEDF73B3EL,
  70797. 0xF3B06B3BL, 0xF771768CL, 0xFA325055L, 0xFEF34DE2L,
  70798. 0xC6BCF05FL, 0xC27DEDE8L, 0xCF3ECB31L, 0xCBFFD686L,
  70799. 0xD5B88683L, 0xD1799B34L, 0xDC3ABDEDL, 0xD8FBA05AL,
  70800. 0x690CE0EEL, 0x6DCDFD59L, 0x608EDB80L, 0x644FC637L,
  70801. 0x7A089632L, 0x7EC98B85L, 0x738AAD5CL, 0x774BB0EBL,
  70802. 0x4F040D56L, 0x4BC510E1L, 0x46863638L, 0x42472B8FL,
  70803. 0x5C007B8AL, 0x58C1663DL, 0x558240E4L, 0x51435D53L,
  70804. 0x251D3B9EL, 0x21DC2629L, 0x2C9F00F0L, 0x285E1D47L,
  70805. 0x36194D42L, 0x32D850F5L, 0x3F9B762CL, 0x3B5A6B9BL,
  70806. 0x0315D626L, 0x07D4CB91L, 0x0A97ED48L, 0x0E56F0FFL,
  70807. 0x1011A0FAL, 0x14D0BD4DL, 0x19939B94L, 0x1D528623L,
  70808. 0xF12F560EL, 0xF5EE4BB9L, 0xF8AD6D60L, 0xFC6C70D7L,
  70809. 0xE22B20D2L, 0xE6EA3D65L, 0xEBA91BBCL, 0xEF68060BL,
  70810. 0xD727BBB6L, 0xD3E6A601L, 0xDEA580D8L, 0xDA649D6FL,
  70811. 0xC423CD6AL, 0xC0E2D0DDL, 0xCDA1F604L, 0xC960EBB3L,
  70812. 0xBD3E8D7EL, 0xB9FF90C9L, 0xB4BCB610L, 0xB07DABA7L,
  70813. 0xAE3AFBA2L, 0xAAFBE615L, 0xA7B8C0CCL, 0xA379DD7BL,
  70814. 0x9B3660C6L, 0x9FF77D71L, 0x92B45BA8L, 0x9675461FL,
  70815. 0x8832161AL, 0x8CF30BADL, 0x81B02D74L, 0x857130C3L,
  70816. 0x5D8A9099L, 0x594B8D2EL, 0x5408ABF7L, 0x50C9B640L,
  70817. 0x4E8EE645L, 0x4A4FFBF2L, 0x470CDD2BL, 0x43CDC09CL,
  70818. 0x7B827D21L, 0x7F436096L, 0x7200464FL, 0x76C15BF8L,
  70819. 0x68860BFDL, 0x6C47164AL, 0x61043093L, 0x65C52D24L,
  70820. 0x119B4BE9L, 0x155A565EL, 0x18197087L, 0x1CD86D30L,
  70821. 0x029F3D35L, 0x065E2082L, 0x0B1D065BL, 0x0FDC1BECL,
  70822. 0x3793A651L, 0x3352BBE6L, 0x3E119D3FL, 0x3AD08088L,
  70823. 0x2497D08DL, 0x2056CD3AL, 0x2D15EBE3L, 0x29D4F654L,
  70824. 0xC5A92679L, 0xC1683BCEL, 0xCC2B1D17L, 0xC8EA00A0L,
  70825. 0xD6AD50A5L, 0xD26C4D12L, 0xDF2F6BCBL, 0xDBEE767CL,
  70826. 0xE3A1CBC1L, 0xE760D676L, 0xEA23F0AFL, 0xEEE2ED18L,
  70827. 0xF0A5BD1DL, 0xF464A0AAL, 0xF9278673L, 0xFDE69BC4L,
  70828. 0x89B8FD09L, 0x8D79E0BEL, 0x803AC667L, 0x84FBDBD0L,
  70829. 0x9ABC8BD5L, 0x9E7D9662L, 0x933EB0BBL, 0x97FFAD0CL,
  70830. 0xAFB010B1L, 0xAB710D06L, 0xA6322BDFL, 0xA2F33668L,
  70831. 0xBCB4666DL, 0xB8757BDAL, 0xB5365D03L, 0xB1F740B4L
  70832. };
  70833. #endif
  70834. static DRFLAC_INLINE drflac_uint32 drflac_crc32_byte(drflac_uint32 crc32, drflac_uint8 data)
  70835. {
  70836. #ifndef DR_FLAC_NO_CRC
  70837. return (crc32 << 8) ^ drflac__crc32_table[(drflac_uint8)((crc32 >> 24) & 0xFF) ^ data];
  70838. #else
  70839. (void)data;
  70840. return crc32;
  70841. #endif
  70842. }
  70843. #if 0
  70844. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint32(drflac_uint32 crc32, drflac_uint32 data)
  70845. {
  70846. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 24) & 0xFF));
  70847. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 16) & 0xFF));
  70848. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 8) & 0xFF));
  70849. crc32 = drflac_crc32_byte(crc32, (drflac_uint8)((data >> 0) & 0xFF));
  70850. return crc32;
  70851. }
  70852. static DRFLAC_INLINE drflac_uint32 drflac_crc32_uint64(drflac_uint32 crc32, drflac_uint64 data)
  70853. {
  70854. crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 32) & 0xFFFFFFFF));
  70855. crc32 = drflac_crc32_uint32(crc32, (drflac_uint32)((data >> 0) & 0xFFFFFFFF));
  70856. return crc32;
  70857. }
  70858. #endif
  70859. static DRFLAC_INLINE drflac_uint32 drflac_crc32_buffer(drflac_uint32 crc32, drflac_uint8* pData, drflac_uint32 dataSize)
  70860. {
  70861. drflac_uint32 i;
  70862. for (i = 0; i < dataSize; ++i) {
  70863. crc32 = drflac_crc32_byte(crc32, pData[i]);
  70864. }
  70865. return crc32;
  70866. }
  70867. static DRFLAC_INLINE drflac_bool32 drflac_ogg__is_capture_pattern(drflac_uint8 pattern[4])
  70868. {
  70869. return pattern[0] == 'O' && pattern[1] == 'g' && pattern[2] == 'g' && pattern[3] == 'S';
  70870. }
  70871. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_header_size(drflac_ogg_page_header* pHeader)
  70872. {
  70873. return 27 + pHeader->segmentCount;
  70874. }
  70875. static DRFLAC_INLINE drflac_uint32 drflac_ogg__get_page_body_size(drflac_ogg_page_header* pHeader)
  70876. {
  70877. drflac_uint32 pageBodySize = 0;
  70878. int i;
  70879. for (i = 0; i < pHeader->segmentCount; ++i) {
  70880. pageBodySize += pHeader->segmentTable[i];
  70881. }
  70882. return pageBodySize;
  70883. }
  70884. static drflac_result drflac_ogg__read_page_header_after_capture_pattern(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
  70885. {
  70886. drflac_uint8 data[23];
  70887. drflac_uint32 i;
  70888. DRFLAC_ASSERT(*pCRC32 == DRFLAC_OGG_CAPTURE_PATTERN_CRC32);
  70889. if (onRead(pUserData, data, 23) != 23) {
  70890. return DRFLAC_AT_END;
  70891. }
  70892. *pBytesRead += 23;
  70893. pHeader->capturePattern[0] = 'O';
  70894. pHeader->capturePattern[1] = 'g';
  70895. pHeader->capturePattern[2] = 'g';
  70896. pHeader->capturePattern[3] = 'S';
  70897. pHeader->structureVersion = data[0];
  70898. pHeader->headerType = data[1];
  70899. DRFLAC_COPY_MEMORY(&pHeader->granulePosition, &data[ 2], 8);
  70900. DRFLAC_COPY_MEMORY(&pHeader->serialNumber, &data[10], 4);
  70901. DRFLAC_COPY_MEMORY(&pHeader->sequenceNumber, &data[14], 4);
  70902. DRFLAC_COPY_MEMORY(&pHeader->checksum, &data[18], 4);
  70903. pHeader->segmentCount = data[22];
  70904. data[18] = 0;
  70905. data[19] = 0;
  70906. data[20] = 0;
  70907. data[21] = 0;
  70908. for (i = 0; i < 23; ++i) {
  70909. *pCRC32 = drflac_crc32_byte(*pCRC32, data[i]);
  70910. }
  70911. if (onRead(pUserData, pHeader->segmentTable, pHeader->segmentCount) != pHeader->segmentCount) {
  70912. return DRFLAC_AT_END;
  70913. }
  70914. *pBytesRead += pHeader->segmentCount;
  70915. for (i = 0; i < pHeader->segmentCount; ++i) {
  70916. *pCRC32 = drflac_crc32_byte(*pCRC32, pHeader->segmentTable[i]);
  70917. }
  70918. return DRFLAC_SUCCESS;
  70919. }
  70920. static drflac_result drflac_ogg__read_page_header(drflac_read_proc onRead, void* pUserData, drflac_ogg_page_header* pHeader, drflac_uint32* pBytesRead, drflac_uint32* pCRC32)
  70921. {
  70922. drflac_uint8 id[4];
  70923. *pBytesRead = 0;
  70924. if (onRead(pUserData, id, 4) != 4) {
  70925. return DRFLAC_AT_END;
  70926. }
  70927. *pBytesRead += 4;
  70928. for (;;) {
  70929. if (drflac_ogg__is_capture_pattern(id)) {
  70930. drflac_result result;
  70931. *pCRC32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  70932. result = drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, pHeader, pBytesRead, pCRC32);
  70933. if (result == DRFLAC_SUCCESS) {
  70934. return DRFLAC_SUCCESS;
  70935. } else {
  70936. if (result == DRFLAC_CRC_MISMATCH) {
  70937. continue;
  70938. } else {
  70939. return result;
  70940. }
  70941. }
  70942. } else {
  70943. id[0] = id[1];
  70944. id[1] = id[2];
  70945. id[2] = id[3];
  70946. if (onRead(pUserData, &id[3], 1) != 1) {
  70947. return DRFLAC_AT_END;
  70948. }
  70949. *pBytesRead += 1;
  70950. }
  70951. }
  70952. }
  70953. typedef struct
  70954. {
  70955. drflac_read_proc onRead;
  70956. drflac_seek_proc onSeek;
  70957. void* pUserData;
  70958. drflac_uint64 currentBytePos;
  70959. drflac_uint64 firstBytePos;
  70960. drflac_uint32 serialNumber;
  70961. drflac_ogg_page_header bosPageHeader;
  70962. drflac_ogg_page_header currentPageHeader;
  70963. drflac_uint32 bytesRemainingInPage;
  70964. drflac_uint32 pageDataSize;
  70965. drflac_uint8 pageData[DRFLAC_OGG_MAX_PAGE_SIZE];
  70966. } drflac_oggbs;
  70967. static size_t drflac_oggbs__read_physical(drflac_oggbs* oggbs, void* bufferOut, size_t bytesToRead)
  70968. {
  70969. size_t bytesActuallyRead = oggbs->onRead(oggbs->pUserData, bufferOut, bytesToRead);
  70970. oggbs->currentBytePos += bytesActuallyRead;
  70971. return bytesActuallyRead;
  70972. }
  70973. static drflac_bool32 drflac_oggbs__seek_physical(drflac_oggbs* oggbs, drflac_uint64 offset, drflac_seek_origin origin)
  70974. {
  70975. if (origin == drflac_seek_origin_start) {
  70976. if (offset <= 0x7FFFFFFF) {
  70977. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_start)) {
  70978. return DRFLAC_FALSE;
  70979. }
  70980. oggbs->currentBytePos = offset;
  70981. return DRFLAC_TRUE;
  70982. } else {
  70983. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_start)) {
  70984. return DRFLAC_FALSE;
  70985. }
  70986. oggbs->currentBytePos = offset;
  70987. return drflac_oggbs__seek_physical(oggbs, offset - 0x7FFFFFFF, drflac_seek_origin_current);
  70988. }
  70989. } else {
  70990. while (offset > 0x7FFFFFFF) {
  70991. if (!oggbs->onSeek(oggbs->pUserData, 0x7FFFFFFF, drflac_seek_origin_current)) {
  70992. return DRFLAC_FALSE;
  70993. }
  70994. oggbs->currentBytePos += 0x7FFFFFFF;
  70995. offset -= 0x7FFFFFFF;
  70996. }
  70997. if (!oggbs->onSeek(oggbs->pUserData, (int)offset, drflac_seek_origin_current)) {
  70998. return DRFLAC_FALSE;
  70999. }
  71000. oggbs->currentBytePos += offset;
  71001. return DRFLAC_TRUE;
  71002. }
  71003. }
  71004. static drflac_bool32 drflac_oggbs__goto_next_page(drflac_oggbs* oggbs, drflac_ogg_crc_mismatch_recovery recoveryMethod)
  71005. {
  71006. drflac_ogg_page_header header;
  71007. for (;;) {
  71008. drflac_uint32 crc32 = 0;
  71009. drflac_uint32 bytesRead;
  71010. drflac_uint32 pageBodySize;
  71011. #ifndef DR_FLAC_NO_CRC
  71012. drflac_uint32 actualCRC32;
  71013. #endif
  71014. if (drflac_ogg__read_page_header(oggbs->onRead, oggbs->pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  71015. return DRFLAC_FALSE;
  71016. }
  71017. oggbs->currentBytePos += bytesRead;
  71018. pageBodySize = drflac_ogg__get_page_body_size(&header);
  71019. if (pageBodySize > DRFLAC_OGG_MAX_PAGE_SIZE) {
  71020. continue;
  71021. }
  71022. if (header.serialNumber != oggbs->serialNumber) {
  71023. if (pageBodySize > 0 && !drflac_oggbs__seek_physical(oggbs, pageBodySize, drflac_seek_origin_current)) {
  71024. return DRFLAC_FALSE;
  71025. }
  71026. continue;
  71027. }
  71028. if (drflac_oggbs__read_physical(oggbs, oggbs->pageData, pageBodySize) != pageBodySize) {
  71029. return DRFLAC_FALSE;
  71030. }
  71031. oggbs->pageDataSize = pageBodySize;
  71032. #ifndef DR_FLAC_NO_CRC
  71033. actualCRC32 = drflac_crc32_buffer(crc32, oggbs->pageData, oggbs->pageDataSize);
  71034. if (actualCRC32 != header.checksum) {
  71035. if (recoveryMethod == drflac_ogg_recover_on_crc_mismatch) {
  71036. continue;
  71037. } else {
  71038. drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch);
  71039. return DRFLAC_FALSE;
  71040. }
  71041. }
  71042. #else
  71043. (void)recoveryMethod;
  71044. #endif
  71045. oggbs->currentPageHeader = header;
  71046. oggbs->bytesRemainingInPage = pageBodySize;
  71047. return DRFLAC_TRUE;
  71048. }
  71049. }
  71050. #if 0
  71051. static drflac_uint8 drflac_oggbs__get_current_segment_index(drflac_oggbs* oggbs, drflac_uint8* pBytesRemainingInSeg)
  71052. {
  71053. drflac_uint32 bytesConsumedInPage = drflac_ogg__get_page_body_size(&oggbs->currentPageHeader) - oggbs->bytesRemainingInPage;
  71054. drflac_uint8 iSeg = 0;
  71055. drflac_uint32 iByte = 0;
  71056. while (iByte < bytesConsumedInPage) {
  71057. drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  71058. if (iByte + segmentSize > bytesConsumedInPage) {
  71059. break;
  71060. } else {
  71061. iSeg += 1;
  71062. iByte += segmentSize;
  71063. }
  71064. }
  71065. *pBytesRemainingInSeg = oggbs->currentPageHeader.segmentTable[iSeg] - (drflac_uint8)(bytesConsumedInPage - iByte);
  71066. return iSeg;
  71067. }
  71068. static drflac_bool32 drflac_oggbs__seek_to_next_packet(drflac_oggbs* oggbs)
  71069. {
  71070. for (;;) {
  71071. drflac_bool32 atEndOfPage = DRFLAC_FALSE;
  71072. drflac_uint8 bytesRemainingInSeg;
  71073. drflac_uint8 iFirstSeg = drflac_oggbs__get_current_segment_index(oggbs, &bytesRemainingInSeg);
  71074. drflac_uint32 bytesToEndOfPacketOrPage = bytesRemainingInSeg;
  71075. for (drflac_uint8 iSeg = iFirstSeg; iSeg < oggbs->currentPageHeader.segmentCount; ++iSeg) {
  71076. drflac_uint8 segmentSize = oggbs->currentPageHeader.segmentTable[iSeg];
  71077. if (segmentSize < 255) {
  71078. if (iSeg == oggbs->currentPageHeader.segmentCount-1) {
  71079. atEndOfPage = DRFLAC_TRUE;
  71080. }
  71081. break;
  71082. }
  71083. bytesToEndOfPacketOrPage += segmentSize;
  71084. }
  71085. drflac_oggbs__seek_physical(oggbs, bytesToEndOfPacketOrPage, drflac_seek_origin_current);
  71086. oggbs->bytesRemainingInPage -= bytesToEndOfPacketOrPage;
  71087. if (atEndOfPage) {
  71088. if (!drflac_oggbs__goto_next_page(oggbs)) {
  71089. return DRFLAC_FALSE;
  71090. }
  71091. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  71092. return DRFLAC_TRUE;
  71093. }
  71094. } else {
  71095. return DRFLAC_TRUE;
  71096. }
  71097. }
  71098. }
  71099. static drflac_bool32 drflac_oggbs__seek_to_next_frame(drflac_oggbs* oggbs)
  71100. {
  71101. return drflac_oggbs__seek_to_next_packet(oggbs);
  71102. }
  71103. #endif
  71104. static size_t drflac__on_read_ogg(void* pUserData, void* bufferOut, size_t bytesToRead)
  71105. {
  71106. drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  71107. drflac_uint8* pRunningBufferOut = (drflac_uint8*)bufferOut;
  71108. size_t bytesRead = 0;
  71109. DRFLAC_ASSERT(oggbs != NULL);
  71110. DRFLAC_ASSERT(pRunningBufferOut != NULL);
  71111. while (bytesRead < bytesToRead) {
  71112. size_t bytesRemainingToRead = bytesToRead - bytesRead;
  71113. if (oggbs->bytesRemainingInPage >= bytesRemainingToRead) {
  71114. DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), bytesRemainingToRead);
  71115. bytesRead += bytesRemainingToRead;
  71116. oggbs->bytesRemainingInPage -= (drflac_uint32)bytesRemainingToRead;
  71117. break;
  71118. }
  71119. if (oggbs->bytesRemainingInPage > 0) {
  71120. DRFLAC_COPY_MEMORY(pRunningBufferOut, oggbs->pageData + (oggbs->pageDataSize - oggbs->bytesRemainingInPage), oggbs->bytesRemainingInPage);
  71121. bytesRead += oggbs->bytesRemainingInPage;
  71122. pRunningBufferOut += oggbs->bytesRemainingInPage;
  71123. oggbs->bytesRemainingInPage = 0;
  71124. }
  71125. DRFLAC_ASSERT(bytesRemainingToRead > 0);
  71126. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  71127. break;
  71128. }
  71129. }
  71130. return bytesRead;
  71131. }
  71132. static drflac_bool32 drflac__on_seek_ogg(void* pUserData, int offset, drflac_seek_origin origin)
  71133. {
  71134. drflac_oggbs* oggbs = (drflac_oggbs*)pUserData;
  71135. int bytesSeeked = 0;
  71136. DRFLAC_ASSERT(oggbs != NULL);
  71137. DRFLAC_ASSERT(offset >= 0);
  71138. if (origin == drflac_seek_origin_start) {
  71139. if (!drflac_oggbs__seek_physical(oggbs, (int)oggbs->firstBytePos, drflac_seek_origin_start)) {
  71140. return DRFLAC_FALSE;
  71141. }
  71142. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  71143. return DRFLAC_FALSE;
  71144. }
  71145. return drflac__on_seek_ogg(pUserData, offset, drflac_seek_origin_current);
  71146. }
  71147. DRFLAC_ASSERT(origin == drflac_seek_origin_current);
  71148. while (bytesSeeked < offset) {
  71149. int bytesRemainingToSeek = offset - bytesSeeked;
  71150. DRFLAC_ASSERT(bytesRemainingToSeek >= 0);
  71151. if (oggbs->bytesRemainingInPage >= (size_t)bytesRemainingToSeek) {
  71152. bytesSeeked += bytesRemainingToSeek;
  71153. (void)bytesSeeked;
  71154. oggbs->bytesRemainingInPage -= bytesRemainingToSeek;
  71155. break;
  71156. }
  71157. if (oggbs->bytesRemainingInPage > 0) {
  71158. bytesSeeked += (int)oggbs->bytesRemainingInPage;
  71159. oggbs->bytesRemainingInPage = 0;
  71160. }
  71161. DRFLAC_ASSERT(bytesRemainingToSeek > 0);
  71162. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_fail_on_crc_mismatch)) {
  71163. return DRFLAC_FALSE;
  71164. }
  71165. }
  71166. return DRFLAC_TRUE;
  71167. }
  71168. static drflac_bool32 drflac_ogg__seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  71169. {
  71170. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  71171. drflac_uint64 originalBytePos;
  71172. drflac_uint64 runningGranulePosition;
  71173. drflac_uint64 runningFrameBytePos;
  71174. drflac_uint64 runningPCMFrameCount;
  71175. DRFLAC_ASSERT(oggbs != NULL);
  71176. originalBytePos = oggbs->currentBytePos;
  71177. if (!drflac__seek_to_byte(&pFlac->bs, pFlac->firstFLACFramePosInBytes)) {
  71178. return DRFLAC_FALSE;
  71179. }
  71180. oggbs->bytesRemainingInPage = 0;
  71181. runningGranulePosition = 0;
  71182. for (;;) {
  71183. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  71184. drflac_oggbs__seek_physical(oggbs, originalBytePos, drflac_seek_origin_start);
  71185. return DRFLAC_FALSE;
  71186. }
  71187. runningFrameBytePos = oggbs->currentBytePos - drflac_ogg__get_page_header_size(&oggbs->currentPageHeader) - oggbs->pageDataSize;
  71188. if (oggbs->currentPageHeader.granulePosition >= pcmFrameIndex) {
  71189. break;
  71190. }
  71191. if ((oggbs->currentPageHeader.headerType & 0x01) == 0) {
  71192. if (oggbs->currentPageHeader.segmentTable[0] >= 2) {
  71193. drflac_uint8 firstBytesInPage[2];
  71194. firstBytesInPage[0] = oggbs->pageData[0];
  71195. firstBytesInPage[1] = oggbs->pageData[1];
  71196. if ((firstBytesInPage[0] == 0xFF) && (firstBytesInPage[1] & 0xFC) == 0xF8) {
  71197. runningGranulePosition = oggbs->currentPageHeader.granulePosition;
  71198. }
  71199. continue;
  71200. }
  71201. }
  71202. }
  71203. if (!drflac_oggbs__seek_physical(oggbs, runningFrameBytePos, drflac_seek_origin_start)) {
  71204. return DRFLAC_FALSE;
  71205. }
  71206. if (!drflac_oggbs__goto_next_page(oggbs, drflac_ogg_recover_on_crc_mismatch)) {
  71207. return DRFLAC_FALSE;
  71208. }
  71209. runningPCMFrameCount = runningGranulePosition;
  71210. for (;;) {
  71211. drflac_uint64 firstPCMFrameInFLACFrame = 0;
  71212. drflac_uint64 lastPCMFrameInFLACFrame = 0;
  71213. drflac_uint64 pcmFrameCountInThisFrame;
  71214. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71215. return DRFLAC_FALSE;
  71216. }
  71217. drflac__get_pcm_frame_range_of_current_flac_frame(pFlac, &firstPCMFrameInFLACFrame, &lastPCMFrameInFLACFrame);
  71218. pcmFrameCountInThisFrame = (lastPCMFrameInFLACFrame - firstPCMFrameInFLACFrame) + 1;
  71219. if (pcmFrameIndex == pFlac->totalPCMFrameCount && (runningPCMFrameCount + pcmFrameCountInThisFrame) == pFlac->totalPCMFrameCount) {
  71220. drflac_result result = drflac__decode_flac_frame(pFlac);
  71221. if (result == DRFLAC_SUCCESS) {
  71222. pFlac->currentPCMFrame = pcmFrameIndex;
  71223. pFlac->currentFLACFrame.pcmFramesRemaining = 0;
  71224. return DRFLAC_TRUE;
  71225. } else {
  71226. return DRFLAC_FALSE;
  71227. }
  71228. }
  71229. if (pcmFrameIndex < (runningPCMFrameCount + pcmFrameCountInThisFrame)) {
  71230. drflac_result result = drflac__decode_flac_frame(pFlac);
  71231. if (result == DRFLAC_SUCCESS) {
  71232. drflac_uint64 pcmFramesToDecode = (size_t)(pcmFrameIndex - runningPCMFrameCount);
  71233. if (pcmFramesToDecode == 0) {
  71234. return DRFLAC_TRUE;
  71235. }
  71236. pFlac->currentPCMFrame = runningPCMFrameCount;
  71237. return drflac__seek_forward_by_pcm_frames(pFlac, pcmFramesToDecode) == pcmFramesToDecode;
  71238. } else {
  71239. if (result == DRFLAC_CRC_MISMATCH) {
  71240. continue;
  71241. } else {
  71242. return DRFLAC_FALSE;
  71243. }
  71244. }
  71245. } else {
  71246. drflac_result result = drflac__seek_to_next_flac_frame(pFlac);
  71247. if (result == DRFLAC_SUCCESS) {
  71248. runningPCMFrameCount += pcmFrameCountInThisFrame;
  71249. } else {
  71250. if (result == DRFLAC_CRC_MISMATCH) {
  71251. continue;
  71252. } else {
  71253. return DRFLAC_FALSE;
  71254. }
  71255. }
  71256. }
  71257. }
  71258. }
  71259. static drflac_bool32 drflac__init_private__ogg(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, void* pUserDataMD, drflac_bool32 relaxed)
  71260. {
  71261. drflac_ogg_page_header header;
  71262. drflac_uint32 crc32 = DRFLAC_OGG_CAPTURE_PATTERN_CRC32;
  71263. drflac_uint32 bytesRead = 0;
  71264. (void)relaxed;
  71265. pInit->container = drflac_container_ogg;
  71266. pInit->oggFirstBytePos = 0;
  71267. if (drflac_ogg__read_page_header_after_capture_pattern(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  71268. return DRFLAC_FALSE;
  71269. }
  71270. pInit->runningFilePos += bytesRead;
  71271. for (;;) {
  71272. int pageBodySize;
  71273. if ((header.headerType & 0x02) == 0) {
  71274. return DRFLAC_FALSE;
  71275. }
  71276. pageBodySize = drflac_ogg__get_page_body_size(&header);
  71277. if (pageBodySize == 51) {
  71278. drflac_uint32 bytesRemainingInPage = pageBodySize;
  71279. drflac_uint8 packetType;
  71280. if (onRead(pUserData, &packetType, 1) != 1) {
  71281. return DRFLAC_FALSE;
  71282. }
  71283. bytesRemainingInPage -= 1;
  71284. if (packetType == 0x7F) {
  71285. drflac_uint8 sig[4];
  71286. if (onRead(pUserData, sig, 4) != 4) {
  71287. return DRFLAC_FALSE;
  71288. }
  71289. bytesRemainingInPage -= 4;
  71290. if (sig[0] == 'F' && sig[1] == 'L' && sig[2] == 'A' && sig[3] == 'C') {
  71291. drflac_uint8 mappingVersion[2];
  71292. if (onRead(pUserData, mappingVersion, 2) != 2) {
  71293. return DRFLAC_FALSE;
  71294. }
  71295. if (mappingVersion[0] != 1) {
  71296. return DRFLAC_FALSE;
  71297. }
  71298. if (!onSeek(pUserData, 2, drflac_seek_origin_current)) {
  71299. return DRFLAC_FALSE;
  71300. }
  71301. if (onRead(pUserData, sig, 4) != 4) {
  71302. return DRFLAC_FALSE;
  71303. }
  71304. if (sig[0] == 'f' && sig[1] == 'L' && sig[2] == 'a' && sig[3] == 'C') {
  71305. drflac_streaminfo streaminfo;
  71306. drflac_uint8 isLastBlock;
  71307. drflac_uint8 blockType;
  71308. drflac_uint32 blockSize;
  71309. if (!drflac__read_and_decode_block_header(onRead, pUserData, &isLastBlock, &blockType, &blockSize)) {
  71310. return DRFLAC_FALSE;
  71311. }
  71312. if (blockType != DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO || blockSize != 34) {
  71313. return DRFLAC_FALSE;
  71314. }
  71315. if (drflac__read_streaminfo(onRead, pUserData, &streaminfo)) {
  71316. pInit->hasStreamInfoBlock = DRFLAC_TRUE;
  71317. pInit->sampleRate = streaminfo.sampleRate;
  71318. pInit->channels = streaminfo.channels;
  71319. pInit->bitsPerSample = streaminfo.bitsPerSample;
  71320. pInit->totalPCMFrameCount = streaminfo.totalPCMFrameCount;
  71321. pInit->maxBlockSizeInPCMFrames = streaminfo.maxBlockSizeInPCMFrames;
  71322. pInit->hasMetadataBlocks = !isLastBlock;
  71323. if (onMeta) {
  71324. drflac_metadata metadata;
  71325. metadata.type = DRFLAC_METADATA_BLOCK_TYPE_STREAMINFO;
  71326. metadata.pRawData = NULL;
  71327. metadata.rawDataSize = 0;
  71328. metadata.data.streaminfo = streaminfo;
  71329. onMeta(pUserDataMD, &metadata);
  71330. }
  71331. pInit->runningFilePos += pageBodySize;
  71332. pInit->oggFirstBytePos = pInit->runningFilePos - 79;
  71333. pInit->oggSerial = header.serialNumber;
  71334. pInit->oggBosHeader = header;
  71335. break;
  71336. } else {
  71337. return DRFLAC_FALSE;
  71338. }
  71339. } else {
  71340. return DRFLAC_FALSE;
  71341. }
  71342. } else {
  71343. if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  71344. return DRFLAC_FALSE;
  71345. }
  71346. }
  71347. } else {
  71348. if (!onSeek(pUserData, bytesRemainingInPage, drflac_seek_origin_current)) {
  71349. return DRFLAC_FALSE;
  71350. }
  71351. }
  71352. } else {
  71353. if (!onSeek(pUserData, pageBodySize, drflac_seek_origin_current)) {
  71354. return DRFLAC_FALSE;
  71355. }
  71356. }
  71357. pInit->runningFilePos += pageBodySize;
  71358. if (drflac_ogg__read_page_header(onRead, pUserData, &header, &bytesRead, &crc32) != DRFLAC_SUCCESS) {
  71359. return DRFLAC_FALSE;
  71360. }
  71361. pInit->runningFilePos += bytesRead;
  71362. }
  71363. pInit->hasMetadataBlocks = DRFLAC_TRUE;
  71364. return DRFLAC_TRUE;
  71365. }
  71366. #endif
  71367. static drflac_bool32 drflac__init_private(drflac_init_info* pInit, drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD)
  71368. {
  71369. drflac_bool32 relaxed;
  71370. drflac_uint8 id[4];
  71371. if (pInit == NULL || onRead == NULL || onSeek == NULL) {
  71372. return DRFLAC_FALSE;
  71373. }
  71374. DRFLAC_ZERO_MEMORY(pInit, sizeof(*pInit));
  71375. pInit->onRead = onRead;
  71376. pInit->onSeek = onSeek;
  71377. pInit->onMeta = onMeta;
  71378. pInit->container = container;
  71379. pInit->pUserData = pUserData;
  71380. pInit->pUserDataMD = pUserDataMD;
  71381. pInit->bs.onRead = onRead;
  71382. pInit->bs.onSeek = onSeek;
  71383. pInit->bs.pUserData = pUserData;
  71384. drflac__reset_cache(&pInit->bs);
  71385. relaxed = container != drflac_container_unknown;
  71386. for (;;) {
  71387. if (onRead(pUserData, id, 4) != 4) {
  71388. return DRFLAC_FALSE;
  71389. }
  71390. pInit->runningFilePos += 4;
  71391. if (id[0] == 'I' && id[1] == 'D' && id[2] == '3') {
  71392. drflac_uint8 header[6];
  71393. drflac_uint8 flags;
  71394. drflac_uint32 headerSize;
  71395. if (onRead(pUserData, header, 6) != 6) {
  71396. return DRFLAC_FALSE;
  71397. }
  71398. pInit->runningFilePos += 6;
  71399. flags = header[1];
  71400. DRFLAC_COPY_MEMORY(&headerSize, header+2, 4);
  71401. headerSize = drflac__unsynchsafe_32(drflac__be2host_32(headerSize));
  71402. if (flags & 0x10) {
  71403. headerSize += 10;
  71404. }
  71405. if (!onSeek(pUserData, headerSize, drflac_seek_origin_current)) {
  71406. return DRFLAC_FALSE;
  71407. }
  71408. pInit->runningFilePos += headerSize;
  71409. } else {
  71410. break;
  71411. }
  71412. }
  71413. if (id[0] == 'f' && id[1] == 'L' && id[2] == 'a' && id[3] == 'C') {
  71414. return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  71415. }
  71416. #ifndef DR_FLAC_NO_OGG
  71417. if (id[0] == 'O' && id[1] == 'g' && id[2] == 'g' && id[3] == 'S') {
  71418. return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  71419. }
  71420. #endif
  71421. if (relaxed) {
  71422. if (container == drflac_container_native) {
  71423. return drflac__init_private__native(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  71424. }
  71425. #ifndef DR_FLAC_NO_OGG
  71426. if (container == drflac_container_ogg) {
  71427. return drflac__init_private__ogg(pInit, onRead, onSeek, onMeta, pUserData, pUserDataMD, relaxed);
  71428. }
  71429. #endif
  71430. }
  71431. return DRFLAC_FALSE;
  71432. }
  71433. static void drflac__init_from_info(drflac* pFlac, const drflac_init_info* pInit)
  71434. {
  71435. DRFLAC_ASSERT(pFlac != NULL);
  71436. DRFLAC_ASSERT(pInit != NULL);
  71437. DRFLAC_ZERO_MEMORY(pFlac, sizeof(*pFlac));
  71438. pFlac->bs = pInit->bs;
  71439. pFlac->onMeta = pInit->onMeta;
  71440. pFlac->pUserDataMD = pInit->pUserDataMD;
  71441. pFlac->maxBlockSizeInPCMFrames = pInit->maxBlockSizeInPCMFrames;
  71442. pFlac->sampleRate = pInit->sampleRate;
  71443. pFlac->channels = (drflac_uint8)pInit->channels;
  71444. pFlac->bitsPerSample = (drflac_uint8)pInit->bitsPerSample;
  71445. pFlac->totalPCMFrameCount = pInit->totalPCMFrameCount;
  71446. pFlac->container = pInit->container;
  71447. }
  71448. static drflac* drflac_open_with_metadata_private(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, void* pUserDataMD, const drflac_allocation_callbacks* pAllocationCallbacks)
  71449. {
  71450. drflac_init_info init;
  71451. drflac_uint32 allocationSize;
  71452. drflac_uint32 wholeSIMDVectorCountPerChannel;
  71453. drflac_uint32 decodedSamplesAllocationSize;
  71454. #ifndef DR_FLAC_NO_OGG
  71455. drflac_oggbs* pOggbs = NULL;
  71456. #endif
  71457. drflac_uint64 firstFramePos;
  71458. drflac_uint64 seektablePos;
  71459. drflac_uint32 seekpointCount;
  71460. drflac_allocation_callbacks allocationCallbacks;
  71461. drflac* pFlac;
  71462. drflac__init_cpu_caps();
  71463. if (!drflac__init_private(&init, onRead, onSeek, onMeta, container, pUserData, pUserDataMD)) {
  71464. return NULL;
  71465. }
  71466. if (pAllocationCallbacks != NULL) {
  71467. allocationCallbacks = *pAllocationCallbacks;
  71468. if (allocationCallbacks.onFree == NULL || (allocationCallbacks.onMalloc == NULL && allocationCallbacks.onRealloc == NULL)) {
  71469. return NULL;
  71470. }
  71471. } else {
  71472. allocationCallbacks.pUserData = NULL;
  71473. allocationCallbacks.onMalloc = drflac__malloc_default;
  71474. allocationCallbacks.onRealloc = drflac__realloc_default;
  71475. allocationCallbacks.onFree = drflac__free_default;
  71476. }
  71477. allocationSize = sizeof(drflac);
  71478. if ((init.maxBlockSizeInPCMFrames % (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) == 0) {
  71479. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32)));
  71480. } else {
  71481. wholeSIMDVectorCountPerChannel = (init.maxBlockSizeInPCMFrames / (DRFLAC_MAX_SIMD_VECTOR_SIZE / sizeof(drflac_int32))) + 1;
  71482. }
  71483. decodedSamplesAllocationSize = wholeSIMDVectorCountPerChannel * DRFLAC_MAX_SIMD_VECTOR_SIZE * init.channels;
  71484. allocationSize += decodedSamplesAllocationSize;
  71485. allocationSize += DRFLAC_MAX_SIMD_VECTOR_SIZE;
  71486. #ifndef DR_FLAC_NO_OGG
  71487. if (init.container == drflac_container_ogg) {
  71488. allocationSize += sizeof(drflac_oggbs);
  71489. pOggbs = (drflac_oggbs*)drflac__malloc_from_callbacks(sizeof(*pOggbs), &allocationCallbacks);
  71490. if (pOggbs == NULL) {
  71491. return NULL;
  71492. }
  71493. DRFLAC_ZERO_MEMORY(pOggbs, sizeof(*pOggbs));
  71494. pOggbs->onRead = onRead;
  71495. pOggbs->onSeek = onSeek;
  71496. pOggbs->pUserData = pUserData;
  71497. pOggbs->currentBytePos = init.oggFirstBytePos;
  71498. pOggbs->firstBytePos = init.oggFirstBytePos;
  71499. pOggbs->serialNumber = init.oggSerial;
  71500. pOggbs->bosPageHeader = init.oggBosHeader;
  71501. pOggbs->bytesRemainingInPage = 0;
  71502. }
  71503. #endif
  71504. firstFramePos = 42;
  71505. seektablePos = 0;
  71506. seekpointCount = 0;
  71507. if (init.hasMetadataBlocks) {
  71508. drflac_read_proc onReadOverride = onRead;
  71509. drflac_seek_proc onSeekOverride = onSeek;
  71510. void* pUserDataOverride = pUserData;
  71511. #ifndef DR_FLAC_NO_OGG
  71512. if (init.container == drflac_container_ogg) {
  71513. onReadOverride = drflac__on_read_ogg;
  71514. onSeekOverride = drflac__on_seek_ogg;
  71515. pUserDataOverride = (void*)pOggbs;
  71516. }
  71517. #endif
  71518. if (!drflac__read_and_decode_metadata(onReadOverride, onSeekOverride, onMeta, pUserDataOverride, pUserDataMD, &firstFramePos, &seektablePos, &seekpointCount, &allocationCallbacks)) {
  71519. #ifndef DR_FLAC_NO_OGG
  71520. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  71521. #endif
  71522. return NULL;
  71523. }
  71524. allocationSize += seekpointCount * sizeof(drflac_seekpoint);
  71525. }
  71526. pFlac = (drflac*)drflac__malloc_from_callbacks(allocationSize, &allocationCallbacks);
  71527. if (pFlac == NULL) {
  71528. #ifndef DR_FLAC_NO_OGG
  71529. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  71530. #endif
  71531. return NULL;
  71532. }
  71533. drflac__init_from_info(pFlac, &init);
  71534. pFlac->allocationCallbacks = allocationCallbacks;
  71535. pFlac->pDecodedSamples = (drflac_int32*)drflac_align((size_t)pFlac->pExtraData, DRFLAC_MAX_SIMD_VECTOR_SIZE);
  71536. #ifndef DR_FLAC_NO_OGG
  71537. if (init.container == drflac_container_ogg) {
  71538. drflac_oggbs* pInternalOggbs = (drflac_oggbs*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize + (seekpointCount * sizeof(drflac_seekpoint)));
  71539. DRFLAC_COPY_MEMORY(pInternalOggbs, pOggbs, sizeof(*pOggbs));
  71540. drflac__free_from_callbacks(pOggbs, &allocationCallbacks);
  71541. pOggbs = NULL;
  71542. pFlac->bs.onRead = drflac__on_read_ogg;
  71543. pFlac->bs.onSeek = drflac__on_seek_ogg;
  71544. pFlac->bs.pUserData = (void*)pInternalOggbs;
  71545. pFlac->_oggbs = (void*)pInternalOggbs;
  71546. }
  71547. #endif
  71548. pFlac->firstFLACFramePosInBytes = firstFramePos;
  71549. #ifndef DR_FLAC_NO_OGG
  71550. if (init.container == drflac_container_ogg)
  71551. {
  71552. pFlac->pSeekpoints = NULL;
  71553. pFlac->seekpointCount = 0;
  71554. }
  71555. else
  71556. #endif
  71557. {
  71558. if (seektablePos != 0) {
  71559. pFlac->seekpointCount = seekpointCount;
  71560. pFlac->pSeekpoints = (drflac_seekpoint*)((drflac_uint8*)pFlac->pDecodedSamples + decodedSamplesAllocationSize);
  71561. DRFLAC_ASSERT(pFlac->bs.onSeek != NULL);
  71562. DRFLAC_ASSERT(pFlac->bs.onRead != NULL);
  71563. if (pFlac->bs.onSeek(pFlac->bs.pUserData, (int)seektablePos, drflac_seek_origin_start)) {
  71564. drflac_uint32 iSeekpoint;
  71565. for (iSeekpoint = 0; iSeekpoint < seekpointCount; iSeekpoint += 1) {
  71566. if (pFlac->bs.onRead(pFlac->bs.pUserData, pFlac->pSeekpoints + iSeekpoint, DRFLAC_SEEKPOINT_SIZE_IN_BYTES) == DRFLAC_SEEKPOINT_SIZE_IN_BYTES) {
  71567. pFlac->pSeekpoints[iSeekpoint].firstPCMFrame = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].firstPCMFrame);
  71568. pFlac->pSeekpoints[iSeekpoint].flacFrameOffset = drflac__be2host_64(pFlac->pSeekpoints[iSeekpoint].flacFrameOffset);
  71569. pFlac->pSeekpoints[iSeekpoint].pcmFrameCount = drflac__be2host_16(pFlac->pSeekpoints[iSeekpoint].pcmFrameCount);
  71570. } else {
  71571. pFlac->pSeekpoints = NULL;
  71572. pFlac->seekpointCount = 0;
  71573. break;
  71574. }
  71575. }
  71576. if (!pFlac->bs.onSeek(pFlac->bs.pUserData, (int)pFlac->firstFLACFramePosInBytes, drflac_seek_origin_start)) {
  71577. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  71578. return NULL;
  71579. }
  71580. } else {
  71581. pFlac->pSeekpoints = NULL;
  71582. pFlac->seekpointCount = 0;
  71583. }
  71584. }
  71585. }
  71586. if (!init.hasStreamInfoBlock) {
  71587. pFlac->currentFLACFrame.header = init.firstFrameHeader;
  71588. for (;;) {
  71589. drflac_result result = drflac__decode_flac_frame(pFlac);
  71590. if (result == DRFLAC_SUCCESS) {
  71591. break;
  71592. } else {
  71593. if (result == DRFLAC_CRC_MISMATCH) {
  71594. if (!drflac__read_next_flac_frame_header(&pFlac->bs, pFlac->bitsPerSample, &pFlac->currentFLACFrame.header)) {
  71595. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  71596. return NULL;
  71597. }
  71598. continue;
  71599. } else {
  71600. drflac__free_from_callbacks(pFlac, &allocationCallbacks);
  71601. return NULL;
  71602. }
  71603. }
  71604. }
  71605. }
  71606. return pFlac;
  71607. }
  71608. #ifndef DR_FLAC_NO_STDIO
  71609. #include <stdio.h>
  71610. #ifndef DR_FLAC_NO_WCHAR
  71611. #include <wchar.h>
  71612. #endif
  71613. #include <errno.h>
  71614. static drflac_result drflac_result_from_errno(int e)
  71615. {
  71616. switch (e)
  71617. {
  71618. case 0: return DRFLAC_SUCCESS;
  71619. #ifdef EPERM
  71620. case EPERM: return DRFLAC_INVALID_OPERATION;
  71621. #endif
  71622. #ifdef ENOENT
  71623. case ENOENT: return DRFLAC_DOES_NOT_EXIST;
  71624. #endif
  71625. #ifdef ESRCH
  71626. case ESRCH: return DRFLAC_DOES_NOT_EXIST;
  71627. #endif
  71628. #ifdef EINTR
  71629. case EINTR: return DRFLAC_INTERRUPT;
  71630. #endif
  71631. #ifdef EIO
  71632. case EIO: return DRFLAC_IO_ERROR;
  71633. #endif
  71634. #ifdef ENXIO
  71635. case ENXIO: return DRFLAC_DOES_NOT_EXIST;
  71636. #endif
  71637. #ifdef E2BIG
  71638. case E2BIG: return DRFLAC_INVALID_ARGS;
  71639. #endif
  71640. #ifdef ENOEXEC
  71641. case ENOEXEC: return DRFLAC_INVALID_FILE;
  71642. #endif
  71643. #ifdef EBADF
  71644. case EBADF: return DRFLAC_INVALID_FILE;
  71645. #endif
  71646. #ifdef ECHILD
  71647. case ECHILD: return DRFLAC_ERROR;
  71648. #endif
  71649. #ifdef EAGAIN
  71650. case EAGAIN: return DRFLAC_UNAVAILABLE;
  71651. #endif
  71652. #ifdef ENOMEM
  71653. case ENOMEM: return DRFLAC_OUT_OF_MEMORY;
  71654. #endif
  71655. #ifdef EACCES
  71656. case EACCES: return DRFLAC_ACCESS_DENIED;
  71657. #endif
  71658. #ifdef EFAULT
  71659. case EFAULT: return DRFLAC_BAD_ADDRESS;
  71660. #endif
  71661. #ifdef ENOTBLK
  71662. case ENOTBLK: return DRFLAC_ERROR;
  71663. #endif
  71664. #ifdef EBUSY
  71665. case EBUSY: return DRFLAC_BUSY;
  71666. #endif
  71667. #ifdef EEXIST
  71668. case EEXIST: return DRFLAC_ALREADY_EXISTS;
  71669. #endif
  71670. #ifdef EXDEV
  71671. case EXDEV: return DRFLAC_ERROR;
  71672. #endif
  71673. #ifdef ENODEV
  71674. case ENODEV: return DRFLAC_DOES_NOT_EXIST;
  71675. #endif
  71676. #ifdef ENOTDIR
  71677. case ENOTDIR: return DRFLAC_NOT_DIRECTORY;
  71678. #endif
  71679. #ifdef EISDIR
  71680. case EISDIR: return DRFLAC_IS_DIRECTORY;
  71681. #endif
  71682. #ifdef EINVAL
  71683. case EINVAL: return DRFLAC_INVALID_ARGS;
  71684. #endif
  71685. #ifdef ENFILE
  71686. case ENFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  71687. #endif
  71688. #ifdef EMFILE
  71689. case EMFILE: return DRFLAC_TOO_MANY_OPEN_FILES;
  71690. #endif
  71691. #ifdef ENOTTY
  71692. case ENOTTY: return DRFLAC_INVALID_OPERATION;
  71693. #endif
  71694. #ifdef ETXTBSY
  71695. case ETXTBSY: return DRFLAC_BUSY;
  71696. #endif
  71697. #ifdef EFBIG
  71698. case EFBIG: return DRFLAC_TOO_BIG;
  71699. #endif
  71700. #ifdef ENOSPC
  71701. case ENOSPC: return DRFLAC_NO_SPACE;
  71702. #endif
  71703. #ifdef ESPIPE
  71704. case ESPIPE: return DRFLAC_BAD_SEEK;
  71705. #endif
  71706. #ifdef EROFS
  71707. case EROFS: return DRFLAC_ACCESS_DENIED;
  71708. #endif
  71709. #ifdef EMLINK
  71710. case EMLINK: return DRFLAC_TOO_MANY_LINKS;
  71711. #endif
  71712. #ifdef EPIPE
  71713. case EPIPE: return DRFLAC_BAD_PIPE;
  71714. #endif
  71715. #ifdef EDOM
  71716. case EDOM: return DRFLAC_OUT_OF_RANGE;
  71717. #endif
  71718. #ifdef ERANGE
  71719. case ERANGE: return DRFLAC_OUT_OF_RANGE;
  71720. #endif
  71721. #ifdef EDEADLK
  71722. case EDEADLK: return DRFLAC_DEADLOCK;
  71723. #endif
  71724. #ifdef ENAMETOOLONG
  71725. case ENAMETOOLONG: return DRFLAC_PATH_TOO_LONG;
  71726. #endif
  71727. #ifdef ENOLCK
  71728. case ENOLCK: return DRFLAC_ERROR;
  71729. #endif
  71730. #ifdef ENOSYS
  71731. case ENOSYS: return DRFLAC_NOT_IMPLEMENTED;
  71732. #endif
  71733. #ifdef ENOTEMPTY
  71734. case ENOTEMPTY: return DRFLAC_DIRECTORY_NOT_EMPTY;
  71735. #endif
  71736. #ifdef ELOOP
  71737. case ELOOP: return DRFLAC_TOO_MANY_LINKS;
  71738. #endif
  71739. #ifdef ENOMSG
  71740. case ENOMSG: return DRFLAC_NO_MESSAGE;
  71741. #endif
  71742. #ifdef EIDRM
  71743. case EIDRM: return DRFLAC_ERROR;
  71744. #endif
  71745. #ifdef ECHRNG
  71746. case ECHRNG: return DRFLAC_ERROR;
  71747. #endif
  71748. #ifdef EL2NSYNC
  71749. case EL2NSYNC: return DRFLAC_ERROR;
  71750. #endif
  71751. #ifdef EL3HLT
  71752. case EL3HLT: return DRFLAC_ERROR;
  71753. #endif
  71754. #ifdef EL3RST
  71755. case EL3RST: return DRFLAC_ERROR;
  71756. #endif
  71757. #ifdef ELNRNG
  71758. case ELNRNG: return DRFLAC_OUT_OF_RANGE;
  71759. #endif
  71760. #ifdef EUNATCH
  71761. case EUNATCH: return DRFLAC_ERROR;
  71762. #endif
  71763. #ifdef ENOCSI
  71764. case ENOCSI: return DRFLAC_ERROR;
  71765. #endif
  71766. #ifdef EL2HLT
  71767. case EL2HLT: return DRFLAC_ERROR;
  71768. #endif
  71769. #ifdef EBADE
  71770. case EBADE: return DRFLAC_ERROR;
  71771. #endif
  71772. #ifdef EBADR
  71773. case EBADR: return DRFLAC_ERROR;
  71774. #endif
  71775. #ifdef EXFULL
  71776. case EXFULL: return DRFLAC_ERROR;
  71777. #endif
  71778. #ifdef ENOANO
  71779. case ENOANO: return DRFLAC_ERROR;
  71780. #endif
  71781. #ifdef EBADRQC
  71782. case EBADRQC: return DRFLAC_ERROR;
  71783. #endif
  71784. #ifdef EBADSLT
  71785. case EBADSLT: return DRFLAC_ERROR;
  71786. #endif
  71787. #ifdef EBFONT
  71788. case EBFONT: return DRFLAC_INVALID_FILE;
  71789. #endif
  71790. #ifdef ENOSTR
  71791. case ENOSTR: return DRFLAC_ERROR;
  71792. #endif
  71793. #ifdef ENODATA
  71794. case ENODATA: return DRFLAC_NO_DATA_AVAILABLE;
  71795. #endif
  71796. #ifdef ETIME
  71797. case ETIME: return DRFLAC_TIMEOUT;
  71798. #endif
  71799. #ifdef ENOSR
  71800. case ENOSR: return DRFLAC_NO_DATA_AVAILABLE;
  71801. #endif
  71802. #ifdef ENONET
  71803. case ENONET: return DRFLAC_NO_NETWORK;
  71804. #endif
  71805. #ifdef ENOPKG
  71806. case ENOPKG: return DRFLAC_ERROR;
  71807. #endif
  71808. #ifdef EREMOTE
  71809. case EREMOTE: return DRFLAC_ERROR;
  71810. #endif
  71811. #ifdef ENOLINK
  71812. case ENOLINK: return DRFLAC_ERROR;
  71813. #endif
  71814. #ifdef EADV
  71815. case EADV: return DRFLAC_ERROR;
  71816. #endif
  71817. #ifdef ESRMNT
  71818. case ESRMNT: return DRFLAC_ERROR;
  71819. #endif
  71820. #ifdef ECOMM
  71821. case ECOMM: return DRFLAC_ERROR;
  71822. #endif
  71823. #ifdef EPROTO
  71824. case EPROTO: return DRFLAC_ERROR;
  71825. #endif
  71826. #ifdef EMULTIHOP
  71827. case EMULTIHOP: return DRFLAC_ERROR;
  71828. #endif
  71829. #ifdef EDOTDOT
  71830. case EDOTDOT: return DRFLAC_ERROR;
  71831. #endif
  71832. #ifdef EBADMSG
  71833. case EBADMSG: return DRFLAC_BAD_MESSAGE;
  71834. #endif
  71835. #ifdef EOVERFLOW
  71836. case EOVERFLOW: return DRFLAC_TOO_BIG;
  71837. #endif
  71838. #ifdef ENOTUNIQ
  71839. case ENOTUNIQ: return DRFLAC_NOT_UNIQUE;
  71840. #endif
  71841. #ifdef EBADFD
  71842. case EBADFD: return DRFLAC_ERROR;
  71843. #endif
  71844. #ifdef EREMCHG
  71845. case EREMCHG: return DRFLAC_ERROR;
  71846. #endif
  71847. #ifdef ELIBACC
  71848. case ELIBACC: return DRFLAC_ACCESS_DENIED;
  71849. #endif
  71850. #ifdef ELIBBAD
  71851. case ELIBBAD: return DRFLAC_INVALID_FILE;
  71852. #endif
  71853. #ifdef ELIBSCN
  71854. case ELIBSCN: return DRFLAC_INVALID_FILE;
  71855. #endif
  71856. #ifdef ELIBMAX
  71857. case ELIBMAX: return DRFLAC_ERROR;
  71858. #endif
  71859. #ifdef ELIBEXEC
  71860. case ELIBEXEC: return DRFLAC_ERROR;
  71861. #endif
  71862. #ifdef EILSEQ
  71863. case EILSEQ: return DRFLAC_INVALID_DATA;
  71864. #endif
  71865. #ifdef ERESTART
  71866. case ERESTART: return DRFLAC_ERROR;
  71867. #endif
  71868. #ifdef ESTRPIPE
  71869. case ESTRPIPE: return DRFLAC_ERROR;
  71870. #endif
  71871. #ifdef EUSERS
  71872. case EUSERS: return DRFLAC_ERROR;
  71873. #endif
  71874. #ifdef ENOTSOCK
  71875. case ENOTSOCK: return DRFLAC_NOT_SOCKET;
  71876. #endif
  71877. #ifdef EDESTADDRREQ
  71878. case EDESTADDRREQ: return DRFLAC_NO_ADDRESS;
  71879. #endif
  71880. #ifdef EMSGSIZE
  71881. case EMSGSIZE: return DRFLAC_TOO_BIG;
  71882. #endif
  71883. #ifdef EPROTOTYPE
  71884. case EPROTOTYPE: return DRFLAC_BAD_PROTOCOL;
  71885. #endif
  71886. #ifdef ENOPROTOOPT
  71887. case ENOPROTOOPT: return DRFLAC_PROTOCOL_UNAVAILABLE;
  71888. #endif
  71889. #ifdef EPROTONOSUPPORT
  71890. case EPROTONOSUPPORT: return DRFLAC_PROTOCOL_NOT_SUPPORTED;
  71891. #endif
  71892. #ifdef ESOCKTNOSUPPORT
  71893. case ESOCKTNOSUPPORT: return DRFLAC_SOCKET_NOT_SUPPORTED;
  71894. #endif
  71895. #ifdef EOPNOTSUPP
  71896. case EOPNOTSUPP: return DRFLAC_INVALID_OPERATION;
  71897. #endif
  71898. #ifdef EPFNOSUPPORT
  71899. case EPFNOSUPPORT: return DRFLAC_PROTOCOL_FAMILY_NOT_SUPPORTED;
  71900. #endif
  71901. #ifdef EAFNOSUPPORT
  71902. case EAFNOSUPPORT: return DRFLAC_ADDRESS_FAMILY_NOT_SUPPORTED;
  71903. #endif
  71904. #ifdef EADDRINUSE
  71905. case EADDRINUSE: return DRFLAC_ALREADY_IN_USE;
  71906. #endif
  71907. #ifdef EADDRNOTAVAIL
  71908. case EADDRNOTAVAIL: return DRFLAC_ERROR;
  71909. #endif
  71910. #ifdef ENETDOWN
  71911. case ENETDOWN: return DRFLAC_NO_NETWORK;
  71912. #endif
  71913. #ifdef ENETUNREACH
  71914. case ENETUNREACH: return DRFLAC_NO_NETWORK;
  71915. #endif
  71916. #ifdef ENETRESET
  71917. case ENETRESET: return DRFLAC_NO_NETWORK;
  71918. #endif
  71919. #ifdef ECONNABORTED
  71920. case ECONNABORTED: return DRFLAC_NO_NETWORK;
  71921. #endif
  71922. #ifdef ECONNRESET
  71923. case ECONNRESET: return DRFLAC_CONNECTION_RESET;
  71924. #endif
  71925. #ifdef ENOBUFS
  71926. case ENOBUFS: return DRFLAC_NO_SPACE;
  71927. #endif
  71928. #ifdef EISCONN
  71929. case EISCONN: return DRFLAC_ALREADY_CONNECTED;
  71930. #endif
  71931. #ifdef ENOTCONN
  71932. case ENOTCONN: return DRFLAC_NOT_CONNECTED;
  71933. #endif
  71934. #ifdef ESHUTDOWN
  71935. case ESHUTDOWN: return DRFLAC_ERROR;
  71936. #endif
  71937. #ifdef ETOOMANYREFS
  71938. case ETOOMANYREFS: return DRFLAC_ERROR;
  71939. #endif
  71940. #ifdef ETIMEDOUT
  71941. case ETIMEDOUT: return DRFLAC_TIMEOUT;
  71942. #endif
  71943. #ifdef ECONNREFUSED
  71944. case ECONNREFUSED: return DRFLAC_CONNECTION_REFUSED;
  71945. #endif
  71946. #ifdef EHOSTDOWN
  71947. case EHOSTDOWN: return DRFLAC_NO_HOST;
  71948. #endif
  71949. #ifdef EHOSTUNREACH
  71950. case EHOSTUNREACH: return DRFLAC_NO_HOST;
  71951. #endif
  71952. #ifdef EALREADY
  71953. case EALREADY: return DRFLAC_IN_PROGRESS;
  71954. #endif
  71955. #ifdef EINPROGRESS
  71956. case EINPROGRESS: return DRFLAC_IN_PROGRESS;
  71957. #endif
  71958. #ifdef ESTALE
  71959. case ESTALE: return DRFLAC_INVALID_FILE;
  71960. #endif
  71961. #ifdef EUCLEAN
  71962. case EUCLEAN: return DRFLAC_ERROR;
  71963. #endif
  71964. #ifdef ENOTNAM
  71965. case ENOTNAM: return DRFLAC_ERROR;
  71966. #endif
  71967. #ifdef ENAVAIL
  71968. case ENAVAIL: return DRFLAC_ERROR;
  71969. #endif
  71970. #ifdef EISNAM
  71971. case EISNAM: return DRFLAC_ERROR;
  71972. #endif
  71973. #ifdef EREMOTEIO
  71974. case EREMOTEIO: return DRFLAC_IO_ERROR;
  71975. #endif
  71976. #ifdef EDQUOT
  71977. case EDQUOT: return DRFLAC_NO_SPACE;
  71978. #endif
  71979. #ifdef ENOMEDIUM
  71980. case ENOMEDIUM: return DRFLAC_DOES_NOT_EXIST;
  71981. #endif
  71982. #ifdef EMEDIUMTYPE
  71983. case EMEDIUMTYPE: return DRFLAC_ERROR;
  71984. #endif
  71985. #ifdef ECANCELED
  71986. case ECANCELED: return DRFLAC_CANCELLED;
  71987. #endif
  71988. #ifdef ENOKEY
  71989. case ENOKEY: return DRFLAC_ERROR;
  71990. #endif
  71991. #ifdef EKEYEXPIRED
  71992. case EKEYEXPIRED: return DRFLAC_ERROR;
  71993. #endif
  71994. #ifdef EKEYREVOKED
  71995. case EKEYREVOKED: return DRFLAC_ERROR;
  71996. #endif
  71997. #ifdef EKEYREJECTED
  71998. case EKEYREJECTED: return DRFLAC_ERROR;
  71999. #endif
  72000. #ifdef EOWNERDEAD
  72001. case EOWNERDEAD: return DRFLAC_ERROR;
  72002. #endif
  72003. #ifdef ENOTRECOVERABLE
  72004. case ENOTRECOVERABLE: return DRFLAC_ERROR;
  72005. #endif
  72006. #ifdef ERFKILL
  72007. case ERFKILL: return DRFLAC_ERROR;
  72008. #endif
  72009. #ifdef EHWPOISON
  72010. case EHWPOISON: return DRFLAC_ERROR;
  72011. #endif
  72012. default: return DRFLAC_ERROR;
  72013. }
  72014. }
  72015. static drflac_result drflac_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  72016. {
  72017. #if defined(_MSC_VER) && _MSC_VER >= 1400
  72018. errno_t err;
  72019. #endif
  72020. if (ppFile != NULL) {
  72021. *ppFile = NULL;
  72022. }
  72023. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  72024. return DRFLAC_INVALID_ARGS;
  72025. }
  72026. #if defined(_MSC_VER) && _MSC_VER >= 1400
  72027. err = fopen_s(ppFile, pFilePath, pOpenMode);
  72028. if (err != 0) {
  72029. return drflac_result_from_errno(err);
  72030. }
  72031. #else
  72032. #if defined(_WIN32) || defined(__APPLE__)
  72033. *ppFile = fopen(pFilePath, pOpenMode);
  72034. #else
  72035. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  72036. *ppFile = fopen64(pFilePath, pOpenMode);
  72037. #else
  72038. *ppFile = fopen(pFilePath, pOpenMode);
  72039. #endif
  72040. #endif
  72041. if (*ppFile == NULL) {
  72042. drflac_result result = drflac_result_from_errno(errno);
  72043. if (result == DRFLAC_SUCCESS) {
  72044. result = DRFLAC_ERROR;
  72045. }
  72046. return result;
  72047. }
  72048. #endif
  72049. return DRFLAC_SUCCESS;
  72050. }
  72051. #if defined(_WIN32)
  72052. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  72053. #define DRFLAC_HAS_WFOPEN
  72054. #endif
  72055. #endif
  72056. #ifndef DR_FLAC_NO_WCHAR
  72057. static drflac_result drflac_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drflac_allocation_callbacks* pAllocationCallbacks)
  72058. {
  72059. if (ppFile != NULL) {
  72060. *ppFile = NULL;
  72061. }
  72062. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  72063. return DRFLAC_INVALID_ARGS;
  72064. }
  72065. #if defined(DRFLAC_HAS_WFOPEN)
  72066. {
  72067. #if defined(_MSC_VER) && _MSC_VER >= 1400
  72068. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  72069. if (err != 0) {
  72070. return drflac_result_from_errno(err);
  72071. }
  72072. #else
  72073. *ppFile = _wfopen(pFilePath, pOpenMode);
  72074. if (*ppFile == NULL) {
  72075. return drflac_result_from_errno(errno);
  72076. }
  72077. #endif
  72078. (void)pAllocationCallbacks;
  72079. }
  72080. #else
  72081. #if defined(__DJGPP__)
  72082. {
  72083. }
  72084. #else
  72085. {
  72086. mbstate_t mbs;
  72087. size_t lenMB;
  72088. const wchar_t* pFilePathTemp = pFilePath;
  72089. char* pFilePathMB = NULL;
  72090. char pOpenModeMB[32] = {0};
  72091. DRFLAC_ZERO_OBJECT(&mbs);
  72092. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  72093. if (lenMB == (size_t)-1) {
  72094. return drflac_result_from_errno(errno);
  72095. }
  72096. pFilePathMB = (char*)drflac__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  72097. if (pFilePathMB == NULL) {
  72098. return DRFLAC_OUT_OF_MEMORY;
  72099. }
  72100. pFilePathTemp = pFilePath;
  72101. DRFLAC_ZERO_OBJECT(&mbs);
  72102. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  72103. {
  72104. size_t i = 0;
  72105. for (;;) {
  72106. if (pOpenMode[i] == 0) {
  72107. pOpenModeMB[i] = '\0';
  72108. break;
  72109. }
  72110. pOpenModeMB[i] = (char)pOpenMode[i];
  72111. i += 1;
  72112. }
  72113. }
  72114. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  72115. drflac__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  72116. }
  72117. #endif
  72118. if (*ppFile == NULL) {
  72119. return DRFLAC_ERROR;
  72120. }
  72121. #endif
  72122. return DRFLAC_SUCCESS;
  72123. }
  72124. #endif
  72125. static size_t drflac__on_read_stdio(void* pUserData, void* bufferOut, size_t bytesToRead)
  72126. {
  72127. return fread(bufferOut, 1, bytesToRead, (FILE*)pUserData);
  72128. }
  72129. static drflac_bool32 drflac__on_seek_stdio(void* pUserData, int offset, drflac_seek_origin origin)
  72130. {
  72131. DRFLAC_ASSERT(offset >= 0);
  72132. return fseek((FILE*)pUserData, offset, (origin == drflac_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  72133. }
  72134. DRFLAC_API drflac* drflac_open_file(const char* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  72135. {
  72136. drflac* pFlac;
  72137. FILE* pFile;
  72138. if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  72139. return NULL;
  72140. }
  72141. pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  72142. if (pFlac == NULL) {
  72143. fclose(pFile);
  72144. return NULL;
  72145. }
  72146. return pFlac;
  72147. }
  72148. #ifndef DR_FLAC_NO_WCHAR
  72149. DRFLAC_API drflac* drflac_open_file_w(const wchar_t* pFileName, const drflac_allocation_callbacks* pAllocationCallbacks)
  72150. {
  72151. drflac* pFlac;
  72152. FILE* pFile;
  72153. if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  72154. return NULL;
  72155. }
  72156. pFlac = drflac_open(drflac__on_read_stdio, drflac__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  72157. if (pFlac == NULL) {
  72158. fclose(pFile);
  72159. return NULL;
  72160. }
  72161. return pFlac;
  72162. }
  72163. #endif
  72164. DRFLAC_API drflac* drflac_open_file_with_metadata(const char* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72165. {
  72166. drflac* pFlac;
  72167. FILE* pFile;
  72168. if (drflac_fopen(&pFile, pFileName, "rb") != DRFLAC_SUCCESS) {
  72169. return NULL;
  72170. }
  72171. pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  72172. if (pFlac == NULL) {
  72173. fclose(pFile);
  72174. return pFlac;
  72175. }
  72176. return pFlac;
  72177. }
  72178. #ifndef DR_FLAC_NO_WCHAR
  72179. DRFLAC_API drflac* drflac_open_file_with_metadata_w(const wchar_t* pFileName, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72180. {
  72181. drflac* pFlac;
  72182. FILE* pFile;
  72183. if (drflac_wfopen(&pFile, pFileName, L"rb", pAllocationCallbacks) != DRFLAC_SUCCESS) {
  72184. return NULL;
  72185. }
  72186. pFlac = drflac_open_with_metadata_private(drflac__on_read_stdio, drflac__on_seek_stdio, onMeta, drflac_container_unknown, (void*)pFile, pUserData, pAllocationCallbacks);
  72187. if (pFlac == NULL) {
  72188. fclose(pFile);
  72189. return pFlac;
  72190. }
  72191. return pFlac;
  72192. }
  72193. #endif
  72194. #endif
  72195. static size_t drflac__on_read_memory(void* pUserData, void* bufferOut, size_t bytesToRead)
  72196. {
  72197. drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  72198. size_t bytesRemaining;
  72199. DRFLAC_ASSERT(memoryStream != NULL);
  72200. DRFLAC_ASSERT(memoryStream->dataSize >= memoryStream->currentReadPos);
  72201. bytesRemaining = memoryStream->dataSize - memoryStream->currentReadPos;
  72202. if (bytesToRead > bytesRemaining) {
  72203. bytesToRead = bytesRemaining;
  72204. }
  72205. if (bytesToRead > 0) {
  72206. DRFLAC_COPY_MEMORY(bufferOut, memoryStream->data + memoryStream->currentReadPos, bytesToRead);
  72207. memoryStream->currentReadPos += bytesToRead;
  72208. }
  72209. return bytesToRead;
  72210. }
  72211. static drflac_bool32 drflac__on_seek_memory(void* pUserData, int offset, drflac_seek_origin origin)
  72212. {
  72213. drflac__memory_stream* memoryStream = (drflac__memory_stream*)pUserData;
  72214. DRFLAC_ASSERT(memoryStream != NULL);
  72215. DRFLAC_ASSERT(offset >= 0);
  72216. if (offset > (drflac_int64)memoryStream->dataSize) {
  72217. return DRFLAC_FALSE;
  72218. }
  72219. if (origin == drflac_seek_origin_current) {
  72220. if (memoryStream->currentReadPos + offset <= memoryStream->dataSize) {
  72221. memoryStream->currentReadPos += offset;
  72222. } else {
  72223. return DRFLAC_FALSE;
  72224. }
  72225. } else {
  72226. if ((drflac_uint32)offset <= memoryStream->dataSize) {
  72227. memoryStream->currentReadPos = offset;
  72228. } else {
  72229. return DRFLAC_FALSE;
  72230. }
  72231. }
  72232. return DRFLAC_TRUE;
  72233. }
  72234. DRFLAC_API drflac* drflac_open_memory(const void* pData, size_t dataSize, const drflac_allocation_callbacks* pAllocationCallbacks)
  72235. {
  72236. drflac__memory_stream memoryStream;
  72237. drflac* pFlac;
  72238. memoryStream.data = (const drflac_uint8*)pData;
  72239. memoryStream.dataSize = dataSize;
  72240. memoryStream.currentReadPos = 0;
  72241. pFlac = drflac_open(drflac__on_read_memory, drflac__on_seek_memory, &memoryStream, pAllocationCallbacks);
  72242. if (pFlac == NULL) {
  72243. return NULL;
  72244. }
  72245. pFlac->memoryStream = memoryStream;
  72246. #ifndef DR_FLAC_NO_OGG
  72247. if (pFlac->container == drflac_container_ogg)
  72248. {
  72249. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  72250. oggbs->pUserData = &pFlac->memoryStream;
  72251. }
  72252. else
  72253. #endif
  72254. {
  72255. pFlac->bs.pUserData = &pFlac->memoryStream;
  72256. }
  72257. return pFlac;
  72258. }
  72259. DRFLAC_API drflac* drflac_open_memory_with_metadata(const void* pData, size_t dataSize, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72260. {
  72261. drflac__memory_stream memoryStream;
  72262. drflac* pFlac;
  72263. memoryStream.data = (const drflac_uint8*)pData;
  72264. memoryStream.dataSize = dataSize;
  72265. memoryStream.currentReadPos = 0;
  72266. pFlac = drflac_open_with_metadata_private(drflac__on_read_memory, drflac__on_seek_memory, onMeta, drflac_container_unknown, &memoryStream, pUserData, pAllocationCallbacks);
  72267. if (pFlac == NULL) {
  72268. return NULL;
  72269. }
  72270. pFlac->memoryStream = memoryStream;
  72271. #ifndef DR_FLAC_NO_OGG
  72272. if (pFlac->container == drflac_container_ogg)
  72273. {
  72274. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  72275. oggbs->pUserData = &pFlac->memoryStream;
  72276. }
  72277. else
  72278. #endif
  72279. {
  72280. pFlac->bs.pUserData = &pFlac->memoryStream;
  72281. }
  72282. return pFlac;
  72283. }
  72284. DRFLAC_API drflac* drflac_open(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72285. {
  72286. return drflac_open_with_metadata_private(onRead, onSeek, NULL, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  72287. }
  72288. DRFLAC_API drflac* drflac_open_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72289. {
  72290. return drflac_open_with_metadata_private(onRead, onSeek, NULL, container, pUserData, pUserData, pAllocationCallbacks);
  72291. }
  72292. DRFLAC_API drflac* drflac_open_with_metadata(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72293. {
  72294. return drflac_open_with_metadata_private(onRead, onSeek, onMeta, drflac_container_unknown, pUserData, pUserData, pAllocationCallbacks);
  72295. }
  72296. DRFLAC_API drflac* drflac_open_with_metadata_relaxed(drflac_read_proc onRead, drflac_seek_proc onSeek, drflac_meta_proc onMeta, drflac_container container, void* pUserData, const drflac_allocation_callbacks* pAllocationCallbacks)
  72297. {
  72298. return drflac_open_with_metadata_private(onRead, onSeek, onMeta, container, pUserData, pUserData, pAllocationCallbacks);
  72299. }
  72300. DRFLAC_API void drflac_close(drflac* pFlac)
  72301. {
  72302. if (pFlac == NULL) {
  72303. return;
  72304. }
  72305. #ifndef DR_FLAC_NO_STDIO
  72306. if (pFlac->bs.onRead == drflac__on_read_stdio) {
  72307. fclose((FILE*)pFlac->bs.pUserData);
  72308. }
  72309. #ifndef DR_FLAC_NO_OGG
  72310. if (pFlac->container == drflac_container_ogg) {
  72311. drflac_oggbs* oggbs = (drflac_oggbs*)pFlac->_oggbs;
  72312. DRFLAC_ASSERT(pFlac->bs.onRead == drflac__on_read_ogg);
  72313. if (oggbs->onRead == drflac__on_read_stdio) {
  72314. fclose((FILE*)oggbs->pUserData);
  72315. }
  72316. }
  72317. #endif
  72318. #endif
  72319. drflac__free_from_callbacks(pFlac, &pFlac->allocationCallbacks);
  72320. }
  72321. #if 0
  72322. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72323. {
  72324. drflac_uint64 i;
  72325. for (i = 0; i < frameCount; ++i) {
  72326. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72327. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72328. drflac_uint32 right = left - side;
  72329. pOutputSamples[i*2+0] = (drflac_int32)left;
  72330. pOutputSamples[i*2+1] = (drflac_int32)right;
  72331. }
  72332. }
  72333. #endif
  72334. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72335. {
  72336. drflac_uint64 i;
  72337. drflac_uint64 frameCount4 = frameCount >> 2;
  72338. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72339. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72340. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72341. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72342. for (i = 0; i < frameCount4; ++i) {
  72343. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  72344. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  72345. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  72346. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  72347. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  72348. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  72349. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  72350. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  72351. drflac_uint32 right0 = left0 - side0;
  72352. drflac_uint32 right1 = left1 - side1;
  72353. drflac_uint32 right2 = left2 - side2;
  72354. drflac_uint32 right3 = left3 - side3;
  72355. pOutputSamples[i*8+0] = (drflac_int32)left0;
  72356. pOutputSamples[i*8+1] = (drflac_int32)right0;
  72357. pOutputSamples[i*8+2] = (drflac_int32)left1;
  72358. pOutputSamples[i*8+3] = (drflac_int32)right1;
  72359. pOutputSamples[i*8+4] = (drflac_int32)left2;
  72360. pOutputSamples[i*8+5] = (drflac_int32)right2;
  72361. pOutputSamples[i*8+6] = (drflac_int32)left3;
  72362. pOutputSamples[i*8+7] = (drflac_int32)right3;
  72363. }
  72364. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72365. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  72366. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  72367. drflac_uint32 right = left - side;
  72368. pOutputSamples[i*2+0] = (drflac_int32)left;
  72369. pOutputSamples[i*2+1] = (drflac_int32)right;
  72370. }
  72371. }
  72372. #if defined(DRFLAC_SUPPORT_SSE2)
  72373. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72374. {
  72375. drflac_uint64 i;
  72376. drflac_uint64 frameCount4 = frameCount >> 2;
  72377. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72378. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72379. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72380. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72381. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72382. for (i = 0; i < frameCount4; ++i) {
  72383. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  72384. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  72385. __m128i right = _mm_sub_epi32(left, side);
  72386. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  72387. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  72388. }
  72389. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72390. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  72391. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  72392. drflac_uint32 right = left - side;
  72393. pOutputSamples[i*2+0] = (drflac_int32)left;
  72394. pOutputSamples[i*2+1] = (drflac_int32)right;
  72395. }
  72396. }
  72397. #endif
  72398. #if defined(DRFLAC_SUPPORT_NEON)
  72399. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72400. {
  72401. drflac_uint64 i;
  72402. drflac_uint64 frameCount4 = frameCount >> 2;
  72403. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72404. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72405. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72406. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72407. int32x4_t shift0_4;
  72408. int32x4_t shift1_4;
  72409. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72410. shift0_4 = vdupq_n_s32(shift0);
  72411. shift1_4 = vdupq_n_s32(shift1);
  72412. for (i = 0; i < frameCount4; ++i) {
  72413. uint32x4_t left;
  72414. uint32x4_t side;
  72415. uint32x4_t right;
  72416. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  72417. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  72418. right = vsubq_u32(left, side);
  72419. drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  72420. }
  72421. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72422. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  72423. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  72424. drflac_uint32 right = left - side;
  72425. pOutputSamples[i*2+0] = (drflac_int32)left;
  72426. pOutputSamples[i*2+1] = (drflac_int32)right;
  72427. }
  72428. }
  72429. #endif
  72430. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72431. {
  72432. #if defined(DRFLAC_SUPPORT_SSE2)
  72433. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  72434. drflac_read_pcm_frames_s32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72435. } else
  72436. #elif defined(DRFLAC_SUPPORT_NEON)
  72437. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  72438. drflac_read_pcm_frames_s32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72439. } else
  72440. #endif
  72441. {
  72442. #if 0
  72443. drflac_read_pcm_frames_s32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72444. #else
  72445. drflac_read_pcm_frames_s32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72446. #endif
  72447. }
  72448. }
  72449. #if 0
  72450. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72451. {
  72452. drflac_uint64 i;
  72453. for (i = 0; i < frameCount; ++i) {
  72454. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72455. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72456. drflac_uint32 left = right + side;
  72457. pOutputSamples[i*2+0] = (drflac_int32)left;
  72458. pOutputSamples[i*2+1] = (drflac_int32)right;
  72459. }
  72460. }
  72461. #endif
  72462. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72463. {
  72464. drflac_uint64 i;
  72465. drflac_uint64 frameCount4 = frameCount >> 2;
  72466. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72467. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72468. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72469. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72470. for (i = 0; i < frameCount4; ++i) {
  72471. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  72472. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  72473. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  72474. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  72475. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  72476. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  72477. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  72478. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  72479. drflac_uint32 left0 = right0 + side0;
  72480. drflac_uint32 left1 = right1 + side1;
  72481. drflac_uint32 left2 = right2 + side2;
  72482. drflac_uint32 left3 = right3 + side3;
  72483. pOutputSamples[i*8+0] = (drflac_int32)left0;
  72484. pOutputSamples[i*8+1] = (drflac_int32)right0;
  72485. pOutputSamples[i*8+2] = (drflac_int32)left1;
  72486. pOutputSamples[i*8+3] = (drflac_int32)right1;
  72487. pOutputSamples[i*8+4] = (drflac_int32)left2;
  72488. pOutputSamples[i*8+5] = (drflac_int32)right2;
  72489. pOutputSamples[i*8+6] = (drflac_int32)left3;
  72490. pOutputSamples[i*8+7] = (drflac_int32)right3;
  72491. }
  72492. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72493. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  72494. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  72495. drflac_uint32 left = right + side;
  72496. pOutputSamples[i*2+0] = (drflac_int32)left;
  72497. pOutputSamples[i*2+1] = (drflac_int32)right;
  72498. }
  72499. }
  72500. #if defined(DRFLAC_SUPPORT_SSE2)
  72501. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72502. {
  72503. drflac_uint64 i;
  72504. drflac_uint64 frameCount4 = frameCount >> 2;
  72505. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72506. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72507. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72508. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72509. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72510. for (i = 0; i < frameCount4; ++i) {
  72511. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  72512. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  72513. __m128i left = _mm_add_epi32(right, side);
  72514. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  72515. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  72516. }
  72517. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72518. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  72519. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  72520. drflac_uint32 left = right + side;
  72521. pOutputSamples[i*2+0] = (drflac_int32)left;
  72522. pOutputSamples[i*2+1] = (drflac_int32)right;
  72523. }
  72524. }
  72525. #endif
  72526. #if defined(DRFLAC_SUPPORT_NEON)
  72527. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72528. {
  72529. drflac_uint64 i;
  72530. drflac_uint64 frameCount4 = frameCount >> 2;
  72531. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72532. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72533. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72534. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72535. int32x4_t shift0_4;
  72536. int32x4_t shift1_4;
  72537. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72538. shift0_4 = vdupq_n_s32(shift0);
  72539. shift1_4 = vdupq_n_s32(shift1);
  72540. for (i = 0; i < frameCount4; ++i) {
  72541. uint32x4_t side;
  72542. uint32x4_t right;
  72543. uint32x4_t left;
  72544. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  72545. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  72546. left = vaddq_u32(right, side);
  72547. drflac__vst2q_u32((drflac_uint32*)pOutputSamples + i*8, vzipq_u32(left, right));
  72548. }
  72549. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72550. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  72551. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  72552. drflac_uint32 left = right + side;
  72553. pOutputSamples[i*2+0] = (drflac_int32)left;
  72554. pOutputSamples[i*2+1] = (drflac_int32)right;
  72555. }
  72556. }
  72557. #endif
  72558. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72559. {
  72560. #if defined(DRFLAC_SUPPORT_SSE2)
  72561. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  72562. drflac_read_pcm_frames_s32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72563. } else
  72564. #elif defined(DRFLAC_SUPPORT_NEON)
  72565. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  72566. drflac_read_pcm_frames_s32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72567. } else
  72568. #endif
  72569. {
  72570. #if 0
  72571. drflac_read_pcm_frames_s32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72572. #else
  72573. drflac_read_pcm_frames_s32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72574. #endif
  72575. }
  72576. }
  72577. #if 0
  72578. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72579. {
  72580. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  72581. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72582. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72583. mid = (mid << 1) | (side & 0x01);
  72584. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  72585. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  72586. }
  72587. }
  72588. #endif
  72589. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72590. {
  72591. drflac_uint64 i;
  72592. drflac_uint64 frameCount4 = frameCount >> 2;
  72593. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72594. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72595. drflac_int32 shift = unusedBitsPerSample;
  72596. if (shift > 0) {
  72597. shift -= 1;
  72598. for (i = 0; i < frameCount4; ++i) {
  72599. drflac_uint32 temp0L;
  72600. drflac_uint32 temp1L;
  72601. drflac_uint32 temp2L;
  72602. drflac_uint32 temp3L;
  72603. drflac_uint32 temp0R;
  72604. drflac_uint32 temp1R;
  72605. drflac_uint32 temp2R;
  72606. drflac_uint32 temp3R;
  72607. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72608. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72609. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72610. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72611. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72612. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72613. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72614. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72615. mid0 = (mid0 << 1) | (side0 & 0x01);
  72616. mid1 = (mid1 << 1) | (side1 & 0x01);
  72617. mid2 = (mid2 << 1) | (side2 & 0x01);
  72618. mid3 = (mid3 << 1) | (side3 & 0x01);
  72619. temp0L = (mid0 + side0) << shift;
  72620. temp1L = (mid1 + side1) << shift;
  72621. temp2L = (mid2 + side2) << shift;
  72622. temp3L = (mid3 + side3) << shift;
  72623. temp0R = (mid0 - side0) << shift;
  72624. temp1R = (mid1 - side1) << shift;
  72625. temp2R = (mid2 - side2) << shift;
  72626. temp3R = (mid3 - side3) << shift;
  72627. pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  72628. pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  72629. pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  72630. pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  72631. pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  72632. pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  72633. pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  72634. pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  72635. }
  72636. } else {
  72637. for (i = 0; i < frameCount4; ++i) {
  72638. drflac_uint32 temp0L;
  72639. drflac_uint32 temp1L;
  72640. drflac_uint32 temp2L;
  72641. drflac_uint32 temp3L;
  72642. drflac_uint32 temp0R;
  72643. drflac_uint32 temp1R;
  72644. drflac_uint32 temp2R;
  72645. drflac_uint32 temp3R;
  72646. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72647. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72648. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72649. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72650. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72651. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72652. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72653. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72654. mid0 = (mid0 << 1) | (side0 & 0x01);
  72655. mid1 = (mid1 << 1) | (side1 & 0x01);
  72656. mid2 = (mid2 << 1) | (side2 & 0x01);
  72657. mid3 = (mid3 << 1) | (side3 & 0x01);
  72658. temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  72659. temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  72660. temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  72661. temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  72662. temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  72663. temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  72664. temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  72665. temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  72666. pOutputSamples[i*8+0] = (drflac_int32)temp0L;
  72667. pOutputSamples[i*8+1] = (drflac_int32)temp0R;
  72668. pOutputSamples[i*8+2] = (drflac_int32)temp1L;
  72669. pOutputSamples[i*8+3] = (drflac_int32)temp1R;
  72670. pOutputSamples[i*8+4] = (drflac_int32)temp2L;
  72671. pOutputSamples[i*8+5] = (drflac_int32)temp2R;
  72672. pOutputSamples[i*8+6] = (drflac_int32)temp3L;
  72673. pOutputSamples[i*8+7] = (drflac_int32)temp3R;
  72674. }
  72675. }
  72676. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72677. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72678. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72679. mid = (mid << 1) | (side & 0x01);
  72680. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample);
  72681. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample);
  72682. }
  72683. }
  72684. #if defined(DRFLAC_SUPPORT_SSE2)
  72685. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72686. {
  72687. drflac_uint64 i;
  72688. drflac_uint64 frameCount4 = frameCount >> 2;
  72689. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72690. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72691. drflac_int32 shift = unusedBitsPerSample;
  72692. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72693. if (shift == 0) {
  72694. for (i = 0; i < frameCount4; ++i) {
  72695. __m128i mid;
  72696. __m128i side;
  72697. __m128i left;
  72698. __m128i right;
  72699. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72700. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72701. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  72702. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  72703. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  72704. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  72705. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  72706. }
  72707. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72708. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72709. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72710. mid = (mid << 1) | (side & 0x01);
  72711. pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  72712. pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  72713. }
  72714. } else {
  72715. shift -= 1;
  72716. for (i = 0; i < frameCount4; ++i) {
  72717. __m128i mid;
  72718. __m128i side;
  72719. __m128i left;
  72720. __m128i right;
  72721. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72722. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72723. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  72724. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  72725. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  72726. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  72727. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  72728. }
  72729. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72730. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72731. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72732. mid = (mid << 1) | (side & 0x01);
  72733. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  72734. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  72735. }
  72736. }
  72737. }
  72738. #endif
  72739. #if defined(DRFLAC_SUPPORT_NEON)
  72740. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72741. {
  72742. drflac_uint64 i;
  72743. drflac_uint64 frameCount4 = frameCount >> 2;
  72744. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72745. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72746. drflac_int32 shift = unusedBitsPerSample;
  72747. int32x4_t wbpsShift0_4;
  72748. int32x4_t wbpsShift1_4;
  72749. uint32x4_t one4;
  72750. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  72751. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72752. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72753. one4 = vdupq_n_u32(1);
  72754. if (shift == 0) {
  72755. for (i = 0; i < frameCount4; ++i) {
  72756. uint32x4_t mid;
  72757. uint32x4_t side;
  72758. int32x4_t left;
  72759. int32x4_t right;
  72760. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  72761. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  72762. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  72763. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  72764. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  72765. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  72766. }
  72767. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72768. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72769. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72770. mid = (mid << 1) | (side & 0x01);
  72771. pOutputSamples[i*2+0] = (drflac_int32)(mid + side) >> 1;
  72772. pOutputSamples[i*2+1] = (drflac_int32)(mid - side) >> 1;
  72773. }
  72774. } else {
  72775. int32x4_t shift4;
  72776. shift -= 1;
  72777. shift4 = vdupq_n_s32(shift);
  72778. for (i = 0; i < frameCount4; ++i) {
  72779. uint32x4_t mid;
  72780. uint32x4_t side;
  72781. int32x4_t left;
  72782. int32x4_t right;
  72783. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  72784. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  72785. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, one4));
  72786. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  72787. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  72788. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  72789. }
  72790. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72791. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72792. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72793. mid = (mid << 1) | (side & 0x01);
  72794. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift);
  72795. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift);
  72796. }
  72797. }
  72798. }
  72799. #endif
  72800. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72801. {
  72802. #if defined(DRFLAC_SUPPORT_SSE2)
  72803. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  72804. drflac_read_pcm_frames_s32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72805. } else
  72806. #elif defined(DRFLAC_SUPPORT_NEON)
  72807. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  72808. drflac_read_pcm_frames_s32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72809. } else
  72810. #endif
  72811. {
  72812. #if 0
  72813. drflac_read_pcm_frames_s32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72814. #else
  72815. drflac_read_pcm_frames_s32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72816. #endif
  72817. }
  72818. }
  72819. #if 0
  72820. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72821. {
  72822. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  72823. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample));
  72824. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample));
  72825. }
  72826. }
  72827. #endif
  72828. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72829. {
  72830. drflac_uint64 i;
  72831. drflac_uint64 frameCount4 = frameCount >> 2;
  72832. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72833. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72834. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72835. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72836. for (i = 0; i < frameCount4; ++i) {
  72837. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  72838. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  72839. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  72840. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  72841. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  72842. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  72843. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  72844. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  72845. pOutputSamples[i*8+0] = (drflac_int32)tempL0;
  72846. pOutputSamples[i*8+1] = (drflac_int32)tempR0;
  72847. pOutputSamples[i*8+2] = (drflac_int32)tempL1;
  72848. pOutputSamples[i*8+3] = (drflac_int32)tempR1;
  72849. pOutputSamples[i*8+4] = (drflac_int32)tempL2;
  72850. pOutputSamples[i*8+5] = (drflac_int32)tempR2;
  72851. pOutputSamples[i*8+6] = (drflac_int32)tempL3;
  72852. pOutputSamples[i*8+7] = (drflac_int32)tempR3;
  72853. }
  72854. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72855. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  72856. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  72857. }
  72858. }
  72859. #if defined(DRFLAC_SUPPORT_SSE2)
  72860. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72861. {
  72862. drflac_uint64 i;
  72863. drflac_uint64 frameCount4 = frameCount >> 2;
  72864. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72865. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72866. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72867. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72868. for (i = 0; i < frameCount4; ++i) {
  72869. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  72870. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  72871. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 0), _mm_unpacklo_epi32(left, right));
  72872. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8 + 4), _mm_unpackhi_epi32(left, right));
  72873. }
  72874. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72875. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  72876. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  72877. }
  72878. }
  72879. #endif
  72880. #if defined(DRFLAC_SUPPORT_NEON)
  72881. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72882. {
  72883. drflac_uint64 i;
  72884. drflac_uint64 frameCount4 = frameCount >> 2;
  72885. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  72886. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  72887. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  72888. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  72889. int32x4_t shift4_0 = vdupq_n_s32(shift0);
  72890. int32x4_t shift4_1 = vdupq_n_s32(shift1);
  72891. for (i = 0; i < frameCount4; ++i) {
  72892. int32x4_t left;
  72893. int32x4_t right;
  72894. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift4_0));
  72895. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift4_1));
  72896. drflac__vst2q_s32(pOutputSamples + i*8, vzipq_s32(left, right));
  72897. }
  72898. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  72899. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0);
  72900. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1);
  72901. }
  72902. }
  72903. #endif
  72904. static DRFLAC_INLINE void drflac_read_pcm_frames_s32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int32* pOutputSamples)
  72905. {
  72906. #if defined(DRFLAC_SUPPORT_SSE2)
  72907. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  72908. drflac_read_pcm_frames_s32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72909. } else
  72910. #elif defined(DRFLAC_SUPPORT_NEON)
  72911. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  72912. drflac_read_pcm_frames_s32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72913. } else
  72914. #endif
  72915. {
  72916. #if 0
  72917. drflac_read_pcm_frames_s32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72918. #else
  72919. drflac_read_pcm_frames_s32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  72920. #endif
  72921. }
  72922. }
  72923. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s32(drflac* pFlac, drflac_uint64 framesToRead, drflac_int32* pBufferOut)
  72924. {
  72925. drflac_uint64 framesRead;
  72926. drflac_uint32 unusedBitsPerSample;
  72927. if (pFlac == NULL || framesToRead == 0) {
  72928. return 0;
  72929. }
  72930. if (pBufferOut == NULL) {
  72931. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  72932. }
  72933. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  72934. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  72935. framesRead = 0;
  72936. while (framesToRead > 0) {
  72937. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  72938. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  72939. break;
  72940. }
  72941. } else {
  72942. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  72943. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  72944. drflac_uint64 frameCountThisIteration = framesToRead;
  72945. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  72946. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  72947. }
  72948. if (channelCount == 2) {
  72949. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  72950. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  72951. switch (pFlac->currentFLACFrame.header.channelAssignment)
  72952. {
  72953. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  72954. {
  72955. drflac_read_pcm_frames_s32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  72956. } break;
  72957. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  72958. {
  72959. drflac_read_pcm_frames_s32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  72960. } break;
  72961. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  72962. {
  72963. drflac_read_pcm_frames_s32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  72964. } break;
  72965. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  72966. default:
  72967. {
  72968. drflac_read_pcm_frames_s32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  72969. } break;
  72970. }
  72971. } else {
  72972. drflac_uint64 i;
  72973. for (i = 0; i < frameCountThisIteration; ++i) {
  72974. unsigned int j;
  72975. for (j = 0; j < channelCount; ++j) {
  72976. pBufferOut[(i*channelCount)+j] = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  72977. }
  72978. }
  72979. }
  72980. framesRead += frameCountThisIteration;
  72981. pBufferOut += frameCountThisIteration * channelCount;
  72982. framesToRead -= frameCountThisIteration;
  72983. pFlac->currentPCMFrame += frameCountThisIteration;
  72984. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  72985. }
  72986. }
  72987. return framesRead;
  72988. }
  72989. #if 0
  72990. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  72991. {
  72992. drflac_uint64 i;
  72993. for (i = 0; i < frameCount; ++i) {
  72994. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  72995. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  72996. drflac_uint32 right = left - side;
  72997. left >>= 16;
  72998. right >>= 16;
  72999. pOutputSamples[i*2+0] = (drflac_int16)left;
  73000. pOutputSamples[i*2+1] = (drflac_int16)right;
  73001. }
  73002. }
  73003. #endif
  73004. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73005. {
  73006. drflac_uint64 i;
  73007. drflac_uint64 frameCount4 = frameCount >> 2;
  73008. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73009. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73010. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73011. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73012. for (i = 0; i < frameCount4; ++i) {
  73013. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  73014. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  73015. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  73016. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  73017. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  73018. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  73019. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  73020. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  73021. drflac_uint32 right0 = left0 - side0;
  73022. drflac_uint32 right1 = left1 - side1;
  73023. drflac_uint32 right2 = left2 - side2;
  73024. drflac_uint32 right3 = left3 - side3;
  73025. left0 >>= 16;
  73026. left1 >>= 16;
  73027. left2 >>= 16;
  73028. left3 >>= 16;
  73029. right0 >>= 16;
  73030. right1 >>= 16;
  73031. right2 >>= 16;
  73032. right3 >>= 16;
  73033. pOutputSamples[i*8+0] = (drflac_int16)left0;
  73034. pOutputSamples[i*8+1] = (drflac_int16)right0;
  73035. pOutputSamples[i*8+2] = (drflac_int16)left1;
  73036. pOutputSamples[i*8+3] = (drflac_int16)right1;
  73037. pOutputSamples[i*8+4] = (drflac_int16)left2;
  73038. pOutputSamples[i*8+5] = (drflac_int16)right2;
  73039. pOutputSamples[i*8+6] = (drflac_int16)left3;
  73040. pOutputSamples[i*8+7] = (drflac_int16)right3;
  73041. }
  73042. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73043. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73044. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73045. drflac_uint32 right = left - side;
  73046. left >>= 16;
  73047. right >>= 16;
  73048. pOutputSamples[i*2+0] = (drflac_int16)left;
  73049. pOutputSamples[i*2+1] = (drflac_int16)right;
  73050. }
  73051. }
  73052. #if defined(DRFLAC_SUPPORT_SSE2)
  73053. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73054. {
  73055. drflac_uint64 i;
  73056. drflac_uint64 frameCount4 = frameCount >> 2;
  73057. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73058. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73059. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73060. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73061. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73062. for (i = 0; i < frameCount4; ++i) {
  73063. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73064. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73065. __m128i right = _mm_sub_epi32(left, side);
  73066. left = _mm_srai_epi32(left, 16);
  73067. right = _mm_srai_epi32(right, 16);
  73068. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  73069. }
  73070. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73071. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73072. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73073. drflac_uint32 right = left - side;
  73074. left >>= 16;
  73075. right >>= 16;
  73076. pOutputSamples[i*2+0] = (drflac_int16)left;
  73077. pOutputSamples[i*2+1] = (drflac_int16)right;
  73078. }
  73079. }
  73080. #endif
  73081. #if defined(DRFLAC_SUPPORT_NEON)
  73082. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73083. {
  73084. drflac_uint64 i;
  73085. drflac_uint64 frameCount4 = frameCount >> 2;
  73086. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73087. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73088. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73089. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73090. int32x4_t shift0_4;
  73091. int32x4_t shift1_4;
  73092. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73093. shift0_4 = vdupq_n_s32(shift0);
  73094. shift1_4 = vdupq_n_s32(shift1);
  73095. for (i = 0; i < frameCount4; ++i) {
  73096. uint32x4_t left;
  73097. uint32x4_t side;
  73098. uint32x4_t right;
  73099. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73100. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73101. right = vsubq_u32(left, side);
  73102. left = vshrq_n_u32(left, 16);
  73103. right = vshrq_n_u32(right, 16);
  73104. drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  73105. }
  73106. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73107. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73108. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73109. drflac_uint32 right = left - side;
  73110. left >>= 16;
  73111. right >>= 16;
  73112. pOutputSamples[i*2+0] = (drflac_int16)left;
  73113. pOutputSamples[i*2+1] = (drflac_int16)right;
  73114. }
  73115. }
  73116. #endif
  73117. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73118. {
  73119. #if defined(DRFLAC_SUPPORT_SSE2)
  73120. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73121. drflac_read_pcm_frames_s16__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73122. } else
  73123. #elif defined(DRFLAC_SUPPORT_NEON)
  73124. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73125. drflac_read_pcm_frames_s16__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73126. } else
  73127. #endif
  73128. {
  73129. #if 0
  73130. drflac_read_pcm_frames_s16__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73131. #else
  73132. drflac_read_pcm_frames_s16__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73133. #endif
  73134. }
  73135. }
  73136. #if 0
  73137. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73138. {
  73139. drflac_uint64 i;
  73140. for (i = 0; i < frameCount; ++i) {
  73141. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73142. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73143. drflac_uint32 left = right + side;
  73144. left >>= 16;
  73145. right >>= 16;
  73146. pOutputSamples[i*2+0] = (drflac_int16)left;
  73147. pOutputSamples[i*2+1] = (drflac_int16)right;
  73148. }
  73149. }
  73150. #endif
  73151. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73152. {
  73153. drflac_uint64 i;
  73154. drflac_uint64 frameCount4 = frameCount >> 2;
  73155. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73156. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73157. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73158. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73159. for (i = 0; i < frameCount4; ++i) {
  73160. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  73161. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  73162. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  73163. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  73164. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  73165. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  73166. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  73167. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  73168. drflac_uint32 left0 = right0 + side0;
  73169. drflac_uint32 left1 = right1 + side1;
  73170. drflac_uint32 left2 = right2 + side2;
  73171. drflac_uint32 left3 = right3 + side3;
  73172. left0 >>= 16;
  73173. left1 >>= 16;
  73174. left2 >>= 16;
  73175. left3 >>= 16;
  73176. right0 >>= 16;
  73177. right1 >>= 16;
  73178. right2 >>= 16;
  73179. right3 >>= 16;
  73180. pOutputSamples[i*8+0] = (drflac_int16)left0;
  73181. pOutputSamples[i*8+1] = (drflac_int16)right0;
  73182. pOutputSamples[i*8+2] = (drflac_int16)left1;
  73183. pOutputSamples[i*8+3] = (drflac_int16)right1;
  73184. pOutputSamples[i*8+4] = (drflac_int16)left2;
  73185. pOutputSamples[i*8+5] = (drflac_int16)right2;
  73186. pOutputSamples[i*8+6] = (drflac_int16)left3;
  73187. pOutputSamples[i*8+7] = (drflac_int16)right3;
  73188. }
  73189. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73190. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73191. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73192. drflac_uint32 left = right + side;
  73193. left >>= 16;
  73194. right >>= 16;
  73195. pOutputSamples[i*2+0] = (drflac_int16)left;
  73196. pOutputSamples[i*2+1] = (drflac_int16)right;
  73197. }
  73198. }
  73199. #if defined(DRFLAC_SUPPORT_SSE2)
  73200. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73201. {
  73202. drflac_uint64 i;
  73203. drflac_uint64 frameCount4 = frameCount >> 2;
  73204. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73205. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73206. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73207. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73208. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73209. for (i = 0; i < frameCount4; ++i) {
  73210. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73211. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73212. __m128i left = _mm_add_epi32(right, side);
  73213. left = _mm_srai_epi32(left, 16);
  73214. right = _mm_srai_epi32(right, 16);
  73215. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  73216. }
  73217. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73218. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73219. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73220. drflac_uint32 left = right + side;
  73221. left >>= 16;
  73222. right >>= 16;
  73223. pOutputSamples[i*2+0] = (drflac_int16)left;
  73224. pOutputSamples[i*2+1] = (drflac_int16)right;
  73225. }
  73226. }
  73227. #endif
  73228. #if defined(DRFLAC_SUPPORT_NEON)
  73229. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73230. {
  73231. drflac_uint64 i;
  73232. drflac_uint64 frameCount4 = frameCount >> 2;
  73233. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73234. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73235. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73236. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73237. int32x4_t shift0_4;
  73238. int32x4_t shift1_4;
  73239. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73240. shift0_4 = vdupq_n_s32(shift0);
  73241. shift1_4 = vdupq_n_s32(shift1);
  73242. for (i = 0; i < frameCount4; ++i) {
  73243. uint32x4_t side;
  73244. uint32x4_t right;
  73245. uint32x4_t left;
  73246. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73247. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73248. left = vaddq_u32(right, side);
  73249. left = vshrq_n_u32(left, 16);
  73250. right = vshrq_n_u32(right, 16);
  73251. drflac__vst2q_u16((drflac_uint16*)pOutputSamples + i*8, vzip_u16(vmovn_u32(left), vmovn_u32(right)));
  73252. }
  73253. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73254. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73255. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73256. drflac_uint32 left = right + side;
  73257. left >>= 16;
  73258. right >>= 16;
  73259. pOutputSamples[i*2+0] = (drflac_int16)left;
  73260. pOutputSamples[i*2+1] = (drflac_int16)right;
  73261. }
  73262. }
  73263. #endif
  73264. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73265. {
  73266. #if defined(DRFLAC_SUPPORT_SSE2)
  73267. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73268. drflac_read_pcm_frames_s16__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73269. } else
  73270. #elif defined(DRFLAC_SUPPORT_NEON)
  73271. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73272. drflac_read_pcm_frames_s16__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73273. } else
  73274. #endif
  73275. {
  73276. #if 0
  73277. drflac_read_pcm_frames_s16__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73278. #else
  73279. drflac_read_pcm_frames_s16__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73280. #endif
  73281. }
  73282. }
  73283. #if 0
  73284. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73285. {
  73286. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  73287. drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73288. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73289. mid = (mid << 1) | (side & 0x01);
  73290. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  73291. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  73292. }
  73293. }
  73294. #endif
  73295. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73296. {
  73297. drflac_uint64 i;
  73298. drflac_uint64 frameCount4 = frameCount >> 2;
  73299. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73300. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73301. drflac_uint32 shift = unusedBitsPerSample;
  73302. if (shift > 0) {
  73303. shift -= 1;
  73304. for (i = 0; i < frameCount4; ++i) {
  73305. drflac_uint32 temp0L;
  73306. drflac_uint32 temp1L;
  73307. drflac_uint32 temp2L;
  73308. drflac_uint32 temp3L;
  73309. drflac_uint32 temp0R;
  73310. drflac_uint32 temp1R;
  73311. drflac_uint32 temp2R;
  73312. drflac_uint32 temp3R;
  73313. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73314. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73315. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73316. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73317. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73318. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73319. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73320. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73321. mid0 = (mid0 << 1) | (side0 & 0x01);
  73322. mid1 = (mid1 << 1) | (side1 & 0x01);
  73323. mid2 = (mid2 << 1) | (side2 & 0x01);
  73324. mid3 = (mid3 << 1) | (side3 & 0x01);
  73325. temp0L = (mid0 + side0) << shift;
  73326. temp1L = (mid1 + side1) << shift;
  73327. temp2L = (mid2 + side2) << shift;
  73328. temp3L = (mid3 + side3) << shift;
  73329. temp0R = (mid0 - side0) << shift;
  73330. temp1R = (mid1 - side1) << shift;
  73331. temp2R = (mid2 - side2) << shift;
  73332. temp3R = (mid3 - side3) << shift;
  73333. temp0L >>= 16;
  73334. temp1L >>= 16;
  73335. temp2L >>= 16;
  73336. temp3L >>= 16;
  73337. temp0R >>= 16;
  73338. temp1R >>= 16;
  73339. temp2R >>= 16;
  73340. temp3R >>= 16;
  73341. pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  73342. pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  73343. pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  73344. pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  73345. pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  73346. pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  73347. pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  73348. pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  73349. }
  73350. } else {
  73351. for (i = 0; i < frameCount4; ++i) {
  73352. drflac_uint32 temp0L;
  73353. drflac_uint32 temp1L;
  73354. drflac_uint32 temp2L;
  73355. drflac_uint32 temp3L;
  73356. drflac_uint32 temp0R;
  73357. drflac_uint32 temp1R;
  73358. drflac_uint32 temp2R;
  73359. drflac_uint32 temp3R;
  73360. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73361. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73362. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73363. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73364. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73365. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73366. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73367. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73368. mid0 = (mid0 << 1) | (side0 & 0x01);
  73369. mid1 = (mid1 << 1) | (side1 & 0x01);
  73370. mid2 = (mid2 << 1) | (side2 & 0x01);
  73371. mid3 = (mid3 << 1) | (side3 & 0x01);
  73372. temp0L = ((drflac_int32)(mid0 + side0) >> 1);
  73373. temp1L = ((drflac_int32)(mid1 + side1) >> 1);
  73374. temp2L = ((drflac_int32)(mid2 + side2) >> 1);
  73375. temp3L = ((drflac_int32)(mid3 + side3) >> 1);
  73376. temp0R = ((drflac_int32)(mid0 - side0) >> 1);
  73377. temp1R = ((drflac_int32)(mid1 - side1) >> 1);
  73378. temp2R = ((drflac_int32)(mid2 - side2) >> 1);
  73379. temp3R = ((drflac_int32)(mid3 - side3) >> 1);
  73380. temp0L >>= 16;
  73381. temp1L >>= 16;
  73382. temp2L >>= 16;
  73383. temp3L >>= 16;
  73384. temp0R >>= 16;
  73385. temp1R >>= 16;
  73386. temp2R >>= 16;
  73387. temp3R >>= 16;
  73388. pOutputSamples[i*8+0] = (drflac_int16)temp0L;
  73389. pOutputSamples[i*8+1] = (drflac_int16)temp0R;
  73390. pOutputSamples[i*8+2] = (drflac_int16)temp1L;
  73391. pOutputSamples[i*8+3] = (drflac_int16)temp1R;
  73392. pOutputSamples[i*8+4] = (drflac_int16)temp2L;
  73393. pOutputSamples[i*8+5] = (drflac_int16)temp2R;
  73394. pOutputSamples[i*8+6] = (drflac_int16)temp3L;
  73395. pOutputSamples[i*8+7] = (drflac_int16)temp3R;
  73396. }
  73397. }
  73398. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73399. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73400. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73401. mid = (mid << 1) | (side & 0x01);
  73402. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) >> 16);
  73403. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) >> 16);
  73404. }
  73405. }
  73406. #if defined(DRFLAC_SUPPORT_SSE2)
  73407. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73408. {
  73409. drflac_uint64 i;
  73410. drflac_uint64 frameCount4 = frameCount >> 2;
  73411. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73412. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73413. drflac_uint32 shift = unusedBitsPerSample;
  73414. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73415. if (shift == 0) {
  73416. for (i = 0; i < frameCount4; ++i) {
  73417. __m128i mid;
  73418. __m128i side;
  73419. __m128i left;
  73420. __m128i right;
  73421. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73422. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73423. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  73424. left = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  73425. right = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  73426. left = _mm_srai_epi32(left, 16);
  73427. right = _mm_srai_epi32(right, 16);
  73428. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  73429. }
  73430. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73431. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73432. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73433. mid = (mid << 1) | (side & 0x01);
  73434. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  73435. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  73436. }
  73437. } else {
  73438. shift -= 1;
  73439. for (i = 0; i < frameCount4; ++i) {
  73440. __m128i mid;
  73441. __m128i side;
  73442. __m128i left;
  73443. __m128i right;
  73444. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73445. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73446. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  73447. left = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  73448. right = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  73449. left = _mm_srai_epi32(left, 16);
  73450. right = _mm_srai_epi32(right, 16);
  73451. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  73452. }
  73453. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73454. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73455. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73456. mid = (mid << 1) | (side & 0x01);
  73457. pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  73458. pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  73459. }
  73460. }
  73461. }
  73462. #endif
  73463. #if defined(DRFLAC_SUPPORT_NEON)
  73464. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73465. {
  73466. drflac_uint64 i;
  73467. drflac_uint64 frameCount4 = frameCount >> 2;
  73468. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73469. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73470. drflac_uint32 shift = unusedBitsPerSample;
  73471. int32x4_t wbpsShift0_4;
  73472. int32x4_t wbpsShift1_4;
  73473. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73474. wbpsShift0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73475. wbpsShift1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73476. if (shift == 0) {
  73477. for (i = 0; i < frameCount4; ++i) {
  73478. uint32x4_t mid;
  73479. uint32x4_t side;
  73480. int32x4_t left;
  73481. int32x4_t right;
  73482. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  73483. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  73484. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  73485. left = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  73486. right = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  73487. left = vshrq_n_s32(left, 16);
  73488. right = vshrq_n_s32(right, 16);
  73489. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  73490. }
  73491. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73492. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73493. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73494. mid = (mid << 1) | (side & 0x01);
  73495. pOutputSamples[i*2+0] = (drflac_int16)(((drflac_int32)(mid + side) >> 1) >> 16);
  73496. pOutputSamples[i*2+1] = (drflac_int16)(((drflac_int32)(mid - side) >> 1) >> 16);
  73497. }
  73498. } else {
  73499. int32x4_t shift4;
  73500. shift -= 1;
  73501. shift4 = vdupq_n_s32(shift);
  73502. for (i = 0; i < frameCount4; ++i) {
  73503. uint32x4_t mid;
  73504. uint32x4_t side;
  73505. int32x4_t left;
  73506. int32x4_t right;
  73507. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbpsShift0_4);
  73508. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbpsShift1_4);
  73509. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  73510. left = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  73511. right = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  73512. left = vshrq_n_s32(left, 16);
  73513. right = vshrq_n_s32(right, 16);
  73514. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  73515. }
  73516. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73517. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73518. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73519. mid = (mid << 1) | (side & 0x01);
  73520. pOutputSamples[i*2+0] = (drflac_int16)(((mid + side) << shift) >> 16);
  73521. pOutputSamples[i*2+1] = (drflac_int16)(((mid - side) << shift) >> 16);
  73522. }
  73523. }
  73524. }
  73525. #endif
  73526. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73527. {
  73528. #if defined(DRFLAC_SUPPORT_SSE2)
  73529. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73530. drflac_read_pcm_frames_s16__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73531. } else
  73532. #elif defined(DRFLAC_SUPPORT_NEON)
  73533. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73534. drflac_read_pcm_frames_s16__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73535. } else
  73536. #endif
  73537. {
  73538. #if 0
  73539. drflac_read_pcm_frames_s16__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73540. #else
  73541. drflac_read_pcm_frames_s16__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73542. #endif
  73543. }
  73544. }
  73545. #if 0
  73546. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73547. {
  73548. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  73549. pOutputSamples[i*2+0] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) >> 16);
  73550. pOutputSamples[i*2+1] = (drflac_int16)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) >> 16);
  73551. }
  73552. }
  73553. #endif
  73554. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73555. {
  73556. drflac_uint64 i;
  73557. drflac_uint64 frameCount4 = frameCount >> 2;
  73558. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73559. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73560. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73561. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73562. for (i = 0; i < frameCount4; ++i) {
  73563. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  73564. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  73565. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  73566. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  73567. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  73568. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  73569. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  73570. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  73571. tempL0 >>= 16;
  73572. tempL1 >>= 16;
  73573. tempL2 >>= 16;
  73574. tempL3 >>= 16;
  73575. tempR0 >>= 16;
  73576. tempR1 >>= 16;
  73577. tempR2 >>= 16;
  73578. tempR3 >>= 16;
  73579. pOutputSamples[i*8+0] = (drflac_int16)tempL0;
  73580. pOutputSamples[i*8+1] = (drflac_int16)tempR0;
  73581. pOutputSamples[i*8+2] = (drflac_int16)tempL1;
  73582. pOutputSamples[i*8+3] = (drflac_int16)tempR1;
  73583. pOutputSamples[i*8+4] = (drflac_int16)tempL2;
  73584. pOutputSamples[i*8+5] = (drflac_int16)tempR2;
  73585. pOutputSamples[i*8+6] = (drflac_int16)tempL3;
  73586. pOutputSamples[i*8+7] = (drflac_int16)tempR3;
  73587. }
  73588. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73589. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  73590. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  73591. }
  73592. }
  73593. #if defined(DRFLAC_SUPPORT_SSE2)
  73594. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73595. {
  73596. drflac_uint64 i;
  73597. drflac_uint64 frameCount4 = frameCount >> 2;
  73598. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73599. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73600. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73601. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73602. for (i = 0; i < frameCount4; ++i) {
  73603. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73604. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73605. left = _mm_srai_epi32(left, 16);
  73606. right = _mm_srai_epi32(right, 16);
  73607. _mm_storeu_si128((__m128i*)(pOutputSamples + i*8), drflac__mm_packs_interleaved_epi32(left, right));
  73608. }
  73609. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73610. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  73611. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  73612. }
  73613. }
  73614. #endif
  73615. #if defined(DRFLAC_SUPPORT_NEON)
  73616. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73617. {
  73618. drflac_uint64 i;
  73619. drflac_uint64 frameCount4 = frameCount >> 2;
  73620. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73621. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73622. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73623. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73624. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  73625. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  73626. for (i = 0; i < frameCount4; ++i) {
  73627. int32x4_t left;
  73628. int32x4_t right;
  73629. left = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  73630. right = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  73631. left = vshrq_n_s32(left, 16);
  73632. right = vshrq_n_s32(right, 16);
  73633. drflac__vst2q_s16(pOutputSamples + i*8, vzip_s16(vmovn_s32(left), vmovn_s32(right)));
  73634. }
  73635. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73636. pOutputSamples[i*2+0] = (drflac_int16)((pInputSamples0U32[i] << shift0) >> 16);
  73637. pOutputSamples[i*2+1] = (drflac_int16)((pInputSamples1U32[i] << shift1) >> 16);
  73638. }
  73639. }
  73640. #endif
  73641. static DRFLAC_INLINE void drflac_read_pcm_frames_s16__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, drflac_int16* pOutputSamples)
  73642. {
  73643. #if defined(DRFLAC_SUPPORT_SSE2)
  73644. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73645. drflac_read_pcm_frames_s16__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73646. } else
  73647. #elif defined(DRFLAC_SUPPORT_NEON)
  73648. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73649. drflac_read_pcm_frames_s16__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73650. } else
  73651. #endif
  73652. {
  73653. #if 0
  73654. drflac_read_pcm_frames_s16__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73655. #else
  73656. drflac_read_pcm_frames_s16__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73657. #endif
  73658. }
  73659. }
  73660. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_s16(drflac* pFlac, drflac_uint64 framesToRead, drflac_int16* pBufferOut)
  73661. {
  73662. drflac_uint64 framesRead;
  73663. drflac_uint32 unusedBitsPerSample;
  73664. if (pFlac == NULL || framesToRead == 0) {
  73665. return 0;
  73666. }
  73667. if (pBufferOut == NULL) {
  73668. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  73669. }
  73670. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  73671. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  73672. framesRead = 0;
  73673. while (framesToRead > 0) {
  73674. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  73675. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  73676. break;
  73677. }
  73678. } else {
  73679. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  73680. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  73681. drflac_uint64 frameCountThisIteration = framesToRead;
  73682. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  73683. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  73684. }
  73685. if (channelCount == 2) {
  73686. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  73687. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  73688. switch (pFlac->currentFLACFrame.header.channelAssignment)
  73689. {
  73690. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  73691. {
  73692. drflac_read_pcm_frames_s16__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  73693. } break;
  73694. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  73695. {
  73696. drflac_read_pcm_frames_s16__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  73697. } break;
  73698. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  73699. {
  73700. drflac_read_pcm_frames_s16__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  73701. } break;
  73702. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  73703. default:
  73704. {
  73705. drflac_read_pcm_frames_s16__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  73706. } break;
  73707. }
  73708. } else {
  73709. drflac_uint64 i;
  73710. for (i = 0; i < frameCountThisIteration; ++i) {
  73711. unsigned int j;
  73712. for (j = 0; j < channelCount; ++j) {
  73713. drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  73714. pBufferOut[(i*channelCount)+j] = (drflac_int16)(sampleS32 >> 16);
  73715. }
  73716. }
  73717. }
  73718. framesRead += frameCountThisIteration;
  73719. pBufferOut += frameCountThisIteration * channelCount;
  73720. framesToRead -= frameCountThisIteration;
  73721. pFlac->currentPCMFrame += frameCountThisIteration;
  73722. pFlac->currentFLACFrame.pcmFramesRemaining -= (drflac_uint32)frameCountThisIteration;
  73723. }
  73724. }
  73725. return framesRead;
  73726. }
  73727. #if 0
  73728. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73729. {
  73730. drflac_uint64 i;
  73731. for (i = 0; i < frameCount; ++i) {
  73732. drflac_uint32 left = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73733. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73734. drflac_uint32 right = left - side;
  73735. pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
  73736. pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  73737. }
  73738. }
  73739. #endif
  73740. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73741. {
  73742. drflac_uint64 i;
  73743. drflac_uint64 frameCount4 = frameCount >> 2;
  73744. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73745. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73746. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73747. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73748. float factor = 1 / 2147483648.0;
  73749. for (i = 0; i < frameCount4; ++i) {
  73750. drflac_uint32 left0 = pInputSamples0U32[i*4+0] << shift0;
  73751. drflac_uint32 left1 = pInputSamples0U32[i*4+1] << shift0;
  73752. drflac_uint32 left2 = pInputSamples0U32[i*4+2] << shift0;
  73753. drflac_uint32 left3 = pInputSamples0U32[i*4+3] << shift0;
  73754. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << shift1;
  73755. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << shift1;
  73756. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << shift1;
  73757. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << shift1;
  73758. drflac_uint32 right0 = left0 - side0;
  73759. drflac_uint32 right1 = left1 - side1;
  73760. drflac_uint32 right2 = left2 - side2;
  73761. drflac_uint32 right3 = left3 - side3;
  73762. pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
  73763. pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  73764. pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
  73765. pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  73766. pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
  73767. pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  73768. pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
  73769. pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  73770. }
  73771. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73772. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73773. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73774. drflac_uint32 right = left - side;
  73775. pOutputSamples[i*2+0] = (drflac_int32)left * factor;
  73776. pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  73777. }
  73778. }
  73779. #if defined(DRFLAC_SUPPORT_SSE2)
  73780. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73781. {
  73782. drflac_uint64 i;
  73783. drflac_uint64 frameCount4 = frameCount >> 2;
  73784. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73785. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73786. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  73787. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  73788. __m128 factor;
  73789. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73790. factor = _mm_set1_ps(1.0f / 8388608.0f);
  73791. for (i = 0; i < frameCount4; ++i) {
  73792. __m128i left = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73793. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73794. __m128i right = _mm_sub_epi32(left, side);
  73795. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  73796. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  73797. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  73798. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  73799. }
  73800. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73801. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73802. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73803. drflac_uint32 right = left - side;
  73804. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  73805. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  73806. }
  73807. }
  73808. #endif
  73809. #if defined(DRFLAC_SUPPORT_NEON)
  73810. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73811. {
  73812. drflac_uint64 i;
  73813. drflac_uint64 frameCount4 = frameCount >> 2;
  73814. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73815. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73816. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  73817. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  73818. float32x4_t factor4;
  73819. int32x4_t shift0_4;
  73820. int32x4_t shift1_4;
  73821. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73822. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  73823. shift0_4 = vdupq_n_s32(shift0);
  73824. shift1_4 = vdupq_n_s32(shift1);
  73825. for (i = 0; i < frameCount4; ++i) {
  73826. uint32x4_t left;
  73827. uint32x4_t side;
  73828. uint32x4_t right;
  73829. float32x4_t leftf;
  73830. float32x4_t rightf;
  73831. left = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73832. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73833. right = vsubq_u32(left, side);
  73834. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  73835. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  73836. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  73837. }
  73838. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73839. drflac_uint32 left = pInputSamples0U32[i] << shift0;
  73840. drflac_uint32 side = pInputSamples1U32[i] << shift1;
  73841. drflac_uint32 right = left - side;
  73842. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  73843. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  73844. }
  73845. }
  73846. #endif
  73847. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_left_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73848. {
  73849. #if defined(DRFLAC_SUPPORT_SSE2)
  73850. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73851. drflac_read_pcm_frames_f32__decode_left_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73852. } else
  73853. #elif defined(DRFLAC_SUPPORT_NEON)
  73854. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73855. drflac_read_pcm_frames_f32__decode_left_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73856. } else
  73857. #endif
  73858. {
  73859. #if 0
  73860. drflac_read_pcm_frames_f32__decode_left_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73861. #else
  73862. drflac_read_pcm_frames_f32__decode_left_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73863. #endif
  73864. }
  73865. }
  73866. #if 0
  73867. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73868. {
  73869. drflac_uint64 i;
  73870. for (i = 0; i < frameCount; ++i) {
  73871. drflac_uint32 side = (drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  73872. drflac_uint32 right = (drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  73873. drflac_uint32 left = right + side;
  73874. pOutputSamples[i*2+0] = (float)((drflac_int32)left / 2147483648.0);
  73875. pOutputSamples[i*2+1] = (float)((drflac_int32)right / 2147483648.0);
  73876. }
  73877. }
  73878. #endif
  73879. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73880. {
  73881. drflac_uint64 i;
  73882. drflac_uint64 frameCount4 = frameCount >> 2;
  73883. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73884. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73885. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  73886. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  73887. float factor = 1 / 2147483648.0;
  73888. for (i = 0; i < frameCount4; ++i) {
  73889. drflac_uint32 side0 = pInputSamples0U32[i*4+0] << shift0;
  73890. drflac_uint32 side1 = pInputSamples0U32[i*4+1] << shift0;
  73891. drflac_uint32 side2 = pInputSamples0U32[i*4+2] << shift0;
  73892. drflac_uint32 side3 = pInputSamples0U32[i*4+3] << shift0;
  73893. drflac_uint32 right0 = pInputSamples1U32[i*4+0] << shift1;
  73894. drflac_uint32 right1 = pInputSamples1U32[i*4+1] << shift1;
  73895. drflac_uint32 right2 = pInputSamples1U32[i*4+2] << shift1;
  73896. drflac_uint32 right3 = pInputSamples1U32[i*4+3] << shift1;
  73897. drflac_uint32 left0 = right0 + side0;
  73898. drflac_uint32 left1 = right1 + side1;
  73899. drflac_uint32 left2 = right2 + side2;
  73900. drflac_uint32 left3 = right3 + side3;
  73901. pOutputSamples[i*8+0] = (drflac_int32)left0 * factor;
  73902. pOutputSamples[i*8+1] = (drflac_int32)right0 * factor;
  73903. pOutputSamples[i*8+2] = (drflac_int32)left1 * factor;
  73904. pOutputSamples[i*8+3] = (drflac_int32)right1 * factor;
  73905. pOutputSamples[i*8+4] = (drflac_int32)left2 * factor;
  73906. pOutputSamples[i*8+5] = (drflac_int32)right2 * factor;
  73907. pOutputSamples[i*8+6] = (drflac_int32)left3 * factor;
  73908. pOutputSamples[i*8+7] = (drflac_int32)right3 * factor;
  73909. }
  73910. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73911. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73912. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73913. drflac_uint32 left = right + side;
  73914. pOutputSamples[i*2+0] = (drflac_int32)left * factor;
  73915. pOutputSamples[i*2+1] = (drflac_int32)right * factor;
  73916. }
  73917. }
  73918. #if defined(DRFLAC_SUPPORT_SSE2)
  73919. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73920. {
  73921. drflac_uint64 i;
  73922. drflac_uint64 frameCount4 = frameCount >> 2;
  73923. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73924. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73925. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  73926. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  73927. __m128 factor;
  73928. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73929. factor = _mm_set1_ps(1.0f / 8388608.0f);
  73930. for (i = 0; i < frameCount4; ++i) {
  73931. __m128i side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  73932. __m128i right = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  73933. __m128i left = _mm_add_epi32(right, side);
  73934. __m128 leftf = _mm_mul_ps(_mm_cvtepi32_ps(left), factor);
  73935. __m128 rightf = _mm_mul_ps(_mm_cvtepi32_ps(right), factor);
  73936. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  73937. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  73938. }
  73939. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73940. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73941. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73942. drflac_uint32 left = right + side;
  73943. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  73944. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  73945. }
  73946. }
  73947. #endif
  73948. #if defined(DRFLAC_SUPPORT_NEON)
  73949. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73950. {
  73951. drflac_uint64 i;
  73952. drflac_uint64 frameCount4 = frameCount >> 2;
  73953. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  73954. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  73955. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  73956. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  73957. float32x4_t factor4;
  73958. int32x4_t shift0_4;
  73959. int32x4_t shift1_4;
  73960. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  73961. factor4 = vdupq_n_f32(1.0f / 8388608.0f);
  73962. shift0_4 = vdupq_n_s32(shift0);
  73963. shift1_4 = vdupq_n_s32(shift1);
  73964. for (i = 0; i < frameCount4; ++i) {
  73965. uint32x4_t side;
  73966. uint32x4_t right;
  73967. uint32x4_t left;
  73968. float32x4_t leftf;
  73969. float32x4_t rightf;
  73970. side = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4);
  73971. right = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4);
  73972. left = vaddq_u32(right, side);
  73973. leftf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(left)), factor4);
  73974. rightf = vmulq_f32(vcvtq_f32_s32(vreinterpretq_s32_u32(right)), factor4);
  73975. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  73976. }
  73977. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  73978. drflac_uint32 side = pInputSamples0U32[i] << shift0;
  73979. drflac_uint32 right = pInputSamples1U32[i] << shift1;
  73980. drflac_uint32 left = right + side;
  73981. pOutputSamples[i*2+0] = (drflac_int32)left / 8388608.0f;
  73982. pOutputSamples[i*2+1] = (drflac_int32)right / 8388608.0f;
  73983. }
  73984. }
  73985. #endif
  73986. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_right_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  73987. {
  73988. #if defined(DRFLAC_SUPPORT_SSE2)
  73989. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  73990. drflac_read_pcm_frames_f32__decode_right_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73991. } else
  73992. #elif defined(DRFLAC_SUPPORT_NEON)
  73993. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  73994. drflac_read_pcm_frames_f32__decode_right_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  73995. } else
  73996. #endif
  73997. {
  73998. #if 0
  73999. drflac_read_pcm_frames_f32__decode_right_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74000. #else
  74001. drflac_read_pcm_frames_f32__decode_right_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74002. #endif
  74003. }
  74004. }
  74005. #if 0
  74006. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74007. {
  74008. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  74009. drflac_uint32 mid = (drflac_uint32)pInputSamples0[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74010. drflac_uint32 side = (drflac_uint32)pInputSamples1[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74011. mid = (mid << 1) | (side & 0x01);
  74012. pOutputSamples[i*2+0] = (float)((((drflac_int32)(mid + side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  74013. pOutputSamples[i*2+1] = (float)((((drflac_int32)(mid - side) >> 1) << (unusedBitsPerSample)) / 2147483648.0);
  74014. }
  74015. }
  74016. #endif
  74017. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74018. {
  74019. drflac_uint64 i;
  74020. drflac_uint64 frameCount4 = frameCount >> 2;
  74021. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74022. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74023. drflac_uint32 shift = unusedBitsPerSample;
  74024. float factor = 1 / 2147483648.0;
  74025. if (shift > 0) {
  74026. shift -= 1;
  74027. for (i = 0; i < frameCount4; ++i) {
  74028. drflac_uint32 temp0L;
  74029. drflac_uint32 temp1L;
  74030. drflac_uint32 temp2L;
  74031. drflac_uint32 temp3L;
  74032. drflac_uint32 temp0R;
  74033. drflac_uint32 temp1R;
  74034. drflac_uint32 temp2R;
  74035. drflac_uint32 temp3R;
  74036. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74037. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74038. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74039. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74040. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74041. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74042. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74043. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74044. mid0 = (mid0 << 1) | (side0 & 0x01);
  74045. mid1 = (mid1 << 1) | (side1 & 0x01);
  74046. mid2 = (mid2 << 1) | (side2 & 0x01);
  74047. mid3 = (mid3 << 1) | (side3 & 0x01);
  74048. temp0L = (mid0 + side0) << shift;
  74049. temp1L = (mid1 + side1) << shift;
  74050. temp2L = (mid2 + side2) << shift;
  74051. temp3L = (mid3 + side3) << shift;
  74052. temp0R = (mid0 - side0) << shift;
  74053. temp1R = (mid1 - side1) << shift;
  74054. temp2R = (mid2 - side2) << shift;
  74055. temp3R = (mid3 - side3) << shift;
  74056. pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  74057. pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  74058. pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  74059. pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  74060. pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  74061. pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  74062. pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  74063. pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  74064. }
  74065. } else {
  74066. for (i = 0; i < frameCount4; ++i) {
  74067. drflac_uint32 temp0L;
  74068. drflac_uint32 temp1L;
  74069. drflac_uint32 temp2L;
  74070. drflac_uint32 temp3L;
  74071. drflac_uint32 temp0R;
  74072. drflac_uint32 temp1R;
  74073. drflac_uint32 temp2R;
  74074. drflac_uint32 temp3R;
  74075. drflac_uint32 mid0 = pInputSamples0U32[i*4+0] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74076. drflac_uint32 mid1 = pInputSamples0U32[i*4+1] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74077. drflac_uint32 mid2 = pInputSamples0U32[i*4+2] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74078. drflac_uint32 mid3 = pInputSamples0U32[i*4+3] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74079. drflac_uint32 side0 = pInputSamples1U32[i*4+0] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74080. drflac_uint32 side1 = pInputSamples1U32[i*4+1] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74081. drflac_uint32 side2 = pInputSamples1U32[i*4+2] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74082. drflac_uint32 side3 = pInputSamples1U32[i*4+3] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74083. mid0 = (mid0 << 1) | (side0 & 0x01);
  74084. mid1 = (mid1 << 1) | (side1 & 0x01);
  74085. mid2 = (mid2 << 1) | (side2 & 0x01);
  74086. mid3 = (mid3 << 1) | (side3 & 0x01);
  74087. temp0L = (drflac_uint32)((drflac_int32)(mid0 + side0) >> 1);
  74088. temp1L = (drflac_uint32)((drflac_int32)(mid1 + side1) >> 1);
  74089. temp2L = (drflac_uint32)((drflac_int32)(mid2 + side2) >> 1);
  74090. temp3L = (drflac_uint32)((drflac_int32)(mid3 + side3) >> 1);
  74091. temp0R = (drflac_uint32)((drflac_int32)(mid0 - side0) >> 1);
  74092. temp1R = (drflac_uint32)((drflac_int32)(mid1 - side1) >> 1);
  74093. temp2R = (drflac_uint32)((drflac_int32)(mid2 - side2) >> 1);
  74094. temp3R = (drflac_uint32)((drflac_int32)(mid3 - side3) >> 1);
  74095. pOutputSamples[i*8+0] = (drflac_int32)temp0L * factor;
  74096. pOutputSamples[i*8+1] = (drflac_int32)temp0R * factor;
  74097. pOutputSamples[i*8+2] = (drflac_int32)temp1L * factor;
  74098. pOutputSamples[i*8+3] = (drflac_int32)temp1R * factor;
  74099. pOutputSamples[i*8+4] = (drflac_int32)temp2L * factor;
  74100. pOutputSamples[i*8+5] = (drflac_int32)temp2R * factor;
  74101. pOutputSamples[i*8+6] = (drflac_int32)temp3L * factor;
  74102. pOutputSamples[i*8+7] = (drflac_int32)temp3R * factor;
  74103. }
  74104. }
  74105. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74106. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74107. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74108. mid = (mid << 1) | (side & 0x01);
  74109. pOutputSamples[i*2+0] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid + side) >> 1) << unusedBitsPerSample) * factor;
  74110. pOutputSamples[i*2+1] = (drflac_int32)((drflac_uint32)((drflac_int32)(mid - side) >> 1) << unusedBitsPerSample) * factor;
  74111. }
  74112. }
  74113. #if defined(DRFLAC_SUPPORT_SSE2)
  74114. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74115. {
  74116. drflac_uint64 i;
  74117. drflac_uint64 frameCount4 = frameCount >> 2;
  74118. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74119. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74120. drflac_uint32 shift = unusedBitsPerSample - 8;
  74121. float factor;
  74122. __m128 factor128;
  74123. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74124. factor = 1.0f / 8388608.0f;
  74125. factor128 = _mm_set1_ps(factor);
  74126. if (shift == 0) {
  74127. for (i = 0; i < frameCount4; ++i) {
  74128. __m128i mid;
  74129. __m128i side;
  74130. __m128i tempL;
  74131. __m128i tempR;
  74132. __m128 leftf;
  74133. __m128 rightf;
  74134. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74135. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74136. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74137. tempL = _mm_srai_epi32(_mm_add_epi32(mid, side), 1);
  74138. tempR = _mm_srai_epi32(_mm_sub_epi32(mid, side), 1);
  74139. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  74140. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  74141. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  74142. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  74143. }
  74144. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74145. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74146. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74147. mid = (mid << 1) | (side & 0x01);
  74148. pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  74149. pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  74150. }
  74151. } else {
  74152. shift -= 1;
  74153. for (i = 0; i < frameCount4; ++i) {
  74154. __m128i mid;
  74155. __m128i side;
  74156. __m128i tempL;
  74157. __m128i tempR;
  74158. __m128 leftf;
  74159. __m128 rightf;
  74160. mid = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74161. side = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74162. mid = _mm_or_si128(_mm_slli_epi32(mid, 1), _mm_and_si128(side, _mm_set1_epi32(0x01)));
  74163. tempL = _mm_slli_epi32(_mm_add_epi32(mid, side), shift);
  74164. tempR = _mm_slli_epi32(_mm_sub_epi32(mid, side), shift);
  74165. leftf = _mm_mul_ps(_mm_cvtepi32_ps(tempL), factor128);
  74166. rightf = _mm_mul_ps(_mm_cvtepi32_ps(tempR), factor128);
  74167. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  74168. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  74169. }
  74170. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74171. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74172. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74173. mid = (mid << 1) | (side & 0x01);
  74174. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  74175. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  74176. }
  74177. }
  74178. }
  74179. #endif
  74180. #if defined(DRFLAC_SUPPORT_NEON)
  74181. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74182. {
  74183. drflac_uint64 i;
  74184. drflac_uint64 frameCount4 = frameCount >> 2;
  74185. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74186. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74187. drflac_uint32 shift = unusedBitsPerSample - 8;
  74188. float factor;
  74189. float32x4_t factor4;
  74190. int32x4_t shift4;
  74191. int32x4_t wbps0_4;
  74192. int32x4_t wbps1_4;
  74193. DRFLAC_ASSERT(pFlac->bitsPerSample <= 24);
  74194. factor = 1.0f / 8388608.0f;
  74195. factor4 = vdupq_n_f32(factor);
  74196. wbps0_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample);
  74197. wbps1_4 = vdupq_n_s32(pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample);
  74198. if (shift == 0) {
  74199. for (i = 0; i < frameCount4; ++i) {
  74200. int32x4_t lefti;
  74201. int32x4_t righti;
  74202. float32x4_t leftf;
  74203. float32x4_t rightf;
  74204. uint32x4_t mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  74205. uint32x4_t side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  74206. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  74207. lefti = vshrq_n_s32(vreinterpretq_s32_u32(vaddq_u32(mid, side)), 1);
  74208. righti = vshrq_n_s32(vreinterpretq_s32_u32(vsubq_u32(mid, side)), 1);
  74209. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  74210. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  74211. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  74212. }
  74213. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74214. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74215. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74216. mid = (mid << 1) | (side & 0x01);
  74217. pOutputSamples[i*2+0] = ((drflac_int32)(mid + side) >> 1) * factor;
  74218. pOutputSamples[i*2+1] = ((drflac_int32)(mid - side) >> 1) * factor;
  74219. }
  74220. } else {
  74221. shift -= 1;
  74222. shift4 = vdupq_n_s32(shift);
  74223. for (i = 0; i < frameCount4; ++i) {
  74224. uint32x4_t mid;
  74225. uint32x4_t side;
  74226. int32x4_t lefti;
  74227. int32x4_t righti;
  74228. float32x4_t leftf;
  74229. float32x4_t rightf;
  74230. mid = vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), wbps0_4);
  74231. side = vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), wbps1_4);
  74232. mid = vorrq_u32(vshlq_n_u32(mid, 1), vandq_u32(side, vdupq_n_u32(1)));
  74233. lefti = vreinterpretq_s32_u32(vshlq_u32(vaddq_u32(mid, side), shift4));
  74234. righti = vreinterpretq_s32_u32(vshlq_u32(vsubq_u32(mid, side), shift4));
  74235. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  74236. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  74237. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  74238. }
  74239. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74240. drflac_uint32 mid = pInputSamples0U32[i] << pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74241. drflac_uint32 side = pInputSamples1U32[i] << pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74242. mid = (mid << 1) | (side & 0x01);
  74243. pOutputSamples[i*2+0] = (drflac_int32)((mid + side) << shift) * factor;
  74244. pOutputSamples[i*2+1] = (drflac_int32)((mid - side) << shift) * factor;
  74245. }
  74246. }
  74247. }
  74248. #endif
  74249. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_mid_side(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74250. {
  74251. #if defined(DRFLAC_SUPPORT_SSE2)
  74252. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74253. drflac_read_pcm_frames_f32__decode_mid_side__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74254. } else
  74255. #elif defined(DRFLAC_SUPPORT_NEON)
  74256. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74257. drflac_read_pcm_frames_f32__decode_mid_side__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74258. } else
  74259. #endif
  74260. {
  74261. #if 0
  74262. drflac_read_pcm_frames_f32__decode_mid_side__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74263. #else
  74264. drflac_read_pcm_frames_f32__decode_mid_side__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74265. #endif
  74266. }
  74267. }
  74268. #if 0
  74269. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__reference(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74270. {
  74271. for (drflac_uint64 i = 0; i < frameCount; ++i) {
  74272. pOutputSamples[i*2+0] = (float)((drflac_int32)((drflac_uint32)pInputSamples0[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample)) / 2147483648.0);
  74273. pOutputSamples[i*2+1] = (float)((drflac_int32)((drflac_uint32)pInputSamples1[i] << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample)) / 2147483648.0);
  74274. }
  74275. }
  74276. #endif
  74277. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74278. {
  74279. drflac_uint64 i;
  74280. drflac_uint64 frameCount4 = frameCount >> 2;
  74281. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74282. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74283. drflac_uint32 shift0 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample;
  74284. drflac_uint32 shift1 = unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample;
  74285. float factor = 1 / 2147483648.0;
  74286. for (i = 0; i < frameCount4; ++i) {
  74287. drflac_uint32 tempL0 = pInputSamples0U32[i*4+0] << shift0;
  74288. drflac_uint32 tempL1 = pInputSamples0U32[i*4+1] << shift0;
  74289. drflac_uint32 tempL2 = pInputSamples0U32[i*4+2] << shift0;
  74290. drflac_uint32 tempL3 = pInputSamples0U32[i*4+3] << shift0;
  74291. drflac_uint32 tempR0 = pInputSamples1U32[i*4+0] << shift1;
  74292. drflac_uint32 tempR1 = pInputSamples1U32[i*4+1] << shift1;
  74293. drflac_uint32 tempR2 = pInputSamples1U32[i*4+2] << shift1;
  74294. drflac_uint32 tempR3 = pInputSamples1U32[i*4+3] << shift1;
  74295. pOutputSamples[i*8+0] = (drflac_int32)tempL0 * factor;
  74296. pOutputSamples[i*8+1] = (drflac_int32)tempR0 * factor;
  74297. pOutputSamples[i*8+2] = (drflac_int32)tempL1 * factor;
  74298. pOutputSamples[i*8+3] = (drflac_int32)tempR1 * factor;
  74299. pOutputSamples[i*8+4] = (drflac_int32)tempL2 * factor;
  74300. pOutputSamples[i*8+5] = (drflac_int32)tempR2 * factor;
  74301. pOutputSamples[i*8+6] = (drflac_int32)tempL3 * factor;
  74302. pOutputSamples[i*8+7] = (drflac_int32)tempR3 * factor;
  74303. }
  74304. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74305. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  74306. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  74307. }
  74308. }
  74309. #if defined(DRFLAC_SUPPORT_SSE2)
  74310. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74311. {
  74312. drflac_uint64 i;
  74313. drflac_uint64 frameCount4 = frameCount >> 2;
  74314. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74315. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74316. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  74317. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  74318. float factor = 1.0f / 8388608.0f;
  74319. __m128 factor128 = _mm_set1_ps(factor);
  74320. for (i = 0; i < frameCount4; ++i) {
  74321. __m128i lefti;
  74322. __m128i righti;
  74323. __m128 leftf;
  74324. __m128 rightf;
  74325. lefti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples0 + i), shift0);
  74326. righti = _mm_slli_epi32(_mm_loadu_si128((const __m128i*)pInputSamples1 + i), shift1);
  74327. leftf = _mm_mul_ps(_mm_cvtepi32_ps(lefti), factor128);
  74328. rightf = _mm_mul_ps(_mm_cvtepi32_ps(righti), factor128);
  74329. _mm_storeu_ps(pOutputSamples + i*8 + 0, _mm_unpacklo_ps(leftf, rightf));
  74330. _mm_storeu_ps(pOutputSamples + i*8 + 4, _mm_unpackhi_ps(leftf, rightf));
  74331. }
  74332. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74333. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  74334. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  74335. }
  74336. }
  74337. #endif
  74338. #if defined(DRFLAC_SUPPORT_NEON)
  74339. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo__neon(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74340. {
  74341. drflac_uint64 i;
  74342. drflac_uint64 frameCount4 = frameCount >> 2;
  74343. const drflac_uint32* pInputSamples0U32 = (const drflac_uint32*)pInputSamples0;
  74344. const drflac_uint32* pInputSamples1U32 = (const drflac_uint32*)pInputSamples1;
  74345. drflac_uint32 shift0 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[0].wastedBitsPerSample) - 8;
  74346. drflac_uint32 shift1 = (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[1].wastedBitsPerSample) - 8;
  74347. float factor = 1.0f / 8388608.0f;
  74348. float32x4_t factor4 = vdupq_n_f32(factor);
  74349. int32x4_t shift0_4 = vdupq_n_s32(shift0);
  74350. int32x4_t shift1_4 = vdupq_n_s32(shift1);
  74351. for (i = 0; i < frameCount4; ++i) {
  74352. int32x4_t lefti;
  74353. int32x4_t righti;
  74354. float32x4_t leftf;
  74355. float32x4_t rightf;
  74356. lefti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples0U32 + i*4), shift0_4));
  74357. righti = vreinterpretq_s32_u32(vshlq_u32(vld1q_u32(pInputSamples1U32 + i*4), shift1_4));
  74358. leftf = vmulq_f32(vcvtq_f32_s32(lefti), factor4);
  74359. rightf = vmulq_f32(vcvtq_f32_s32(righti), factor4);
  74360. drflac__vst2q_f32(pOutputSamples + i*8, vzipq_f32(leftf, rightf));
  74361. }
  74362. for (i = (frameCount4 << 2); i < frameCount; ++i) {
  74363. pOutputSamples[i*2+0] = (drflac_int32)(pInputSamples0U32[i] << shift0) * factor;
  74364. pOutputSamples[i*2+1] = (drflac_int32)(pInputSamples1U32[i] << shift1) * factor;
  74365. }
  74366. }
  74367. #endif
  74368. static DRFLAC_INLINE void drflac_read_pcm_frames_f32__decode_independent_stereo(drflac* pFlac, drflac_uint64 frameCount, drflac_uint32 unusedBitsPerSample, const drflac_int32* pInputSamples0, const drflac_int32* pInputSamples1, float* pOutputSamples)
  74369. {
  74370. #if defined(DRFLAC_SUPPORT_SSE2)
  74371. if (drflac__gIsSSE2Supported && pFlac->bitsPerSample <= 24) {
  74372. drflac_read_pcm_frames_f32__decode_independent_stereo__sse2(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74373. } else
  74374. #elif defined(DRFLAC_SUPPORT_NEON)
  74375. if (drflac__gIsNEONSupported && pFlac->bitsPerSample <= 24) {
  74376. drflac_read_pcm_frames_f32__decode_independent_stereo__neon(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74377. } else
  74378. #endif
  74379. {
  74380. #if 0
  74381. drflac_read_pcm_frames_f32__decode_independent_stereo__reference(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74382. #else
  74383. drflac_read_pcm_frames_f32__decode_independent_stereo__scalar(pFlac, frameCount, unusedBitsPerSample, pInputSamples0, pInputSamples1, pOutputSamples);
  74384. #endif
  74385. }
  74386. }
  74387. DRFLAC_API drflac_uint64 drflac_read_pcm_frames_f32(drflac* pFlac, drflac_uint64 framesToRead, float* pBufferOut)
  74388. {
  74389. drflac_uint64 framesRead;
  74390. drflac_uint32 unusedBitsPerSample;
  74391. if (pFlac == NULL || framesToRead == 0) {
  74392. return 0;
  74393. }
  74394. if (pBufferOut == NULL) {
  74395. return drflac__seek_forward_by_pcm_frames(pFlac, framesToRead);
  74396. }
  74397. DRFLAC_ASSERT(pFlac->bitsPerSample <= 32);
  74398. unusedBitsPerSample = 32 - pFlac->bitsPerSample;
  74399. framesRead = 0;
  74400. while (framesToRead > 0) {
  74401. if (pFlac->currentFLACFrame.pcmFramesRemaining == 0) {
  74402. if (!drflac__read_and_decode_next_flac_frame(pFlac)) {
  74403. break;
  74404. }
  74405. } else {
  74406. unsigned int channelCount = drflac__get_channel_count_from_channel_assignment(pFlac->currentFLACFrame.header.channelAssignment);
  74407. drflac_uint64 iFirstPCMFrame = pFlac->currentFLACFrame.header.blockSizeInPCMFrames - pFlac->currentFLACFrame.pcmFramesRemaining;
  74408. drflac_uint64 frameCountThisIteration = framesToRead;
  74409. if (frameCountThisIteration > pFlac->currentFLACFrame.pcmFramesRemaining) {
  74410. frameCountThisIteration = pFlac->currentFLACFrame.pcmFramesRemaining;
  74411. }
  74412. if (channelCount == 2) {
  74413. const drflac_int32* pDecodedSamples0 = pFlac->currentFLACFrame.subframes[0].pSamplesS32 + iFirstPCMFrame;
  74414. const drflac_int32* pDecodedSamples1 = pFlac->currentFLACFrame.subframes[1].pSamplesS32 + iFirstPCMFrame;
  74415. switch (pFlac->currentFLACFrame.header.channelAssignment)
  74416. {
  74417. case DRFLAC_CHANNEL_ASSIGNMENT_LEFT_SIDE:
  74418. {
  74419. drflac_read_pcm_frames_f32__decode_left_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74420. } break;
  74421. case DRFLAC_CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  74422. {
  74423. drflac_read_pcm_frames_f32__decode_right_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74424. } break;
  74425. case DRFLAC_CHANNEL_ASSIGNMENT_MID_SIDE:
  74426. {
  74427. drflac_read_pcm_frames_f32__decode_mid_side(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74428. } break;
  74429. case DRFLAC_CHANNEL_ASSIGNMENT_INDEPENDENT:
  74430. default:
  74431. {
  74432. drflac_read_pcm_frames_f32__decode_independent_stereo(pFlac, frameCountThisIteration, unusedBitsPerSample, pDecodedSamples0, pDecodedSamples1, pBufferOut);
  74433. } break;
  74434. }
  74435. } else {
  74436. drflac_uint64 i;
  74437. for (i = 0; i < frameCountThisIteration; ++i) {
  74438. unsigned int j;
  74439. for (j = 0; j < channelCount; ++j) {
  74440. drflac_int32 sampleS32 = (drflac_int32)((drflac_uint32)(pFlac->currentFLACFrame.subframes[j].pSamplesS32[iFirstPCMFrame + i]) << (unusedBitsPerSample + pFlac->currentFLACFrame.subframes[j].wastedBitsPerSample));
  74441. pBufferOut[(i*channelCount)+j] = (float)(sampleS32 / 2147483648.0);
  74442. }
  74443. }
  74444. }
  74445. framesRead += frameCountThisIteration;
  74446. pBufferOut += frameCountThisIteration * channelCount;
  74447. framesToRead -= frameCountThisIteration;
  74448. pFlac->currentPCMFrame += frameCountThisIteration;
  74449. pFlac->currentFLACFrame.pcmFramesRemaining -= (unsigned int)frameCountThisIteration;
  74450. }
  74451. }
  74452. return framesRead;
  74453. }
  74454. DRFLAC_API drflac_bool32 drflac_seek_to_pcm_frame(drflac* pFlac, drflac_uint64 pcmFrameIndex)
  74455. {
  74456. if (pFlac == NULL) {
  74457. return DRFLAC_FALSE;
  74458. }
  74459. if (pFlac->currentPCMFrame == pcmFrameIndex) {
  74460. return DRFLAC_TRUE;
  74461. }
  74462. if (pFlac->firstFLACFramePosInBytes == 0) {
  74463. return DRFLAC_FALSE;
  74464. }
  74465. if (pcmFrameIndex == 0) {
  74466. pFlac->currentPCMFrame = 0;
  74467. return drflac__seek_to_first_frame(pFlac);
  74468. } else {
  74469. drflac_bool32 wasSuccessful = DRFLAC_FALSE;
  74470. drflac_uint64 originalPCMFrame = pFlac->currentPCMFrame;
  74471. if (pcmFrameIndex > pFlac->totalPCMFrameCount) {
  74472. pcmFrameIndex = pFlac->totalPCMFrameCount;
  74473. }
  74474. if (pcmFrameIndex > pFlac->currentPCMFrame) {
  74475. drflac_uint32 offset = (drflac_uint32)(pcmFrameIndex - pFlac->currentPCMFrame);
  74476. if (pFlac->currentFLACFrame.pcmFramesRemaining > offset) {
  74477. pFlac->currentFLACFrame.pcmFramesRemaining -= offset;
  74478. pFlac->currentPCMFrame = pcmFrameIndex;
  74479. return DRFLAC_TRUE;
  74480. }
  74481. } else {
  74482. drflac_uint32 offsetAbs = (drflac_uint32)(pFlac->currentPCMFrame - pcmFrameIndex);
  74483. drflac_uint32 currentFLACFramePCMFrameCount = pFlac->currentFLACFrame.header.blockSizeInPCMFrames;
  74484. drflac_uint32 currentFLACFramePCMFramesConsumed = currentFLACFramePCMFrameCount - pFlac->currentFLACFrame.pcmFramesRemaining;
  74485. if (currentFLACFramePCMFramesConsumed > offsetAbs) {
  74486. pFlac->currentFLACFrame.pcmFramesRemaining += offsetAbs;
  74487. pFlac->currentPCMFrame = pcmFrameIndex;
  74488. return DRFLAC_TRUE;
  74489. }
  74490. }
  74491. #ifndef DR_FLAC_NO_OGG
  74492. if (pFlac->container == drflac_container_ogg)
  74493. {
  74494. wasSuccessful = drflac_ogg__seek_to_pcm_frame(pFlac, pcmFrameIndex);
  74495. }
  74496. else
  74497. #endif
  74498. {
  74499. if (!pFlac->_noSeekTableSeek) {
  74500. wasSuccessful = drflac__seek_to_pcm_frame__seek_table(pFlac, pcmFrameIndex);
  74501. }
  74502. #if !defined(DR_FLAC_NO_CRC)
  74503. if (!wasSuccessful && !pFlac->_noBinarySearchSeek && pFlac->totalPCMFrameCount > 0) {
  74504. wasSuccessful = drflac__seek_to_pcm_frame__binary_search(pFlac, pcmFrameIndex);
  74505. }
  74506. #endif
  74507. if (!wasSuccessful && !pFlac->_noBruteForceSeek) {
  74508. wasSuccessful = drflac__seek_to_pcm_frame__brute_force(pFlac, pcmFrameIndex);
  74509. }
  74510. }
  74511. if (wasSuccessful) {
  74512. pFlac->currentPCMFrame = pcmFrameIndex;
  74513. } else {
  74514. if (drflac_seek_to_pcm_frame(pFlac, originalPCMFrame) == DRFLAC_FALSE) {
  74515. drflac_seek_to_pcm_frame(pFlac, 0);
  74516. }
  74517. }
  74518. return wasSuccessful;
  74519. }
  74520. }
  74521. #if defined(SIZE_MAX)
  74522. #define DRFLAC_SIZE_MAX SIZE_MAX
  74523. #else
  74524. #if defined(DRFLAC_64BIT)
  74525. #define DRFLAC_SIZE_MAX ((drflac_uint64)0xFFFFFFFFFFFFFFFF)
  74526. #else
  74527. #define DRFLAC_SIZE_MAX 0xFFFFFFFF
  74528. #endif
  74529. #endif
  74530. #define DRFLAC_DEFINE_FULL_READ_AND_CLOSE(extension, type) \
  74531. static type* drflac__full_read_and_close_ ## extension (drflac* pFlac, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut)\
  74532. { \
  74533. type* pSampleData = NULL; \
  74534. drflac_uint64 totalPCMFrameCount; \
  74535. \
  74536. DRFLAC_ASSERT(pFlac != NULL); \
  74537. \
  74538. totalPCMFrameCount = pFlac->totalPCMFrameCount; \
  74539. \
  74540. if (totalPCMFrameCount == 0) { \
  74541. type buffer[4096]; \
  74542. drflac_uint64 pcmFramesRead; \
  74543. size_t sampleDataBufferSize = sizeof(buffer); \
  74544. \
  74545. pSampleData = (type*)drflac__malloc_from_callbacks(sampleDataBufferSize, &pFlac->allocationCallbacks); \
  74546. if (pSampleData == NULL) { \
  74547. goto on_error; \
  74548. } \
  74549. \
  74550. while ((pcmFramesRead = (drflac_uint64)drflac_read_pcm_frames_##extension(pFlac, sizeof(buffer)/sizeof(buffer[0])/pFlac->channels, buffer)) > 0) { \
  74551. if (((totalPCMFrameCount + pcmFramesRead) * pFlac->channels * sizeof(type)) > sampleDataBufferSize) { \
  74552. type* pNewSampleData; \
  74553. size_t newSampleDataBufferSize; \
  74554. \
  74555. newSampleDataBufferSize = sampleDataBufferSize * 2; \
  74556. pNewSampleData = (type*)drflac__realloc_from_callbacks(pSampleData, newSampleDataBufferSize, sampleDataBufferSize, &pFlac->allocationCallbacks); \
  74557. if (pNewSampleData == NULL) { \
  74558. drflac__free_from_callbacks(pSampleData, &pFlac->allocationCallbacks); \
  74559. goto on_error; \
  74560. } \
  74561. \
  74562. sampleDataBufferSize = newSampleDataBufferSize; \
  74563. pSampleData = pNewSampleData; \
  74564. } \
  74565. \
  74566. DRFLAC_COPY_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), buffer, (size_t)(pcmFramesRead*pFlac->channels*sizeof(type))); \
  74567. totalPCMFrameCount += pcmFramesRead; \
  74568. } \
  74569. \
  74570. \
  74571. DRFLAC_ZERO_MEMORY(pSampleData + (totalPCMFrameCount*pFlac->channels), (size_t)(sampleDataBufferSize - totalPCMFrameCount*pFlac->channels*sizeof(type))); \
  74572. } else { \
  74573. drflac_uint64 dataSize = totalPCMFrameCount*pFlac->channels*sizeof(type); \
  74574. if (dataSize > (drflac_uint64)DRFLAC_SIZE_MAX) { \
  74575. goto on_error; \
  74576. } \
  74577. \
  74578. pSampleData = (type*)drflac__malloc_from_callbacks((size_t)dataSize, &pFlac->allocationCallbacks); \
  74579. if (pSampleData == NULL) { \
  74580. goto on_error; \
  74581. } \
  74582. \
  74583. totalPCMFrameCount = drflac_read_pcm_frames_##extension(pFlac, pFlac->totalPCMFrameCount, pSampleData); \
  74584. } \
  74585. \
  74586. if (sampleRateOut) *sampleRateOut = pFlac->sampleRate; \
  74587. if (channelsOut) *channelsOut = pFlac->channels; \
  74588. if (totalPCMFrameCountOut) *totalPCMFrameCountOut = totalPCMFrameCount; \
  74589. \
  74590. drflac_close(pFlac); \
  74591. return pSampleData; \
  74592. \
  74593. on_error: \
  74594. drflac_close(pFlac); \
  74595. return NULL; \
  74596. }
  74597. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s32, drflac_int32)
  74598. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(s16, drflac_int16)
  74599. DRFLAC_DEFINE_FULL_READ_AND_CLOSE(f32, float)
  74600. DRFLAC_API drflac_int32* drflac_open_and_read_pcm_frames_s32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  74601. {
  74602. drflac* pFlac;
  74603. if (channelsOut) {
  74604. *channelsOut = 0;
  74605. }
  74606. if (sampleRateOut) {
  74607. *sampleRateOut = 0;
  74608. }
  74609. if (totalPCMFrameCountOut) {
  74610. *totalPCMFrameCountOut = 0;
  74611. }
  74612. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  74613. if (pFlac == NULL) {
  74614. return NULL;
  74615. }
  74616. return drflac__full_read_and_close_s32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  74617. }
  74618. DRFLAC_API drflac_int16* drflac_open_and_read_pcm_frames_s16(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  74619. {
  74620. drflac* pFlac;
  74621. if (channelsOut) {
  74622. *channelsOut = 0;
  74623. }
  74624. if (sampleRateOut) {
  74625. *sampleRateOut = 0;
  74626. }
  74627. if (totalPCMFrameCountOut) {
  74628. *totalPCMFrameCountOut = 0;
  74629. }
  74630. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  74631. if (pFlac == NULL) {
  74632. return NULL;
  74633. }
  74634. return drflac__full_read_and_close_s16(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  74635. }
  74636. DRFLAC_API float* drflac_open_and_read_pcm_frames_f32(drflac_read_proc onRead, drflac_seek_proc onSeek, void* pUserData, unsigned int* channelsOut, unsigned int* sampleRateOut, drflac_uint64* totalPCMFrameCountOut, const drflac_allocation_callbacks* pAllocationCallbacks)
  74637. {
  74638. drflac* pFlac;
  74639. if (channelsOut) {
  74640. *channelsOut = 0;
  74641. }
  74642. if (sampleRateOut) {
  74643. *sampleRateOut = 0;
  74644. }
  74645. if (totalPCMFrameCountOut) {
  74646. *totalPCMFrameCountOut = 0;
  74647. }
  74648. pFlac = drflac_open(onRead, onSeek, pUserData, pAllocationCallbacks);
  74649. if (pFlac == NULL) {
  74650. return NULL;
  74651. }
  74652. return drflac__full_read_and_close_f32(pFlac, channelsOut, sampleRateOut, totalPCMFrameCountOut);
  74653. }
  74654. #ifndef DR_FLAC_NO_STDIO
  74655. DRFLAC_API drflac_int32* drflac_open_file_and_read_pcm_frames_s32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74656. {
  74657. drflac* pFlac;
  74658. if (sampleRate) {
  74659. *sampleRate = 0;
  74660. }
  74661. if (channels) {
  74662. *channels = 0;
  74663. }
  74664. if (totalPCMFrameCount) {
  74665. *totalPCMFrameCount = 0;
  74666. }
  74667. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  74668. if (pFlac == NULL) {
  74669. return NULL;
  74670. }
  74671. return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  74672. }
  74673. DRFLAC_API drflac_int16* drflac_open_file_and_read_pcm_frames_s16(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74674. {
  74675. drflac* pFlac;
  74676. if (sampleRate) {
  74677. *sampleRate = 0;
  74678. }
  74679. if (channels) {
  74680. *channels = 0;
  74681. }
  74682. if (totalPCMFrameCount) {
  74683. *totalPCMFrameCount = 0;
  74684. }
  74685. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  74686. if (pFlac == NULL) {
  74687. return NULL;
  74688. }
  74689. return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  74690. }
  74691. DRFLAC_API float* drflac_open_file_and_read_pcm_frames_f32(const char* filename, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74692. {
  74693. drflac* pFlac;
  74694. if (sampleRate) {
  74695. *sampleRate = 0;
  74696. }
  74697. if (channels) {
  74698. *channels = 0;
  74699. }
  74700. if (totalPCMFrameCount) {
  74701. *totalPCMFrameCount = 0;
  74702. }
  74703. pFlac = drflac_open_file(filename, pAllocationCallbacks);
  74704. if (pFlac == NULL) {
  74705. return NULL;
  74706. }
  74707. return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  74708. }
  74709. #endif
  74710. DRFLAC_API drflac_int32* drflac_open_memory_and_read_pcm_frames_s32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74711. {
  74712. drflac* pFlac;
  74713. if (sampleRate) {
  74714. *sampleRate = 0;
  74715. }
  74716. if (channels) {
  74717. *channels = 0;
  74718. }
  74719. if (totalPCMFrameCount) {
  74720. *totalPCMFrameCount = 0;
  74721. }
  74722. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  74723. if (pFlac == NULL) {
  74724. return NULL;
  74725. }
  74726. return drflac__full_read_and_close_s32(pFlac, channels, sampleRate, totalPCMFrameCount);
  74727. }
  74728. DRFLAC_API drflac_int16* drflac_open_memory_and_read_pcm_frames_s16(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74729. {
  74730. drflac* pFlac;
  74731. if (sampleRate) {
  74732. *sampleRate = 0;
  74733. }
  74734. if (channels) {
  74735. *channels = 0;
  74736. }
  74737. if (totalPCMFrameCount) {
  74738. *totalPCMFrameCount = 0;
  74739. }
  74740. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  74741. if (pFlac == NULL) {
  74742. return NULL;
  74743. }
  74744. return drflac__full_read_and_close_s16(pFlac, channels, sampleRate, totalPCMFrameCount);
  74745. }
  74746. DRFLAC_API float* drflac_open_memory_and_read_pcm_frames_f32(const void* data, size_t dataSize, unsigned int* channels, unsigned int* sampleRate, drflac_uint64* totalPCMFrameCount, const drflac_allocation_callbacks* pAllocationCallbacks)
  74747. {
  74748. drflac* pFlac;
  74749. if (sampleRate) {
  74750. *sampleRate = 0;
  74751. }
  74752. if (channels) {
  74753. *channels = 0;
  74754. }
  74755. if (totalPCMFrameCount) {
  74756. *totalPCMFrameCount = 0;
  74757. }
  74758. pFlac = drflac_open_memory(data, dataSize, pAllocationCallbacks);
  74759. if (pFlac == NULL) {
  74760. return NULL;
  74761. }
  74762. return drflac__full_read_and_close_f32(pFlac, channels, sampleRate, totalPCMFrameCount);
  74763. }
  74764. DRFLAC_API void drflac_free(void* p, const drflac_allocation_callbacks* pAllocationCallbacks)
  74765. {
  74766. if (pAllocationCallbacks != NULL) {
  74767. drflac__free_from_callbacks(p, pAllocationCallbacks);
  74768. } else {
  74769. drflac__free_default(p, NULL);
  74770. }
  74771. }
  74772. DRFLAC_API void drflac_init_vorbis_comment_iterator(drflac_vorbis_comment_iterator* pIter, drflac_uint32 commentCount, const void* pComments)
  74773. {
  74774. if (pIter == NULL) {
  74775. return;
  74776. }
  74777. pIter->countRemaining = commentCount;
  74778. pIter->pRunningData = (const char*)pComments;
  74779. }
  74780. DRFLAC_API const char* drflac_next_vorbis_comment(drflac_vorbis_comment_iterator* pIter, drflac_uint32* pCommentLengthOut)
  74781. {
  74782. drflac_int32 length;
  74783. const char* pComment;
  74784. if (pCommentLengthOut) {
  74785. *pCommentLengthOut = 0;
  74786. }
  74787. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  74788. return NULL;
  74789. }
  74790. length = drflac__le2host_32_ptr_unaligned(pIter->pRunningData);
  74791. pIter->pRunningData += 4;
  74792. pComment = pIter->pRunningData;
  74793. pIter->pRunningData += length;
  74794. pIter->countRemaining -= 1;
  74795. if (pCommentLengthOut) {
  74796. *pCommentLengthOut = length;
  74797. }
  74798. return pComment;
  74799. }
  74800. DRFLAC_API void drflac_init_cuesheet_track_iterator(drflac_cuesheet_track_iterator* pIter, drflac_uint32 trackCount, const void* pTrackData)
  74801. {
  74802. if (pIter == NULL) {
  74803. return;
  74804. }
  74805. pIter->countRemaining = trackCount;
  74806. pIter->pRunningData = (const char*)pTrackData;
  74807. }
  74808. DRFLAC_API drflac_bool32 drflac_next_cuesheet_track(drflac_cuesheet_track_iterator* pIter, drflac_cuesheet_track* pCuesheetTrack)
  74809. {
  74810. drflac_cuesheet_track cuesheetTrack;
  74811. const char* pRunningData;
  74812. drflac_uint64 offsetHi;
  74813. drflac_uint64 offsetLo;
  74814. if (pIter == NULL || pIter->countRemaining == 0 || pIter->pRunningData == NULL) {
  74815. return DRFLAC_FALSE;
  74816. }
  74817. pRunningData = pIter->pRunningData;
  74818. offsetHi = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  74819. offsetLo = drflac__be2host_32(*(const drflac_uint32*)pRunningData); pRunningData += 4;
  74820. cuesheetTrack.offset = offsetLo | (offsetHi << 32);
  74821. cuesheetTrack.trackNumber = pRunningData[0]; pRunningData += 1;
  74822. DRFLAC_COPY_MEMORY(cuesheetTrack.ISRC, pRunningData, sizeof(cuesheetTrack.ISRC)); pRunningData += 12;
  74823. cuesheetTrack.isAudio = (pRunningData[0] & 0x80) != 0;
  74824. cuesheetTrack.preEmphasis = (pRunningData[0] & 0x40) != 0; pRunningData += 14;
  74825. cuesheetTrack.indexCount = pRunningData[0]; pRunningData += 1;
  74826. cuesheetTrack.pIndexPoints = (const drflac_cuesheet_track_index*)pRunningData; pRunningData += cuesheetTrack.indexCount * sizeof(drflac_cuesheet_track_index);
  74827. pIter->pRunningData = pRunningData;
  74828. pIter->countRemaining -= 1;
  74829. if (pCuesheetTrack) {
  74830. *pCuesheetTrack = cuesheetTrack;
  74831. }
  74832. return DRFLAC_TRUE;
  74833. }
  74834. #if defined(__clang__) || (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)))
  74835. #pragma GCC diagnostic pop
  74836. #endif
  74837. #endif
  74838. /* dr_flac_c end */
  74839. #endif /* DRFLAC_IMPLEMENTATION */
  74840. #endif /* MA_NO_FLAC */
  74841. #if !defined(MA_NO_MP3) && !defined(MA_NO_DECODING)
  74842. #if !defined(DR_MP3_IMPLEMENTATION) && !defined(DRMP3_IMPLEMENTATION) /* For backwards compatibility. Will be removed in version 0.11 for cleanliness. */
  74843. /* dr_mp3_c begin */
  74844. #ifndef dr_mp3_c
  74845. #define dr_mp3_c
  74846. #include <stdlib.h>
  74847. #include <string.h>
  74848. #include <limits.h>
  74849. DRMP3_API void drmp3_version(drmp3_uint32* pMajor, drmp3_uint32* pMinor, drmp3_uint32* pRevision)
  74850. {
  74851. if (pMajor) {
  74852. *pMajor = DRMP3_VERSION_MAJOR;
  74853. }
  74854. if (pMinor) {
  74855. *pMinor = DRMP3_VERSION_MINOR;
  74856. }
  74857. if (pRevision) {
  74858. *pRevision = DRMP3_VERSION_REVISION;
  74859. }
  74860. }
  74861. DRMP3_API const char* drmp3_version_string(void)
  74862. {
  74863. return DRMP3_VERSION_STRING;
  74864. }
  74865. #if defined(__TINYC__)
  74866. #define DR_MP3_NO_SIMD
  74867. #endif
  74868. #define DRMP3_OFFSET_PTR(p, offset) ((void*)((drmp3_uint8*)(p) + (offset)))
  74869. #define DRMP3_MAX_FREE_FORMAT_FRAME_SIZE 2304
  74870. #ifndef DRMP3_MAX_FRAME_SYNC_MATCHES
  74871. #define DRMP3_MAX_FRAME_SYNC_MATCHES 10
  74872. #endif
  74873. #define DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES DRMP3_MAX_FREE_FORMAT_FRAME_SIZE
  74874. #define DRMP3_MAX_BITRESERVOIR_BYTES 511
  74875. #define DRMP3_SHORT_BLOCK_TYPE 2
  74876. #define DRMP3_STOP_BLOCK_TYPE 3
  74877. #define DRMP3_MODE_MONO 3
  74878. #define DRMP3_MODE_JOINT_STEREO 1
  74879. #define DRMP3_HDR_SIZE 4
  74880. #define DRMP3_HDR_IS_MONO(h) (((h[3]) & 0xC0) == 0xC0)
  74881. #define DRMP3_HDR_IS_MS_STEREO(h) (((h[3]) & 0xE0) == 0x60)
  74882. #define DRMP3_HDR_IS_FREE_FORMAT(h) (((h[2]) & 0xF0) == 0)
  74883. #define DRMP3_HDR_IS_CRC(h) (!((h[1]) & 1))
  74884. #define DRMP3_HDR_TEST_PADDING(h) ((h[2]) & 0x2)
  74885. #define DRMP3_HDR_TEST_MPEG1(h) ((h[1]) & 0x8)
  74886. #define DRMP3_HDR_TEST_NOT_MPEG25(h) ((h[1]) & 0x10)
  74887. #define DRMP3_HDR_TEST_I_STEREO(h) ((h[3]) & 0x10)
  74888. #define DRMP3_HDR_TEST_MS_STEREO(h) ((h[3]) & 0x20)
  74889. #define DRMP3_HDR_GET_STEREO_MODE(h) (((h[3]) >> 6) & 3)
  74890. #define DRMP3_HDR_GET_STEREO_MODE_EXT(h) (((h[3]) >> 4) & 3)
  74891. #define DRMP3_HDR_GET_LAYER(h) (((h[1]) >> 1) & 3)
  74892. #define DRMP3_HDR_GET_BITRATE(h) ((h[2]) >> 4)
  74893. #define DRMP3_HDR_GET_SAMPLE_RATE(h) (((h[2]) >> 2) & 3)
  74894. #define DRMP3_HDR_GET_MY_SAMPLE_RATE(h) (DRMP3_HDR_GET_SAMPLE_RATE(h) + (((h[1] >> 3) & 1) + ((h[1] >> 4) & 1))*3)
  74895. #define DRMP3_HDR_IS_FRAME_576(h) ((h[1] & 14) == 2)
  74896. #define DRMP3_HDR_IS_LAYER_1(h) ((h[1] & 6) == 6)
  74897. #define DRMP3_BITS_DEQUANTIZER_OUT -1
  74898. #define DRMP3_MAX_SCF (255 + DRMP3_BITS_DEQUANTIZER_OUT*4 - 210)
  74899. #define DRMP3_MAX_SCFI ((DRMP3_MAX_SCF + 3) & ~3)
  74900. #define DRMP3_MIN(a, b) ((a) > (b) ? (b) : (a))
  74901. #define DRMP3_MAX(a, b) ((a) < (b) ? (b) : (a))
  74902. #if !defined(DR_MP3_NO_SIMD)
  74903. #if !defined(DR_MP3_ONLY_SIMD) && (defined(_M_X64) || defined(__x86_64__) || defined(__aarch64__) || defined(_M_ARM64))
  74904. #define DR_MP3_ONLY_SIMD
  74905. #endif
  74906. #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__)))
  74907. #if defined(_MSC_VER)
  74908. #include <intrin.h>
  74909. #endif
  74910. #include <emmintrin.h>
  74911. #define DRMP3_HAVE_SSE 1
  74912. #define DRMP3_HAVE_SIMD 1
  74913. #define DRMP3_VSTORE _mm_storeu_ps
  74914. #define DRMP3_VLD _mm_loadu_ps
  74915. #define DRMP3_VSET _mm_set1_ps
  74916. #define DRMP3_VADD _mm_add_ps
  74917. #define DRMP3_VSUB _mm_sub_ps
  74918. #define DRMP3_VMUL _mm_mul_ps
  74919. #define DRMP3_VMAC(a, x, y) _mm_add_ps(a, _mm_mul_ps(x, y))
  74920. #define DRMP3_VMSB(a, x, y) _mm_sub_ps(a, _mm_mul_ps(x, y))
  74921. #define DRMP3_VMUL_S(x, s) _mm_mul_ps(x, _mm_set1_ps(s))
  74922. #define DRMP3_VREV(x) _mm_shuffle_ps(x, x, _MM_SHUFFLE(0, 1, 2, 3))
  74923. typedef __m128 drmp3_f4;
  74924. #if defined(_MSC_VER) || defined(DR_MP3_ONLY_SIMD)
  74925. #define drmp3_cpuid __cpuid
  74926. #else
  74927. static __inline__ __attribute__((always_inline)) void drmp3_cpuid(int CPUInfo[], const int InfoType)
  74928. {
  74929. #if defined(__PIC__)
  74930. __asm__ __volatile__(
  74931. #if defined(__x86_64__)
  74932. "push %%rbx\n"
  74933. "cpuid\n"
  74934. "xchgl %%ebx, %1\n"
  74935. "pop %%rbx\n"
  74936. #else
  74937. "xchgl %%ebx, %1\n"
  74938. "cpuid\n"
  74939. "xchgl %%ebx, %1\n"
  74940. #endif
  74941. : "=a" (CPUInfo[0]), "=r" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  74942. : "a" (InfoType));
  74943. #else
  74944. __asm__ __volatile__(
  74945. "cpuid"
  74946. : "=a" (CPUInfo[0]), "=b" (CPUInfo[1]), "=c" (CPUInfo[2]), "=d" (CPUInfo[3])
  74947. : "a" (InfoType));
  74948. #endif
  74949. }
  74950. #endif
  74951. static int drmp3_have_simd(void)
  74952. {
  74953. #ifdef DR_MP3_ONLY_SIMD
  74954. return 1;
  74955. #else
  74956. static int g_have_simd;
  74957. int CPUInfo[4];
  74958. #ifdef MINIMP3_TEST
  74959. static int g_counter;
  74960. if (g_counter++ > 100)
  74961. return 0;
  74962. #endif
  74963. if (g_have_simd)
  74964. goto end;
  74965. drmp3_cpuid(CPUInfo, 0);
  74966. if (CPUInfo[0] > 0)
  74967. {
  74968. drmp3_cpuid(CPUInfo, 1);
  74969. g_have_simd = (CPUInfo[3] & (1 << 26)) + 1;
  74970. return g_have_simd - 1;
  74971. }
  74972. end:
  74973. return g_have_simd - 1;
  74974. #endif
  74975. }
  74976. #elif defined(__ARM_NEON) || defined(__aarch64__) || defined(_M_ARM64)
  74977. #include <arm_neon.h>
  74978. #define DRMP3_HAVE_SSE 0
  74979. #define DRMP3_HAVE_SIMD 1
  74980. #define DRMP3_VSTORE vst1q_f32
  74981. #define DRMP3_VLD vld1q_f32
  74982. #define DRMP3_VSET vmovq_n_f32
  74983. #define DRMP3_VADD vaddq_f32
  74984. #define DRMP3_VSUB vsubq_f32
  74985. #define DRMP3_VMUL vmulq_f32
  74986. #define DRMP3_VMAC(a, x, y) vmlaq_f32(a, x, y)
  74987. #define DRMP3_VMSB(a, x, y) vmlsq_f32(a, x, y)
  74988. #define DRMP3_VMUL_S(x, s) vmulq_f32(x, vmovq_n_f32(s))
  74989. #define DRMP3_VREV(x) vcombine_f32(vget_high_f32(vrev64q_f32(x)), vget_low_f32(vrev64q_f32(x)))
  74990. typedef float32x4_t drmp3_f4;
  74991. static int drmp3_have_simd(void)
  74992. {
  74993. return 1;
  74994. }
  74995. #else
  74996. #define DRMP3_HAVE_SSE 0
  74997. #define DRMP3_HAVE_SIMD 0
  74998. #ifdef DR_MP3_ONLY_SIMD
  74999. #error DR_MP3_ONLY_SIMD used, but SSE/NEON not enabled
  75000. #endif
  75001. #endif
  75002. #else
  75003. #define DRMP3_HAVE_SIMD 0
  75004. #endif
  75005. #if defined(__ARM_ARCH) && (__ARM_ARCH >= 6) && !defined(__aarch64__) && !defined(_M_ARM64)
  75006. #define DRMP3_HAVE_ARMV6 1
  75007. static __inline__ __attribute__((always_inline)) drmp3_int32 drmp3_clip_int16_arm(drmp3_int32 a)
  75008. {
  75009. drmp3_int32 x = 0;
  75010. __asm__ ("ssat %0, #16, %1" : "=r"(x) : "r"(a));
  75011. return x;
  75012. }
  75013. #else
  75014. #define DRMP3_HAVE_ARMV6 0
  75015. #endif
  75016. #ifndef DRMP3_ASSERT
  75017. #include <assert.h>
  75018. #define DRMP3_ASSERT(expression) assert(expression)
  75019. #endif
  75020. #ifndef DRMP3_COPY_MEMORY
  75021. #define DRMP3_COPY_MEMORY(dst, src, sz) memcpy((dst), (src), (sz))
  75022. #endif
  75023. #ifndef DRMP3_MOVE_MEMORY
  75024. #define DRMP3_MOVE_MEMORY(dst, src, sz) memmove((dst), (src), (sz))
  75025. #endif
  75026. #ifndef DRMP3_ZERO_MEMORY
  75027. #define DRMP3_ZERO_MEMORY(p, sz) memset((p), 0, (sz))
  75028. #endif
  75029. #define DRMP3_ZERO_OBJECT(p) DRMP3_ZERO_MEMORY((p), sizeof(*(p)))
  75030. #ifndef DRMP3_MALLOC
  75031. #define DRMP3_MALLOC(sz) malloc((sz))
  75032. #endif
  75033. #ifndef DRMP3_REALLOC
  75034. #define DRMP3_REALLOC(p, sz) realloc((p), (sz))
  75035. #endif
  75036. #ifndef DRMP3_FREE
  75037. #define DRMP3_FREE(p) free((p))
  75038. #endif
  75039. typedef struct
  75040. {
  75041. const drmp3_uint8 *buf;
  75042. int pos, limit;
  75043. } drmp3_bs;
  75044. typedef struct
  75045. {
  75046. float scf[3*64];
  75047. drmp3_uint8 total_bands, stereo_bands, bitalloc[64], scfcod[64];
  75048. } drmp3_L12_scale_info;
  75049. typedef struct
  75050. {
  75051. drmp3_uint8 tab_offset, code_tab_width, band_count;
  75052. } drmp3_L12_subband_alloc;
  75053. typedef struct
  75054. {
  75055. const drmp3_uint8 *sfbtab;
  75056. drmp3_uint16 part_23_length, big_values, scalefac_compress;
  75057. drmp3_uint8 global_gain, block_type, mixed_block_flag, n_long_sfb, n_short_sfb;
  75058. drmp3_uint8 table_select[3], region_count[3], subblock_gain[3];
  75059. drmp3_uint8 preflag, scalefac_scale, count1_table, scfsi;
  75060. } drmp3_L3_gr_info;
  75061. typedef struct
  75062. {
  75063. drmp3_bs bs;
  75064. drmp3_uint8 maindata[DRMP3_MAX_BITRESERVOIR_BYTES + DRMP3_MAX_L3_FRAME_PAYLOAD_BYTES];
  75065. drmp3_L3_gr_info gr_info[4];
  75066. float grbuf[2][576], scf[40], syn[18 + 15][2*32];
  75067. drmp3_uint8 ist_pos[2][39];
  75068. } drmp3dec_scratch;
  75069. static void drmp3_bs_init(drmp3_bs *bs, const drmp3_uint8 *data, int bytes)
  75070. {
  75071. bs->buf = data;
  75072. bs->pos = 0;
  75073. bs->limit = bytes*8;
  75074. }
  75075. static drmp3_uint32 drmp3_bs_get_bits(drmp3_bs *bs, int n)
  75076. {
  75077. drmp3_uint32 next, cache = 0, s = bs->pos & 7;
  75078. int shl = n + s;
  75079. const drmp3_uint8 *p = bs->buf + (bs->pos >> 3);
  75080. if ((bs->pos += n) > bs->limit)
  75081. return 0;
  75082. next = *p++ & (255 >> s);
  75083. while ((shl -= 8) > 0)
  75084. {
  75085. cache |= next << shl;
  75086. next = *p++;
  75087. }
  75088. return cache | (next >> -shl);
  75089. }
  75090. static int drmp3_hdr_valid(const drmp3_uint8 *h)
  75091. {
  75092. return h[0] == 0xff &&
  75093. ((h[1] & 0xF0) == 0xf0 || (h[1] & 0xFE) == 0xe2) &&
  75094. (DRMP3_HDR_GET_LAYER(h) != 0) &&
  75095. (DRMP3_HDR_GET_BITRATE(h) != 15) &&
  75096. (DRMP3_HDR_GET_SAMPLE_RATE(h) != 3);
  75097. }
  75098. static int drmp3_hdr_compare(const drmp3_uint8 *h1, const drmp3_uint8 *h2)
  75099. {
  75100. return drmp3_hdr_valid(h2) &&
  75101. ((h1[1] ^ h2[1]) & 0xFE) == 0 &&
  75102. ((h1[2] ^ h2[2]) & 0x0C) == 0 &&
  75103. !(DRMP3_HDR_IS_FREE_FORMAT(h1) ^ DRMP3_HDR_IS_FREE_FORMAT(h2));
  75104. }
  75105. static unsigned drmp3_hdr_bitrate_kbps(const drmp3_uint8 *h)
  75106. {
  75107. static const drmp3_uint8 halfrate[2][3][15] = {
  75108. { { 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 } },
  75109. { { 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 } },
  75110. };
  75111. return 2*halfrate[!!DRMP3_HDR_TEST_MPEG1(h)][DRMP3_HDR_GET_LAYER(h) - 1][DRMP3_HDR_GET_BITRATE(h)];
  75112. }
  75113. static unsigned drmp3_hdr_sample_rate_hz(const drmp3_uint8 *h)
  75114. {
  75115. static const unsigned g_hz[3] = { 44100, 48000, 32000 };
  75116. return g_hz[DRMP3_HDR_GET_SAMPLE_RATE(h)] >> (int)!DRMP3_HDR_TEST_MPEG1(h) >> (int)!DRMP3_HDR_TEST_NOT_MPEG25(h);
  75117. }
  75118. static unsigned drmp3_hdr_frame_samples(const drmp3_uint8 *h)
  75119. {
  75120. return DRMP3_HDR_IS_LAYER_1(h) ? 384 : (1152 >> (int)DRMP3_HDR_IS_FRAME_576(h));
  75121. }
  75122. static int drmp3_hdr_frame_bytes(const drmp3_uint8 *h, int free_format_size)
  75123. {
  75124. int frame_bytes = drmp3_hdr_frame_samples(h)*drmp3_hdr_bitrate_kbps(h)*125/drmp3_hdr_sample_rate_hz(h);
  75125. if (DRMP3_HDR_IS_LAYER_1(h))
  75126. {
  75127. frame_bytes &= ~3;
  75128. }
  75129. return frame_bytes ? frame_bytes : free_format_size;
  75130. }
  75131. static int drmp3_hdr_padding(const drmp3_uint8 *h)
  75132. {
  75133. return DRMP3_HDR_TEST_PADDING(h) ? (DRMP3_HDR_IS_LAYER_1(h) ? 4 : 1) : 0;
  75134. }
  75135. #ifndef DR_MP3_ONLY_MP3
  75136. static const drmp3_L12_subband_alloc *drmp3_L12_subband_alloc_table(const drmp3_uint8 *hdr, drmp3_L12_scale_info *sci)
  75137. {
  75138. const drmp3_L12_subband_alloc *alloc;
  75139. int mode = DRMP3_HDR_GET_STEREO_MODE(hdr);
  75140. int nbands, stereo_bands = (mode == DRMP3_MODE_MONO) ? 0 : (mode == DRMP3_MODE_JOINT_STEREO) ? (DRMP3_HDR_GET_STEREO_MODE_EXT(hdr) << 2) + 4 : 32;
  75141. if (DRMP3_HDR_IS_LAYER_1(hdr))
  75142. {
  75143. static const drmp3_L12_subband_alloc g_alloc_L1[] = { { 76, 4, 32 } };
  75144. alloc = g_alloc_L1;
  75145. nbands = 32;
  75146. } else if (!DRMP3_HDR_TEST_MPEG1(hdr))
  75147. {
  75148. static const drmp3_L12_subband_alloc g_alloc_L2M2[] = { { 60, 4, 4 }, { 44, 3, 7 }, { 44, 2, 19 } };
  75149. alloc = g_alloc_L2M2;
  75150. nbands = 30;
  75151. } else
  75152. {
  75153. static const drmp3_L12_subband_alloc g_alloc_L2M1[] = { { 0, 4, 3 }, { 16, 4, 8 }, { 32, 3, 12 }, { 40, 2, 7 } };
  75154. int sample_rate_idx = DRMP3_HDR_GET_SAMPLE_RATE(hdr);
  75155. unsigned kbps = drmp3_hdr_bitrate_kbps(hdr) >> (int)(mode != DRMP3_MODE_MONO);
  75156. if (!kbps)
  75157. {
  75158. kbps = 192;
  75159. }
  75160. alloc = g_alloc_L2M1;
  75161. nbands = 27;
  75162. if (kbps < 56)
  75163. {
  75164. static const drmp3_L12_subband_alloc g_alloc_L2M1_lowrate[] = { { 44, 4, 2 }, { 44, 3, 10 } };
  75165. alloc = g_alloc_L2M1_lowrate;
  75166. nbands = sample_rate_idx == 2 ? 12 : 8;
  75167. } else if (kbps >= 96 && sample_rate_idx != 1)
  75168. {
  75169. nbands = 30;
  75170. }
  75171. }
  75172. sci->total_bands = (drmp3_uint8)nbands;
  75173. sci->stereo_bands = (drmp3_uint8)DRMP3_MIN(stereo_bands, nbands);
  75174. return alloc;
  75175. }
  75176. static void drmp3_L12_read_scalefactors(drmp3_bs *bs, drmp3_uint8 *pba, drmp3_uint8 *scfcod, int bands, float *scf)
  75177. {
  75178. static const float g_deq_L12[18*3] = {
  75179. #define DRMP3_DQ(x) 9.53674316e-07f/x, 7.56931807e-07f/x, 6.00777173e-07f/x
  75180. DRMP3_DQ(3),DRMP3_DQ(7),DRMP3_DQ(15),DRMP3_DQ(31),DRMP3_DQ(63),DRMP3_DQ(127),DRMP3_DQ(255),DRMP3_DQ(511),DRMP3_DQ(1023),DRMP3_DQ(2047),DRMP3_DQ(4095),DRMP3_DQ(8191),DRMP3_DQ(16383),DRMP3_DQ(32767),DRMP3_DQ(65535),DRMP3_DQ(3),DRMP3_DQ(5),DRMP3_DQ(9)
  75181. };
  75182. int i, m;
  75183. for (i = 0; i < bands; i++)
  75184. {
  75185. float s = 0;
  75186. int ba = *pba++;
  75187. int mask = ba ? 4 + ((19 >> scfcod[i]) & 3) : 0;
  75188. for (m = 4; m; m >>= 1)
  75189. {
  75190. if (mask & m)
  75191. {
  75192. int b = drmp3_bs_get_bits(bs, 6);
  75193. s = g_deq_L12[ba*3 - 6 + b % 3]*(int)(1 << 21 >> b/3);
  75194. }
  75195. *scf++ = s;
  75196. }
  75197. }
  75198. }
  75199. static void drmp3_L12_read_scale_info(const drmp3_uint8 *hdr, drmp3_bs *bs, drmp3_L12_scale_info *sci)
  75200. {
  75201. static const drmp3_uint8 g_bitalloc_code_tab[] = {
  75202. 0,17, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16,
  75203. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,16,
  75204. 0,17,18, 3,19,4,5,16,
  75205. 0,17,18,16,
  75206. 0,17,18,19, 4,5,6, 7,8, 9,10,11,12,13,14,15,
  75207. 0,17,18, 3,19,4,5, 6,7, 8, 9,10,11,12,13,14,
  75208. 0, 2, 3, 4, 5,6,7, 8,9,10,11,12,13,14,15,16
  75209. };
  75210. const drmp3_L12_subband_alloc *subband_alloc = drmp3_L12_subband_alloc_table(hdr, sci);
  75211. int i, k = 0, ba_bits = 0;
  75212. const drmp3_uint8 *ba_code_tab = g_bitalloc_code_tab;
  75213. for (i = 0; i < sci->total_bands; i++)
  75214. {
  75215. drmp3_uint8 ba;
  75216. if (i == k)
  75217. {
  75218. k += subband_alloc->band_count;
  75219. ba_bits = subband_alloc->code_tab_width;
  75220. ba_code_tab = g_bitalloc_code_tab + subband_alloc->tab_offset;
  75221. subband_alloc++;
  75222. }
  75223. ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
  75224. sci->bitalloc[2*i] = ba;
  75225. if (i < sci->stereo_bands)
  75226. {
  75227. ba = ba_code_tab[drmp3_bs_get_bits(bs, ba_bits)];
  75228. }
  75229. sci->bitalloc[2*i + 1] = sci->stereo_bands ? ba : 0;
  75230. }
  75231. for (i = 0; i < 2*sci->total_bands; i++)
  75232. {
  75233. sci->scfcod[i] = (drmp3_uint8)(sci->bitalloc[i] ? DRMP3_HDR_IS_LAYER_1(hdr) ? 2 : drmp3_bs_get_bits(bs, 2) : 6);
  75234. }
  75235. drmp3_L12_read_scalefactors(bs, sci->bitalloc, sci->scfcod, sci->total_bands*2, sci->scf);
  75236. for (i = sci->stereo_bands; i < sci->total_bands; i++)
  75237. {
  75238. sci->bitalloc[2*i + 1] = 0;
  75239. }
  75240. }
  75241. static int drmp3_L12_dequantize_granule(float *grbuf, drmp3_bs *bs, drmp3_L12_scale_info *sci, int group_size)
  75242. {
  75243. int i, j, k, choff = 576;
  75244. for (j = 0; j < 4; j++)
  75245. {
  75246. float *dst = grbuf + group_size*j;
  75247. for (i = 0; i < 2*sci->total_bands; i++)
  75248. {
  75249. int ba = sci->bitalloc[i];
  75250. if (ba != 0)
  75251. {
  75252. if (ba < 17)
  75253. {
  75254. int half = (1 << (ba - 1)) - 1;
  75255. for (k = 0; k < group_size; k++)
  75256. {
  75257. dst[k] = (float)((int)drmp3_bs_get_bits(bs, ba) - half);
  75258. }
  75259. } else
  75260. {
  75261. unsigned mod = (2 << (ba - 17)) + 1;
  75262. unsigned code = drmp3_bs_get_bits(bs, mod + 2 - (mod >> 3));
  75263. for (k = 0; k < group_size; k++, code /= mod)
  75264. {
  75265. dst[k] = (float)((int)(code % mod - mod/2));
  75266. }
  75267. }
  75268. }
  75269. dst += choff;
  75270. choff = 18 - choff;
  75271. }
  75272. }
  75273. return group_size*4;
  75274. }
  75275. static void drmp3_L12_apply_scf_384(drmp3_L12_scale_info *sci, const float *scf, float *dst)
  75276. {
  75277. int i, k;
  75278. DRMP3_COPY_MEMORY(dst + 576 + sci->stereo_bands*18, dst + sci->stereo_bands*18, (sci->total_bands - sci->stereo_bands)*18*sizeof(float));
  75279. for (i = 0; i < sci->total_bands; i++, dst += 18, scf += 6)
  75280. {
  75281. for (k = 0; k < 12; k++)
  75282. {
  75283. dst[k + 0] *= scf[0];
  75284. dst[k + 576] *= scf[3];
  75285. }
  75286. }
  75287. }
  75288. #endif
  75289. static int drmp3_L3_read_side_info(drmp3_bs *bs, drmp3_L3_gr_info *gr, const drmp3_uint8 *hdr)
  75290. {
  75291. static const drmp3_uint8 g_scf_long[8][23] = {
  75292. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  75293. { 12,12,12,12,12,12,16,20,24,28,32,40,48,56,64,76,90,2,2,2,2,2,0 },
  75294. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  75295. { 6,6,6,6,6,6,8,10,12,14,16,18,22,26,32,38,46,54,62,70,76,36,0 },
  75296. { 6,6,6,6,6,6,8,10,12,14,16,20,24,28,32,38,46,52,60,68,58,54,0 },
  75297. { 4,4,4,4,4,4,6,6,8,8,10,12,16,20,24,28,34,42,50,54,76,158,0 },
  75298. { 4,4,4,4,4,4,6,6,6,8,10,12,16,18,22,28,34,40,46,54,54,192,0 },
  75299. { 4,4,4,4,4,4,6,6,8,10,12,16,20,24,30,38,46,56,68,84,102,26,0 }
  75300. };
  75301. static const drmp3_uint8 g_scf_short[8][40] = {
  75302. { 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 },
  75303. { 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 },
  75304. { 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 },
  75305. { 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 },
  75306. { 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 },
  75307. { 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 },
  75308. { 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 },
  75309. { 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 }
  75310. };
  75311. static const drmp3_uint8 g_scf_mixed[8][40] = {
  75312. { 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 },
  75313. { 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 },
  75314. { 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 },
  75315. { 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 },
  75316. { 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 },
  75317. { 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 },
  75318. { 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 },
  75319. { 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 }
  75320. };
  75321. unsigned tables, scfsi = 0;
  75322. int main_data_begin, part_23_sum = 0;
  75323. int gr_count = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2;
  75324. int sr_idx = DRMP3_HDR_GET_MY_SAMPLE_RATE(hdr); sr_idx -= (sr_idx != 0);
  75325. if (DRMP3_HDR_TEST_MPEG1(hdr))
  75326. {
  75327. gr_count *= 2;
  75328. main_data_begin = drmp3_bs_get_bits(bs, 9);
  75329. scfsi = drmp3_bs_get_bits(bs, 7 + gr_count);
  75330. } else
  75331. {
  75332. main_data_begin = drmp3_bs_get_bits(bs, 8 + gr_count) >> gr_count;
  75333. }
  75334. do
  75335. {
  75336. if (DRMP3_HDR_IS_MONO(hdr))
  75337. {
  75338. scfsi <<= 4;
  75339. }
  75340. gr->part_23_length = (drmp3_uint16)drmp3_bs_get_bits(bs, 12);
  75341. part_23_sum += gr->part_23_length;
  75342. gr->big_values = (drmp3_uint16)drmp3_bs_get_bits(bs, 9);
  75343. if (gr->big_values > 288)
  75344. {
  75345. return -1;
  75346. }
  75347. gr->global_gain = (drmp3_uint8)drmp3_bs_get_bits(bs, 8);
  75348. gr->scalefac_compress = (drmp3_uint16)drmp3_bs_get_bits(bs, DRMP3_HDR_TEST_MPEG1(hdr) ? 4 : 9);
  75349. gr->sfbtab = g_scf_long[sr_idx];
  75350. gr->n_long_sfb = 22;
  75351. gr->n_short_sfb = 0;
  75352. if (drmp3_bs_get_bits(bs, 1))
  75353. {
  75354. gr->block_type = (drmp3_uint8)drmp3_bs_get_bits(bs, 2);
  75355. if (!gr->block_type)
  75356. {
  75357. return -1;
  75358. }
  75359. gr->mixed_block_flag = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  75360. gr->region_count[0] = 7;
  75361. gr->region_count[1] = 255;
  75362. if (gr->block_type == DRMP3_SHORT_BLOCK_TYPE)
  75363. {
  75364. scfsi &= 0x0F0F;
  75365. if (!gr->mixed_block_flag)
  75366. {
  75367. gr->region_count[0] = 8;
  75368. gr->sfbtab = g_scf_short[sr_idx];
  75369. gr->n_long_sfb = 0;
  75370. gr->n_short_sfb = 39;
  75371. } else
  75372. {
  75373. gr->sfbtab = g_scf_mixed[sr_idx];
  75374. gr->n_long_sfb = DRMP3_HDR_TEST_MPEG1(hdr) ? 8 : 6;
  75375. gr->n_short_sfb = 30;
  75376. }
  75377. }
  75378. tables = drmp3_bs_get_bits(bs, 10);
  75379. tables <<= 5;
  75380. gr->subblock_gain[0] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  75381. gr->subblock_gain[1] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  75382. gr->subblock_gain[2] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  75383. } else
  75384. {
  75385. gr->block_type = 0;
  75386. gr->mixed_block_flag = 0;
  75387. tables = drmp3_bs_get_bits(bs, 15);
  75388. gr->region_count[0] = (drmp3_uint8)drmp3_bs_get_bits(bs, 4);
  75389. gr->region_count[1] = (drmp3_uint8)drmp3_bs_get_bits(bs, 3);
  75390. gr->region_count[2] = 255;
  75391. }
  75392. gr->table_select[0] = (drmp3_uint8)(tables >> 10);
  75393. gr->table_select[1] = (drmp3_uint8)((tables >> 5) & 31);
  75394. gr->table_select[2] = (drmp3_uint8)((tables) & 31);
  75395. gr->preflag = (drmp3_uint8)(DRMP3_HDR_TEST_MPEG1(hdr) ? drmp3_bs_get_bits(bs, 1) : (gr->scalefac_compress >= 500));
  75396. gr->scalefac_scale = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  75397. gr->count1_table = (drmp3_uint8)drmp3_bs_get_bits(bs, 1);
  75398. gr->scfsi = (drmp3_uint8)((scfsi >> 12) & 15);
  75399. scfsi <<= 4;
  75400. gr++;
  75401. } while(--gr_count);
  75402. if (part_23_sum + bs->pos > bs->limit + main_data_begin*8)
  75403. {
  75404. return -1;
  75405. }
  75406. return main_data_begin;
  75407. }
  75408. static void drmp3_L3_read_scalefactors(drmp3_uint8 *scf, drmp3_uint8 *ist_pos, const drmp3_uint8 *scf_size, const drmp3_uint8 *scf_count, drmp3_bs *bitbuf, int scfsi)
  75409. {
  75410. int i, k;
  75411. for (i = 0; i < 4 && scf_count[i]; i++, scfsi *= 2)
  75412. {
  75413. int cnt = scf_count[i];
  75414. if (scfsi & 8)
  75415. {
  75416. DRMP3_COPY_MEMORY(scf, ist_pos, cnt);
  75417. } else
  75418. {
  75419. int bits = scf_size[i];
  75420. if (!bits)
  75421. {
  75422. DRMP3_ZERO_MEMORY(scf, cnt);
  75423. DRMP3_ZERO_MEMORY(ist_pos, cnt);
  75424. } else
  75425. {
  75426. int max_scf = (scfsi < 0) ? (1 << bits) - 1 : -1;
  75427. for (k = 0; k < cnt; k++)
  75428. {
  75429. int s = drmp3_bs_get_bits(bitbuf, bits);
  75430. ist_pos[k] = (drmp3_uint8)(s == max_scf ? -1 : s);
  75431. scf[k] = (drmp3_uint8)s;
  75432. }
  75433. }
  75434. }
  75435. ist_pos += cnt;
  75436. scf += cnt;
  75437. }
  75438. scf[0] = scf[1] = scf[2] = 0;
  75439. }
  75440. static float drmp3_L3_ldexp_q2(float y, int exp_q2)
  75441. {
  75442. static const float g_expfrac[4] = { 9.31322575e-10f,7.83145814e-10f,6.58544508e-10f,5.53767716e-10f };
  75443. int e;
  75444. do
  75445. {
  75446. e = DRMP3_MIN(30*4, exp_q2);
  75447. y *= g_expfrac[e & 3]*(1 << 30 >> (e >> 2));
  75448. } while ((exp_q2 -= e) > 0);
  75449. return y;
  75450. }
  75451. static void drmp3_L3_decode_scalefactors(const drmp3_uint8 *hdr, drmp3_uint8 *ist_pos, drmp3_bs *bs, const drmp3_L3_gr_info *gr, float *scf, int ch)
  75452. {
  75453. static const drmp3_uint8 g_scf_partitions[3][28] = {
  75454. { 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 },
  75455. { 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 },
  75456. { 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 }
  75457. };
  75458. const drmp3_uint8 *scf_partition = g_scf_partitions[!!gr->n_short_sfb + !gr->n_long_sfb];
  75459. drmp3_uint8 scf_size[4], iscf[40];
  75460. int i, scf_shift = gr->scalefac_scale + 1, gain_exp, scfsi = gr->scfsi;
  75461. float gain;
  75462. if (DRMP3_HDR_TEST_MPEG1(hdr))
  75463. {
  75464. static const drmp3_uint8 g_scfc_decode[16] = { 0,1,2,3, 12,5,6,7, 9,10,11,13, 14,15,18,19 };
  75465. int part = g_scfc_decode[gr->scalefac_compress];
  75466. scf_size[1] = scf_size[0] = (drmp3_uint8)(part >> 2);
  75467. scf_size[3] = scf_size[2] = (drmp3_uint8)(part & 3);
  75468. } else
  75469. {
  75470. static const drmp3_uint8 g_mod[6*4] = { 5,5,4,4,5,5,4,1,4,3,1,1,5,6,6,1,4,4,4,1,4,3,1,1 };
  75471. int k, modprod, sfc, ist = DRMP3_HDR_TEST_I_STEREO(hdr) && ch;
  75472. sfc = gr->scalefac_compress >> ist;
  75473. for (k = ist*3*4; sfc >= 0; sfc -= modprod, k += 4)
  75474. {
  75475. for (modprod = 1, i = 3; i >= 0; i--)
  75476. {
  75477. scf_size[i] = (drmp3_uint8)(sfc / modprod % g_mod[k + i]);
  75478. modprod *= g_mod[k + i];
  75479. }
  75480. }
  75481. scf_partition += k;
  75482. scfsi = -16;
  75483. }
  75484. drmp3_L3_read_scalefactors(iscf, ist_pos, scf_size, scf_partition, bs, scfsi);
  75485. if (gr->n_short_sfb)
  75486. {
  75487. int sh = 3 - scf_shift;
  75488. for (i = 0; i < gr->n_short_sfb; i += 3)
  75489. {
  75490. iscf[gr->n_long_sfb + i + 0] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 0] + (gr->subblock_gain[0] << sh));
  75491. iscf[gr->n_long_sfb + i + 1] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 1] + (gr->subblock_gain[1] << sh));
  75492. iscf[gr->n_long_sfb + i + 2] = (drmp3_uint8)(iscf[gr->n_long_sfb + i + 2] + (gr->subblock_gain[2] << sh));
  75493. }
  75494. } else if (gr->preflag)
  75495. {
  75496. static const drmp3_uint8 g_preamp[10] = { 1,1,1,1,2,2,3,3,3,2 };
  75497. for (i = 0; i < 10; i++)
  75498. {
  75499. iscf[11 + i] = (drmp3_uint8)(iscf[11 + i] + g_preamp[i]);
  75500. }
  75501. }
  75502. gain_exp = gr->global_gain + DRMP3_BITS_DEQUANTIZER_OUT*4 - 210 - (DRMP3_HDR_IS_MS_STEREO(hdr) ? 2 : 0);
  75503. gain = drmp3_L3_ldexp_q2(1 << (DRMP3_MAX_SCFI/4), DRMP3_MAX_SCFI - gain_exp);
  75504. for (i = 0; i < (int)(gr->n_long_sfb + gr->n_short_sfb); i++)
  75505. {
  75506. scf[i] = drmp3_L3_ldexp_q2(gain, iscf[i] << scf_shift);
  75507. }
  75508. }
  75509. static const float g_drmp3_pow43[129 + 16] = {
  75510. 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,
  75511. 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
  75512. };
  75513. static float drmp3_L3_pow_43(int x)
  75514. {
  75515. float frac;
  75516. int sign, mult = 256;
  75517. if (x < 129)
  75518. {
  75519. return g_drmp3_pow43[16 + x];
  75520. }
  75521. if (x < 1024)
  75522. {
  75523. mult = 16;
  75524. x <<= 3;
  75525. }
  75526. sign = 2*x & 64;
  75527. frac = (float)((x & 63) - sign) / ((x & ~63) + sign);
  75528. return g_drmp3_pow43[16 + ((x + sign) >> 6)]*(1.f + frac*((4.f/3) + frac*(2.f/9)))*mult;
  75529. }
  75530. static void drmp3_L3_huffman(float *dst, drmp3_bs *bs, const drmp3_L3_gr_info *gr_info, const float *scf, int layer3gr_limit)
  75531. {
  75532. static const drmp3_int16 tabs[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  75533. 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,
  75534. -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,
  75535. -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,
  75536. -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,
  75537. -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,
  75538. -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,
  75539. -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,
  75540. -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,
  75541. -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,
  75542. -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,
  75543. -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,
  75544. -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,
  75545. -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,
  75546. -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,
  75547. -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 };
  75548. static const drmp3_uint8 tab32[] = { 130,162,193,209,44,28,76,140,9,9,9,9,9,9,9,9,190,254,222,238,126,94,157,157,109,61,173,205};
  75549. static const drmp3_uint8 tab33[] = { 252,236,220,204,188,172,156,140,124,108,92,76,60,44,28,12 };
  75550. static const drmp3_int16 tabindex[2*16] = { 0,32,64,98,0,132,180,218,292,364,426,538,648,746,0,1126,1460,1460,1460,1460,1460,1460,1460,1460,1842,1842,1842,1842,1842,1842,1842,1842 };
  75551. static const drmp3_uint8 g_linbits[] = { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,6,8,10,13,4,5,6,7,8,9,11,13 };
  75552. #define DRMP3_PEEK_BITS(n) (bs_cache >> (32 - (n)))
  75553. #define DRMP3_FLUSH_BITS(n) { bs_cache <<= (n); bs_sh += (n); }
  75554. #define DRMP3_CHECK_BITS while (bs_sh >= 0) { bs_cache |= (drmp3_uint32)*bs_next_ptr++ << bs_sh; bs_sh -= 8; }
  75555. #define DRMP3_BSPOS ((bs_next_ptr - bs->buf)*8 - 24 + bs_sh)
  75556. float one = 0.0f;
  75557. int ireg = 0, big_val_cnt = gr_info->big_values;
  75558. const drmp3_uint8 *sfb = gr_info->sfbtab;
  75559. const drmp3_uint8 *bs_next_ptr = bs->buf + bs->pos/8;
  75560. drmp3_uint32 bs_cache = (((bs_next_ptr[0]*256u + bs_next_ptr[1])*256u + bs_next_ptr[2])*256u + bs_next_ptr[3]) << (bs->pos & 7);
  75561. int pairs_to_decode, np, bs_sh = (bs->pos & 7) - 8;
  75562. bs_next_ptr += 4;
  75563. while (big_val_cnt > 0)
  75564. {
  75565. int tab_num = gr_info->table_select[ireg];
  75566. int sfb_cnt = gr_info->region_count[ireg++];
  75567. const drmp3_int16 *codebook = tabs + tabindex[tab_num];
  75568. int linbits = g_linbits[tab_num];
  75569. if (linbits)
  75570. {
  75571. do
  75572. {
  75573. np = *sfb++ / 2;
  75574. pairs_to_decode = DRMP3_MIN(big_val_cnt, np);
  75575. one = *scf++;
  75576. do
  75577. {
  75578. int j, w = 5;
  75579. int leaf = codebook[DRMP3_PEEK_BITS(w)];
  75580. while (leaf < 0)
  75581. {
  75582. DRMP3_FLUSH_BITS(w);
  75583. w = leaf & 7;
  75584. leaf = codebook[DRMP3_PEEK_BITS(w) - (leaf >> 3)];
  75585. }
  75586. DRMP3_FLUSH_BITS(leaf >> 8);
  75587. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  75588. {
  75589. int lsb = leaf & 0x0F;
  75590. if (lsb == 15)
  75591. {
  75592. lsb += DRMP3_PEEK_BITS(linbits);
  75593. DRMP3_FLUSH_BITS(linbits);
  75594. DRMP3_CHECK_BITS;
  75595. *dst = one*drmp3_L3_pow_43(lsb)*((drmp3_int32)bs_cache < 0 ? -1: 1);
  75596. } else
  75597. {
  75598. *dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  75599. }
  75600. DRMP3_FLUSH_BITS(lsb ? 1 : 0);
  75601. }
  75602. DRMP3_CHECK_BITS;
  75603. } while (--pairs_to_decode);
  75604. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  75605. } else
  75606. {
  75607. do
  75608. {
  75609. np = *sfb++ / 2;
  75610. pairs_to_decode = DRMP3_MIN(big_val_cnt, np);
  75611. one = *scf++;
  75612. do
  75613. {
  75614. int j, w = 5;
  75615. int leaf = codebook[DRMP3_PEEK_BITS(w)];
  75616. while (leaf < 0)
  75617. {
  75618. DRMP3_FLUSH_BITS(w);
  75619. w = leaf & 7;
  75620. leaf = codebook[DRMP3_PEEK_BITS(w) - (leaf >> 3)];
  75621. }
  75622. DRMP3_FLUSH_BITS(leaf >> 8);
  75623. for (j = 0; j < 2; j++, dst++, leaf >>= 4)
  75624. {
  75625. int lsb = leaf & 0x0F;
  75626. *dst = g_drmp3_pow43[16 + lsb - 16*(bs_cache >> 31)]*one;
  75627. DRMP3_FLUSH_BITS(lsb ? 1 : 0);
  75628. }
  75629. DRMP3_CHECK_BITS;
  75630. } while (--pairs_to_decode);
  75631. } while ((big_val_cnt -= np) > 0 && --sfb_cnt >= 0);
  75632. }
  75633. }
  75634. for (np = 1 - big_val_cnt;; dst += 4)
  75635. {
  75636. const drmp3_uint8 *codebook_count1 = (gr_info->count1_table) ? tab33 : tab32;
  75637. int leaf = codebook_count1[DRMP3_PEEK_BITS(4)];
  75638. if (!(leaf & 8))
  75639. {
  75640. leaf = codebook_count1[(leaf >> 3) + (bs_cache << 4 >> (32 - (leaf & 3)))];
  75641. }
  75642. DRMP3_FLUSH_BITS(leaf & 7);
  75643. if (DRMP3_BSPOS > layer3gr_limit)
  75644. {
  75645. break;
  75646. }
  75647. #define DRMP3_RELOAD_SCALEFACTOR if (!--np) { np = *sfb++/2; if (!np) break; one = *scf++; }
  75648. #define DRMP3_DEQ_COUNT1(s) if (leaf & (128 >> s)) { dst[s] = ((drmp3_int32)bs_cache < 0) ? -one : one; DRMP3_FLUSH_BITS(1) }
  75649. DRMP3_RELOAD_SCALEFACTOR;
  75650. DRMP3_DEQ_COUNT1(0);
  75651. DRMP3_DEQ_COUNT1(1);
  75652. DRMP3_RELOAD_SCALEFACTOR;
  75653. DRMP3_DEQ_COUNT1(2);
  75654. DRMP3_DEQ_COUNT1(3);
  75655. DRMP3_CHECK_BITS;
  75656. }
  75657. bs->pos = layer3gr_limit;
  75658. }
  75659. static void drmp3_L3_midside_stereo(float *left, int n)
  75660. {
  75661. int i = 0;
  75662. float *right = left + 576;
  75663. #if DRMP3_HAVE_SIMD
  75664. if (drmp3_have_simd())
  75665. {
  75666. for (; i < n - 3; i += 4)
  75667. {
  75668. drmp3_f4 vl = DRMP3_VLD(left + i);
  75669. drmp3_f4 vr = DRMP3_VLD(right + i);
  75670. DRMP3_VSTORE(left + i, DRMP3_VADD(vl, vr));
  75671. DRMP3_VSTORE(right + i, DRMP3_VSUB(vl, vr));
  75672. }
  75673. #ifdef __GNUC__
  75674. if (__builtin_constant_p(n % 4 == 0) && n % 4 == 0)
  75675. return;
  75676. #endif
  75677. }
  75678. #endif
  75679. for (; i < n; i++)
  75680. {
  75681. float a = left[i];
  75682. float b = right[i];
  75683. left[i] = a + b;
  75684. right[i] = a - b;
  75685. }
  75686. }
  75687. static void drmp3_L3_intensity_stereo_band(float *left, int n, float kl, float kr)
  75688. {
  75689. int i;
  75690. for (i = 0; i < n; i++)
  75691. {
  75692. left[i + 576] = left[i]*kr;
  75693. left[i] = left[i]*kl;
  75694. }
  75695. }
  75696. static void drmp3_L3_stereo_top_band(const float *right, const drmp3_uint8 *sfb, int nbands, int max_band[3])
  75697. {
  75698. int i, k;
  75699. max_band[0] = max_band[1] = max_band[2] = -1;
  75700. for (i = 0; i < nbands; i++)
  75701. {
  75702. for (k = 0; k < sfb[i]; k += 2)
  75703. {
  75704. if (right[k] != 0 || right[k + 1] != 0)
  75705. {
  75706. max_band[i % 3] = i;
  75707. break;
  75708. }
  75709. }
  75710. right += sfb[i];
  75711. }
  75712. }
  75713. static void drmp3_L3_stereo_process(float *left, const drmp3_uint8 *ist_pos, const drmp3_uint8 *sfb, const drmp3_uint8 *hdr, int max_band[3], int mpeg2_sh)
  75714. {
  75715. 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 };
  75716. unsigned i, max_pos = DRMP3_HDR_TEST_MPEG1(hdr) ? 7 : 64;
  75717. for (i = 0; sfb[i]; i++)
  75718. {
  75719. unsigned ipos = ist_pos[i];
  75720. if ((int)i > max_band[i % 3] && ipos < max_pos)
  75721. {
  75722. float kl, kr, s = DRMP3_HDR_TEST_MS_STEREO(hdr) ? 1.41421356f : 1;
  75723. if (DRMP3_HDR_TEST_MPEG1(hdr))
  75724. {
  75725. kl = g_pan[2*ipos];
  75726. kr = g_pan[2*ipos + 1];
  75727. } else
  75728. {
  75729. kl = 1;
  75730. kr = drmp3_L3_ldexp_q2(1, (ipos + 1) >> 1 << mpeg2_sh);
  75731. if (ipos & 1)
  75732. {
  75733. kl = kr;
  75734. kr = 1;
  75735. }
  75736. }
  75737. drmp3_L3_intensity_stereo_band(left, sfb[i], kl*s, kr*s);
  75738. } else if (DRMP3_HDR_TEST_MS_STEREO(hdr))
  75739. {
  75740. drmp3_L3_midside_stereo(left, sfb[i]);
  75741. }
  75742. left += sfb[i];
  75743. }
  75744. }
  75745. static void drmp3_L3_intensity_stereo(float *left, drmp3_uint8 *ist_pos, const drmp3_L3_gr_info *gr, const drmp3_uint8 *hdr)
  75746. {
  75747. int max_band[3], n_sfb = gr->n_long_sfb + gr->n_short_sfb;
  75748. int i, max_blocks = gr->n_short_sfb ? 3 : 1;
  75749. drmp3_L3_stereo_top_band(left + 576, gr->sfbtab, n_sfb, max_band);
  75750. if (gr->n_long_sfb)
  75751. {
  75752. max_band[0] = max_band[1] = max_band[2] = DRMP3_MAX(DRMP3_MAX(max_band[0], max_band[1]), max_band[2]);
  75753. }
  75754. for (i = 0; i < max_blocks; i++)
  75755. {
  75756. int default_pos = DRMP3_HDR_TEST_MPEG1(hdr) ? 3 : 0;
  75757. int itop = n_sfb - max_blocks + i;
  75758. int prev = itop - max_blocks;
  75759. ist_pos[itop] = (drmp3_uint8)(max_band[i] >= prev ? default_pos : ist_pos[prev]);
  75760. }
  75761. drmp3_L3_stereo_process(left, ist_pos, gr->sfbtab, hdr, max_band, gr[1].scalefac_compress & 1);
  75762. }
  75763. static void drmp3_L3_reorder(float *grbuf, float *scratch, const drmp3_uint8 *sfb)
  75764. {
  75765. int i, len;
  75766. float *src = grbuf, *dst = scratch;
  75767. for (;0 != (len = *sfb); sfb += 3, src += 2*len)
  75768. {
  75769. for (i = 0; i < len; i++, src++)
  75770. {
  75771. *dst++ = src[0*len];
  75772. *dst++ = src[1*len];
  75773. *dst++ = src[2*len];
  75774. }
  75775. }
  75776. DRMP3_COPY_MEMORY(grbuf, scratch, (dst - scratch)*sizeof(float));
  75777. }
  75778. static void drmp3_L3_antialias(float *grbuf, int nbands)
  75779. {
  75780. static const float g_aa[2][8] = {
  75781. {0.85749293f,0.88174200f,0.94962865f,0.98331459f,0.99551782f,0.99916056f,0.99989920f,0.99999316f},
  75782. {0.51449576f,0.47173197f,0.31337745f,0.18191320f,0.09457419f,0.04096558f,0.01419856f,0.00369997f}
  75783. };
  75784. for (; nbands > 0; nbands--, grbuf += 18)
  75785. {
  75786. int i = 0;
  75787. #if DRMP3_HAVE_SIMD
  75788. if (drmp3_have_simd()) for (; i < 8; i += 4)
  75789. {
  75790. drmp3_f4 vu = DRMP3_VLD(grbuf + 18 + i);
  75791. drmp3_f4 vd = DRMP3_VLD(grbuf + 14 - i);
  75792. drmp3_f4 vc0 = DRMP3_VLD(g_aa[0] + i);
  75793. drmp3_f4 vc1 = DRMP3_VLD(g_aa[1] + i);
  75794. vd = DRMP3_VREV(vd);
  75795. DRMP3_VSTORE(grbuf + 18 + i, DRMP3_VSUB(DRMP3_VMUL(vu, vc0), DRMP3_VMUL(vd, vc1)));
  75796. vd = DRMP3_VADD(DRMP3_VMUL(vu, vc1), DRMP3_VMUL(vd, vc0));
  75797. DRMP3_VSTORE(grbuf + 14 - i, DRMP3_VREV(vd));
  75798. }
  75799. #endif
  75800. #ifndef DR_MP3_ONLY_SIMD
  75801. for(; i < 8; i++)
  75802. {
  75803. float u = grbuf[18 + i];
  75804. float d = grbuf[17 - i];
  75805. grbuf[18 + i] = u*g_aa[0][i] - d*g_aa[1][i];
  75806. grbuf[17 - i] = u*g_aa[1][i] + d*g_aa[0][i];
  75807. }
  75808. #endif
  75809. }
  75810. }
  75811. static void drmp3_L3_dct3_9(float *y)
  75812. {
  75813. float s0, s1, s2, s3, s4, s5, s6, s7, s8, t0, t2, t4;
  75814. s0 = y[0]; s2 = y[2]; s4 = y[4]; s6 = y[6]; s8 = y[8];
  75815. t0 = s0 + s6*0.5f;
  75816. s0 -= s6;
  75817. t4 = (s4 + s2)*0.93969262f;
  75818. t2 = (s8 + s2)*0.76604444f;
  75819. s6 = (s4 - s8)*0.17364818f;
  75820. s4 += s8 - s2;
  75821. s2 = s0 - s4*0.5f;
  75822. y[4] = s4 + s0;
  75823. s8 = t0 - t2 + s6;
  75824. s0 = t0 - t4 + t2;
  75825. s4 = t0 + t4 - s6;
  75826. s1 = y[1]; s3 = y[3]; s5 = y[5]; s7 = y[7];
  75827. s3 *= 0.86602540f;
  75828. t0 = (s5 + s1)*0.98480775f;
  75829. t4 = (s5 - s7)*0.34202014f;
  75830. t2 = (s1 + s7)*0.64278761f;
  75831. s1 = (s1 - s5 - s7)*0.86602540f;
  75832. s5 = t0 - s3 - t2;
  75833. s7 = t4 - s3 - t0;
  75834. s3 = t4 + s3 - t2;
  75835. y[0] = s4 - s7;
  75836. y[1] = s2 + s1;
  75837. y[2] = s0 - s3;
  75838. y[3] = s8 + s5;
  75839. y[5] = s8 - s5;
  75840. y[6] = s0 + s3;
  75841. y[7] = s2 - s1;
  75842. y[8] = s4 + s7;
  75843. }
  75844. static void drmp3_L3_imdct36(float *grbuf, float *overlap, const float *window, int nbands)
  75845. {
  75846. int i, j;
  75847. static const float g_twid9[18] = {
  75848. 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
  75849. };
  75850. for (j = 0; j < nbands; j++, grbuf += 18, overlap += 9)
  75851. {
  75852. float co[9], si[9];
  75853. co[0] = -grbuf[0];
  75854. si[0] = grbuf[17];
  75855. for (i = 0; i < 4; i++)
  75856. {
  75857. si[8 - 2*i] = grbuf[4*i + 1] - grbuf[4*i + 2];
  75858. co[1 + 2*i] = grbuf[4*i + 1] + grbuf[4*i + 2];
  75859. si[7 - 2*i] = grbuf[4*i + 4] - grbuf[4*i + 3];
  75860. co[2 + 2*i] = -(grbuf[4*i + 3] + grbuf[4*i + 4]);
  75861. }
  75862. drmp3_L3_dct3_9(co);
  75863. drmp3_L3_dct3_9(si);
  75864. si[1] = -si[1];
  75865. si[3] = -si[3];
  75866. si[5] = -si[5];
  75867. si[7] = -si[7];
  75868. i = 0;
  75869. #if DRMP3_HAVE_SIMD
  75870. if (drmp3_have_simd()) for (; i < 8; i += 4)
  75871. {
  75872. drmp3_f4 vovl = DRMP3_VLD(overlap + i);
  75873. drmp3_f4 vc = DRMP3_VLD(co + i);
  75874. drmp3_f4 vs = DRMP3_VLD(si + i);
  75875. drmp3_f4 vr0 = DRMP3_VLD(g_twid9 + i);
  75876. drmp3_f4 vr1 = DRMP3_VLD(g_twid9 + 9 + i);
  75877. drmp3_f4 vw0 = DRMP3_VLD(window + i);
  75878. drmp3_f4 vw1 = DRMP3_VLD(window + 9 + i);
  75879. drmp3_f4 vsum = DRMP3_VADD(DRMP3_VMUL(vc, vr1), DRMP3_VMUL(vs, vr0));
  75880. DRMP3_VSTORE(overlap + i, DRMP3_VSUB(DRMP3_VMUL(vc, vr0), DRMP3_VMUL(vs, vr1)));
  75881. DRMP3_VSTORE(grbuf + i, DRMP3_VSUB(DRMP3_VMUL(vovl, vw0), DRMP3_VMUL(vsum, vw1)));
  75882. vsum = DRMP3_VADD(DRMP3_VMUL(vovl, vw1), DRMP3_VMUL(vsum, vw0));
  75883. DRMP3_VSTORE(grbuf + 14 - i, DRMP3_VREV(vsum));
  75884. }
  75885. #endif
  75886. for (; i < 9; i++)
  75887. {
  75888. float ovl = overlap[i];
  75889. float sum = co[i]*g_twid9[9 + i] + si[i]*g_twid9[0 + i];
  75890. overlap[i] = co[i]*g_twid9[0 + i] - si[i]*g_twid9[9 + i];
  75891. grbuf[i] = ovl*window[0 + i] - sum*window[9 + i];
  75892. grbuf[17 - i] = ovl*window[9 + i] + sum*window[0 + i];
  75893. }
  75894. }
  75895. }
  75896. static void drmp3_L3_idct3(float x0, float x1, float x2, float *dst)
  75897. {
  75898. float m1 = x1*0.86602540f;
  75899. float a1 = x0 - x2*0.5f;
  75900. dst[1] = x0 + x2;
  75901. dst[0] = a1 + m1;
  75902. dst[2] = a1 - m1;
  75903. }
  75904. static void drmp3_L3_imdct12(float *x, float *dst, float *overlap)
  75905. {
  75906. static const float g_twid3[6] = { 0.79335334f,0.92387953f,0.99144486f, 0.60876143f,0.38268343f,0.13052619f };
  75907. float co[3], si[3];
  75908. int i;
  75909. drmp3_L3_idct3(-x[0], x[6] + x[3], x[12] + x[9], co);
  75910. drmp3_L3_idct3(x[15], x[12] - x[9], x[6] - x[3], si);
  75911. si[1] = -si[1];
  75912. for (i = 0; i < 3; i++)
  75913. {
  75914. float ovl = overlap[i];
  75915. float sum = co[i]*g_twid3[3 + i] + si[i]*g_twid3[0 + i];
  75916. overlap[i] = co[i]*g_twid3[0 + i] - si[i]*g_twid3[3 + i];
  75917. dst[i] = ovl*g_twid3[2 - i] - sum*g_twid3[5 - i];
  75918. dst[5 - i] = ovl*g_twid3[5 - i] + sum*g_twid3[2 - i];
  75919. }
  75920. }
  75921. static void drmp3_L3_imdct_short(float *grbuf, float *overlap, int nbands)
  75922. {
  75923. for (;nbands > 0; nbands--, overlap += 9, grbuf += 18)
  75924. {
  75925. float tmp[18];
  75926. DRMP3_COPY_MEMORY(tmp, grbuf, sizeof(tmp));
  75927. DRMP3_COPY_MEMORY(grbuf, overlap, 6*sizeof(float));
  75928. drmp3_L3_imdct12(tmp, grbuf + 6, overlap + 6);
  75929. drmp3_L3_imdct12(tmp + 1, grbuf + 12, overlap + 6);
  75930. drmp3_L3_imdct12(tmp + 2, overlap, overlap + 6);
  75931. }
  75932. }
  75933. static void drmp3_L3_change_sign(float *grbuf)
  75934. {
  75935. int b, i;
  75936. for (b = 0, grbuf += 18; b < 32; b += 2, grbuf += 36)
  75937. for (i = 1; i < 18; i += 2)
  75938. grbuf[i] = -grbuf[i];
  75939. }
  75940. static void drmp3_L3_imdct_gr(float *grbuf, float *overlap, unsigned block_type, unsigned n_long_bands)
  75941. {
  75942. static const float g_mdct_window[2][18] = {
  75943. { 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 },
  75944. { 1,1,1,1,1,1,0.99144486f,0.92387953f,0.79335334f,0,0,0,0,0,0,0.13052619f,0.38268343f,0.60876143f }
  75945. };
  75946. if (n_long_bands)
  75947. {
  75948. drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[0], n_long_bands);
  75949. grbuf += 18*n_long_bands;
  75950. overlap += 9*n_long_bands;
  75951. }
  75952. if (block_type == DRMP3_SHORT_BLOCK_TYPE)
  75953. drmp3_L3_imdct_short(grbuf, overlap, 32 - n_long_bands);
  75954. else
  75955. drmp3_L3_imdct36(grbuf, overlap, g_mdct_window[block_type == DRMP3_STOP_BLOCK_TYPE], 32 - n_long_bands);
  75956. }
  75957. static void drmp3_L3_save_reservoir(drmp3dec *h, drmp3dec_scratch *s)
  75958. {
  75959. int pos = (s->bs.pos + 7)/8u;
  75960. int remains = s->bs.limit/8u - pos;
  75961. if (remains > DRMP3_MAX_BITRESERVOIR_BYTES)
  75962. {
  75963. pos += remains - DRMP3_MAX_BITRESERVOIR_BYTES;
  75964. remains = DRMP3_MAX_BITRESERVOIR_BYTES;
  75965. }
  75966. if (remains > 0)
  75967. {
  75968. DRMP3_MOVE_MEMORY(h->reserv_buf, s->maindata + pos, remains);
  75969. }
  75970. h->reserv = remains;
  75971. }
  75972. static int drmp3_L3_restore_reservoir(drmp3dec *h, drmp3_bs *bs, drmp3dec_scratch *s, int main_data_begin)
  75973. {
  75974. int frame_bytes = (bs->limit - bs->pos)/8;
  75975. int bytes_have = DRMP3_MIN(h->reserv, main_data_begin);
  75976. DRMP3_COPY_MEMORY(s->maindata, h->reserv_buf + DRMP3_MAX(0, h->reserv - main_data_begin), DRMP3_MIN(h->reserv, main_data_begin));
  75977. DRMP3_COPY_MEMORY(s->maindata + bytes_have, bs->buf + bs->pos/8, frame_bytes);
  75978. drmp3_bs_init(&s->bs, s->maindata, bytes_have + frame_bytes);
  75979. return h->reserv >= main_data_begin;
  75980. }
  75981. static void drmp3_L3_decode(drmp3dec *h, drmp3dec_scratch *s, drmp3_L3_gr_info *gr_info, int nch)
  75982. {
  75983. int ch;
  75984. for (ch = 0; ch < nch; ch++)
  75985. {
  75986. int layer3gr_limit = s->bs.pos + gr_info[ch].part_23_length;
  75987. drmp3_L3_decode_scalefactors(h->header, s->ist_pos[ch], &s->bs, gr_info + ch, s->scf, ch);
  75988. drmp3_L3_huffman(s->grbuf[ch], &s->bs, gr_info + ch, s->scf, layer3gr_limit);
  75989. }
  75990. if (DRMP3_HDR_TEST_I_STEREO(h->header))
  75991. {
  75992. drmp3_L3_intensity_stereo(s->grbuf[0], s->ist_pos[1], gr_info, h->header);
  75993. } else if (DRMP3_HDR_IS_MS_STEREO(h->header))
  75994. {
  75995. drmp3_L3_midside_stereo(s->grbuf[0], 576);
  75996. }
  75997. for (ch = 0; ch < nch; ch++, gr_info++)
  75998. {
  75999. int aa_bands = 31;
  76000. int n_long_bands = (gr_info->mixed_block_flag ? 2 : 0) << (int)(DRMP3_HDR_GET_MY_SAMPLE_RATE(h->header) == 2);
  76001. if (gr_info->n_short_sfb)
  76002. {
  76003. aa_bands = n_long_bands - 1;
  76004. drmp3_L3_reorder(s->grbuf[ch] + n_long_bands*18, s->syn[0], gr_info->sfbtab + gr_info->n_long_sfb);
  76005. }
  76006. drmp3_L3_antialias(s->grbuf[ch], aa_bands);
  76007. drmp3_L3_imdct_gr(s->grbuf[ch], h->mdct_overlap[ch], gr_info->block_type, n_long_bands);
  76008. drmp3_L3_change_sign(s->grbuf[ch]);
  76009. }
  76010. }
  76011. static void drmp3d_DCT_II(float *grbuf, int n)
  76012. {
  76013. static const float g_sec[24] = {
  76014. 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
  76015. };
  76016. int i, k = 0;
  76017. #if DRMP3_HAVE_SIMD
  76018. if (drmp3_have_simd()) for (; k < n; k += 4)
  76019. {
  76020. drmp3_f4 t[4][8], *x;
  76021. float *y = grbuf + k;
  76022. for (x = t[0], i = 0; i < 8; i++, x++)
  76023. {
  76024. drmp3_f4 x0 = DRMP3_VLD(&y[i*18]);
  76025. drmp3_f4 x1 = DRMP3_VLD(&y[(15 - i)*18]);
  76026. drmp3_f4 x2 = DRMP3_VLD(&y[(16 + i)*18]);
  76027. drmp3_f4 x3 = DRMP3_VLD(&y[(31 - i)*18]);
  76028. drmp3_f4 t0 = DRMP3_VADD(x0, x3);
  76029. drmp3_f4 t1 = DRMP3_VADD(x1, x2);
  76030. drmp3_f4 t2 = DRMP3_VMUL_S(DRMP3_VSUB(x1, x2), g_sec[3*i + 0]);
  76031. drmp3_f4 t3 = DRMP3_VMUL_S(DRMP3_VSUB(x0, x3), g_sec[3*i + 1]);
  76032. x[0] = DRMP3_VADD(t0, t1);
  76033. x[8] = DRMP3_VMUL_S(DRMP3_VSUB(t0, t1), g_sec[3*i + 2]);
  76034. x[16] = DRMP3_VADD(t3, t2);
  76035. x[24] = DRMP3_VMUL_S(DRMP3_VSUB(t3, t2), g_sec[3*i + 2]);
  76036. }
  76037. for (x = t[0], i = 0; i < 4; i++, x += 8)
  76038. {
  76039. drmp3_f4 x0 = x[0], x1 = x[1], x2 = x[2], x3 = x[3], x4 = x[4], x5 = x[5], x6 = x[6], x7 = x[7], xt;
  76040. xt = DRMP3_VSUB(x0, x7); x0 = DRMP3_VADD(x0, x7);
  76041. x7 = DRMP3_VSUB(x1, x6); x1 = DRMP3_VADD(x1, x6);
  76042. x6 = DRMP3_VSUB(x2, x5); x2 = DRMP3_VADD(x2, x5);
  76043. x5 = DRMP3_VSUB(x3, x4); x3 = DRMP3_VADD(x3, x4);
  76044. x4 = DRMP3_VSUB(x0, x3); x0 = DRMP3_VADD(x0, x3);
  76045. x3 = DRMP3_VSUB(x1, x2); x1 = DRMP3_VADD(x1, x2);
  76046. x[0] = DRMP3_VADD(x0, x1);
  76047. x[4] = DRMP3_VMUL_S(DRMP3_VSUB(x0, x1), 0.70710677f);
  76048. x5 = DRMP3_VADD(x5, x6);
  76049. x6 = DRMP3_VMUL_S(DRMP3_VADD(x6, x7), 0.70710677f);
  76050. x7 = DRMP3_VADD(x7, xt);
  76051. x3 = DRMP3_VMUL_S(DRMP3_VADD(x3, x4), 0.70710677f);
  76052. x5 = DRMP3_VSUB(x5, DRMP3_VMUL_S(x7, 0.198912367f));
  76053. x7 = DRMP3_VADD(x7, DRMP3_VMUL_S(x5, 0.382683432f));
  76054. x5 = DRMP3_VSUB(x5, DRMP3_VMUL_S(x7, 0.198912367f));
  76055. x0 = DRMP3_VSUB(xt, x6); xt = DRMP3_VADD(xt, x6);
  76056. x[1] = DRMP3_VMUL_S(DRMP3_VADD(xt, x7), 0.50979561f);
  76057. x[2] = DRMP3_VMUL_S(DRMP3_VADD(x4, x3), 0.54119611f);
  76058. x[3] = DRMP3_VMUL_S(DRMP3_VSUB(x0, x5), 0.60134488f);
  76059. x[5] = DRMP3_VMUL_S(DRMP3_VADD(x0, x5), 0.89997619f);
  76060. x[6] = DRMP3_VMUL_S(DRMP3_VSUB(x4, x3), 1.30656302f);
  76061. x[7] = DRMP3_VMUL_S(DRMP3_VSUB(xt, x7), 2.56291556f);
  76062. }
  76063. if (k > n - 3)
  76064. {
  76065. #if DRMP3_HAVE_SSE
  76066. #define DRMP3_VSAVE2(i, v) _mm_storel_pi((__m64 *)(void*)&y[i*18], v)
  76067. #else
  76068. #define DRMP3_VSAVE2(i, v) vst1_f32((float32_t *)&y[(i)*18], vget_low_f32(v))
  76069. #endif
  76070. for (i = 0; i < 7; i++, y += 4*18)
  76071. {
  76072. drmp3_f4 s = DRMP3_VADD(t[3][i], t[3][i + 1]);
  76073. DRMP3_VSAVE2(0, t[0][i]);
  76074. DRMP3_VSAVE2(1, DRMP3_VADD(t[2][i], s));
  76075. DRMP3_VSAVE2(2, DRMP3_VADD(t[1][i], t[1][i + 1]));
  76076. DRMP3_VSAVE2(3, DRMP3_VADD(t[2][1 + i], s));
  76077. }
  76078. DRMP3_VSAVE2(0, t[0][7]);
  76079. DRMP3_VSAVE2(1, DRMP3_VADD(t[2][7], t[3][7]));
  76080. DRMP3_VSAVE2(2, t[1][7]);
  76081. DRMP3_VSAVE2(3, t[3][7]);
  76082. } else
  76083. {
  76084. #define DRMP3_VSAVE4(i, v) DRMP3_VSTORE(&y[(i)*18], v)
  76085. for (i = 0; i < 7; i++, y += 4*18)
  76086. {
  76087. drmp3_f4 s = DRMP3_VADD(t[3][i], t[3][i + 1]);
  76088. DRMP3_VSAVE4(0, t[0][i]);
  76089. DRMP3_VSAVE4(1, DRMP3_VADD(t[2][i], s));
  76090. DRMP3_VSAVE4(2, DRMP3_VADD(t[1][i], t[1][i + 1]));
  76091. DRMP3_VSAVE4(3, DRMP3_VADD(t[2][1 + i], s));
  76092. }
  76093. DRMP3_VSAVE4(0, t[0][7]);
  76094. DRMP3_VSAVE4(1, DRMP3_VADD(t[2][7], t[3][7]));
  76095. DRMP3_VSAVE4(2, t[1][7]);
  76096. DRMP3_VSAVE4(3, t[3][7]);
  76097. }
  76098. } else
  76099. #endif
  76100. #ifdef DR_MP3_ONLY_SIMD
  76101. {}
  76102. #else
  76103. for (; k < n; k++)
  76104. {
  76105. float t[4][8], *x, *y = grbuf + k;
  76106. for (x = t[0], i = 0; i < 8; i++, x++)
  76107. {
  76108. float x0 = y[i*18];
  76109. float x1 = y[(15 - i)*18];
  76110. float x2 = y[(16 + i)*18];
  76111. float x3 = y[(31 - i)*18];
  76112. float t0 = x0 + x3;
  76113. float t1 = x1 + x2;
  76114. float t2 = (x1 - x2)*g_sec[3*i + 0];
  76115. float t3 = (x0 - x3)*g_sec[3*i + 1];
  76116. x[0] = t0 + t1;
  76117. x[8] = (t0 - t1)*g_sec[3*i + 2];
  76118. x[16] = t3 + t2;
  76119. x[24] = (t3 - t2)*g_sec[3*i + 2];
  76120. }
  76121. for (x = t[0], i = 0; i < 4; i++, x += 8)
  76122. {
  76123. 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;
  76124. xt = x0 - x7; x0 += x7;
  76125. x7 = x1 - x6; x1 += x6;
  76126. x6 = x2 - x5; x2 += x5;
  76127. x5 = x3 - x4; x3 += x4;
  76128. x4 = x0 - x3; x0 += x3;
  76129. x3 = x1 - x2; x1 += x2;
  76130. x[0] = x0 + x1;
  76131. x[4] = (x0 - x1)*0.70710677f;
  76132. x5 = x5 + x6;
  76133. x6 = (x6 + x7)*0.70710677f;
  76134. x7 = x7 + xt;
  76135. x3 = (x3 + x4)*0.70710677f;
  76136. x5 -= x7*0.198912367f;
  76137. x7 += x5*0.382683432f;
  76138. x5 -= x7*0.198912367f;
  76139. x0 = xt - x6; xt += x6;
  76140. x[1] = (xt + x7)*0.50979561f;
  76141. x[2] = (x4 + x3)*0.54119611f;
  76142. x[3] = (x0 - x5)*0.60134488f;
  76143. x[5] = (x0 + x5)*0.89997619f;
  76144. x[6] = (x4 - x3)*1.30656302f;
  76145. x[7] = (xt - x7)*2.56291556f;
  76146. }
  76147. for (i = 0; i < 7; i++, y += 4*18)
  76148. {
  76149. y[0*18] = t[0][i];
  76150. y[1*18] = t[2][i] + t[3][i] + t[3][i + 1];
  76151. y[2*18] = t[1][i] + t[1][i + 1];
  76152. y[3*18] = t[2][i + 1] + t[3][i] + t[3][i + 1];
  76153. }
  76154. y[0*18] = t[0][7];
  76155. y[1*18] = t[2][7] + t[3][7];
  76156. y[2*18] = t[1][7];
  76157. y[3*18] = t[3][7];
  76158. }
  76159. #endif
  76160. }
  76161. #ifndef DR_MP3_FLOAT_OUTPUT
  76162. typedef drmp3_int16 drmp3d_sample_t;
  76163. static drmp3_int16 drmp3d_scale_pcm(float sample)
  76164. {
  76165. drmp3_int16 s;
  76166. #if DRMP3_HAVE_ARMV6
  76167. drmp3_int32 s32 = (drmp3_int32)(sample + .5f);
  76168. s32 -= (s32 < 0);
  76169. s = (drmp3_int16)drmp3_clip_int16_arm(s32);
  76170. #else
  76171. if (sample >= 32766.5) return (drmp3_int16) 32767;
  76172. if (sample <= -32767.5) return (drmp3_int16)-32768;
  76173. s = (drmp3_int16)(sample + .5f);
  76174. s -= (s < 0);
  76175. #endif
  76176. return s;
  76177. }
  76178. #else
  76179. typedef float drmp3d_sample_t;
  76180. static float drmp3d_scale_pcm(float sample)
  76181. {
  76182. return sample*(1.f/32768.f);
  76183. }
  76184. #endif
  76185. static void drmp3d_synth_pair(drmp3d_sample_t *pcm, int nch, const float *z)
  76186. {
  76187. float a;
  76188. a = (z[14*64] - z[ 0]) * 29;
  76189. a += (z[ 1*64] + z[13*64]) * 213;
  76190. a += (z[12*64] - z[ 2*64]) * 459;
  76191. a += (z[ 3*64] + z[11*64]) * 2037;
  76192. a += (z[10*64] - z[ 4*64]) * 5153;
  76193. a += (z[ 5*64] + z[ 9*64]) * 6574;
  76194. a += (z[ 8*64] - z[ 6*64]) * 37489;
  76195. a += z[ 7*64] * 75038;
  76196. pcm[0] = drmp3d_scale_pcm(a);
  76197. z += 2;
  76198. a = z[14*64] * 104;
  76199. a += z[12*64] * 1567;
  76200. a += z[10*64] * 9727;
  76201. a += z[ 8*64] * 64019;
  76202. a += z[ 6*64] * -9975;
  76203. a += z[ 4*64] * -45;
  76204. a += z[ 2*64] * 146;
  76205. a += z[ 0*64] * -5;
  76206. pcm[16*nch] = drmp3d_scale_pcm(a);
  76207. }
  76208. static void drmp3d_synth(float *xl, drmp3d_sample_t *dstl, int nch, float *lins)
  76209. {
  76210. int i;
  76211. float *xr = xl + 576*(nch - 1);
  76212. drmp3d_sample_t *dstr = dstl + (nch - 1);
  76213. static const float g_win[] = {
  76214. -1,26,-31,208,218,401,-519,2063,2000,4788,-5517,7134,5959,35640,-39336,74992,
  76215. -1,24,-35,202,222,347,-581,2080,1952,4425,-5879,7640,5288,33791,-41176,74856,
  76216. -1,21,-38,196,225,294,-645,2087,1893,4063,-6237,8092,4561,31947,-43006,74630,
  76217. -1,19,-41,190,227,244,-711,2085,1822,3705,-6589,8492,3776,30112,-44821,74313,
  76218. -1,17,-45,183,228,197,-779,2075,1739,3351,-6935,8840,2935,28289,-46617,73908,
  76219. -1,16,-49,176,228,153,-848,2057,1644,3004,-7271,9139,2037,26482,-48390,73415,
  76220. -2,14,-53,169,227,111,-919,2032,1535,2663,-7597,9389,1082,24694,-50137,72835,
  76221. -2,13,-58,161,224,72,-991,2001,1414,2330,-7910,9592,70,22929,-51853,72169,
  76222. -2,11,-63,154,221,36,-1064,1962,1280,2006,-8209,9750,-998,21189,-53534,71420,
  76223. -2,10,-68,147,215,2,-1137,1919,1131,1692,-8491,9863,-2122,19478,-55178,70590,
  76224. -3,9,-73,139,208,-29,-1210,1870,970,1388,-8755,9935,-3300,17799,-56778,69679,
  76225. -3,8,-79,132,200,-57,-1283,1817,794,1095,-8998,9966,-4533,16155,-58333,68692,
  76226. -4,7,-85,125,189,-83,-1356,1759,605,814,-9219,9959,-5818,14548,-59838,67629,
  76227. -4,7,-91,117,177,-106,-1428,1698,402,545,-9416,9916,-7154,12980,-61289,66494,
  76228. -5,6,-97,111,163,-127,-1498,1634,185,288,-9585,9838,-8540,11455,-62684,65290
  76229. };
  76230. float *zlin = lins + 15*64;
  76231. const float *w = g_win;
  76232. zlin[4*15] = xl[18*16];
  76233. zlin[4*15 + 1] = xr[18*16];
  76234. zlin[4*15 + 2] = xl[0];
  76235. zlin[4*15 + 3] = xr[0];
  76236. zlin[4*31] = xl[1 + 18*16];
  76237. zlin[4*31 + 1] = xr[1 + 18*16];
  76238. zlin[4*31 + 2] = xl[1];
  76239. zlin[4*31 + 3] = xr[1];
  76240. drmp3d_synth_pair(dstr, nch, lins + 4*15 + 1);
  76241. drmp3d_synth_pair(dstr + 32*nch, nch, lins + 4*15 + 64 + 1);
  76242. drmp3d_synth_pair(dstl, nch, lins + 4*15);
  76243. drmp3d_synth_pair(dstl + 32*nch, nch, lins + 4*15 + 64);
  76244. #if DRMP3_HAVE_SIMD
  76245. if (drmp3_have_simd()) for (i = 14; i >= 0; i--)
  76246. {
  76247. #define DRMP3_VLOAD(k) drmp3_f4 w0 = DRMP3_VSET(*w++); drmp3_f4 w1 = DRMP3_VSET(*w++); drmp3_f4 vz = DRMP3_VLD(&zlin[4*i - 64*k]); drmp3_f4 vy = DRMP3_VLD(&zlin[4*i - 64*(15 - k)]);
  76248. #define DRMP3_V0(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0)) ; a = DRMP3_VSUB(DRMP3_VMUL(vz, w0), DRMP3_VMUL(vy, w1)); }
  76249. #define DRMP3_V1(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(b, DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0))); a = DRMP3_VADD(a, DRMP3_VSUB(DRMP3_VMUL(vz, w0), DRMP3_VMUL(vy, w1))); }
  76250. #define DRMP3_V2(k) { DRMP3_VLOAD(k) b = DRMP3_VADD(b, DRMP3_VADD(DRMP3_VMUL(vz, w1), DRMP3_VMUL(vy, w0))); a = DRMP3_VADD(a, DRMP3_VSUB(DRMP3_VMUL(vy, w1), DRMP3_VMUL(vz, w0))); }
  76251. drmp3_f4 a, b;
  76252. zlin[4*i] = xl[18*(31 - i)];
  76253. zlin[4*i + 1] = xr[18*(31 - i)];
  76254. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  76255. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  76256. zlin[4*i + 64] = xl[1 + 18*(1 + i)];
  76257. zlin[4*i + 64 + 1] = xr[1 + 18*(1 + i)];
  76258. zlin[4*i - 64 + 2] = xl[18*(1 + i)];
  76259. zlin[4*i - 64 + 3] = xr[18*(1 + i)];
  76260. DRMP3_V0(0) DRMP3_V2(1) DRMP3_V1(2) DRMP3_V2(3) DRMP3_V1(4) DRMP3_V2(5) DRMP3_V1(6) DRMP3_V2(7)
  76261. {
  76262. #ifndef DR_MP3_FLOAT_OUTPUT
  76263. #if DRMP3_HAVE_SSE
  76264. static const drmp3_f4 g_max = { 32767.0f, 32767.0f, 32767.0f, 32767.0f };
  76265. static const drmp3_f4 g_min = { -32768.0f, -32768.0f, -32768.0f, -32768.0f };
  76266. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, g_max), g_min)),
  76267. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, g_max), g_min)));
  76268. dstr[(15 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
  76269. dstr[(17 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 5);
  76270. dstl[(15 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
  76271. dstl[(17 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 4);
  76272. dstr[(47 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 3);
  76273. dstr[(49 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 7);
  76274. dstl[(47 - i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
  76275. dstl[(49 + i)*nch] = (drmp3_int16)_mm_extract_epi16(pcm8, 6);
  76276. #else
  76277. int16x4_t pcma, pcmb;
  76278. a = DRMP3_VADD(a, DRMP3_VSET(0.5f));
  76279. b = DRMP3_VADD(b, DRMP3_VSET(0.5f));
  76280. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, DRMP3_VSET(0)))));
  76281. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, DRMP3_VSET(0)))));
  76282. vst1_lane_s16(dstr + (15 - i)*nch, pcma, 1);
  76283. vst1_lane_s16(dstr + (17 + i)*nch, pcmb, 1);
  76284. vst1_lane_s16(dstl + (15 - i)*nch, pcma, 0);
  76285. vst1_lane_s16(dstl + (17 + i)*nch, pcmb, 0);
  76286. vst1_lane_s16(dstr + (47 - i)*nch, pcma, 3);
  76287. vst1_lane_s16(dstr + (49 + i)*nch, pcmb, 3);
  76288. vst1_lane_s16(dstl + (47 - i)*nch, pcma, 2);
  76289. vst1_lane_s16(dstl + (49 + i)*nch, pcmb, 2);
  76290. #endif
  76291. #else
  76292. #if DRMP3_HAVE_SSE
  76293. static const drmp3_f4 g_scale = { 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f, 1.0f/32768.0f };
  76294. #else
  76295. const drmp3_f4 g_scale = vdupq_n_f32(1.0f/32768.0f);
  76296. #endif
  76297. a = DRMP3_VMUL(a, g_scale);
  76298. b = DRMP3_VMUL(b, g_scale);
  76299. #if DRMP3_HAVE_SSE
  76300. _mm_store_ss(dstr + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(1, 1, 1, 1)));
  76301. _mm_store_ss(dstr + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(1, 1, 1, 1)));
  76302. _mm_store_ss(dstl + (15 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(0, 0, 0, 0)));
  76303. _mm_store_ss(dstl + (17 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(0, 0, 0, 0)));
  76304. _mm_store_ss(dstr + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(3, 3, 3, 3)));
  76305. _mm_store_ss(dstr + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(3, 3, 3, 3)));
  76306. _mm_store_ss(dstl + (47 - i)*nch, _mm_shuffle_ps(a, a, _MM_SHUFFLE(2, 2, 2, 2)));
  76307. _mm_store_ss(dstl + (49 + i)*nch, _mm_shuffle_ps(b, b, _MM_SHUFFLE(2, 2, 2, 2)));
  76308. #else
  76309. vst1q_lane_f32(dstr + (15 - i)*nch, a, 1);
  76310. vst1q_lane_f32(dstr + (17 + i)*nch, b, 1);
  76311. vst1q_lane_f32(dstl + (15 - i)*nch, a, 0);
  76312. vst1q_lane_f32(dstl + (17 + i)*nch, b, 0);
  76313. vst1q_lane_f32(dstr + (47 - i)*nch, a, 3);
  76314. vst1q_lane_f32(dstr + (49 + i)*nch, b, 3);
  76315. vst1q_lane_f32(dstl + (47 - i)*nch, a, 2);
  76316. vst1q_lane_f32(dstl + (49 + i)*nch, b, 2);
  76317. #endif
  76318. #endif
  76319. }
  76320. } else
  76321. #endif
  76322. #ifdef DR_MP3_ONLY_SIMD
  76323. {}
  76324. #else
  76325. for (i = 14; i >= 0; i--)
  76326. {
  76327. #define DRMP3_LOAD(k) float w0 = *w++; float w1 = *w++; float *vz = &zlin[4*i - k*64]; float *vy = &zlin[4*i - (15 - k)*64];
  76328. #define DRMP3_S0(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] = vz[j]*w1 + vy[j]*w0, a[j] = vz[j]*w0 - vy[j]*w1; }
  76329. #define DRMP3_S1(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vz[j]*w0 - vy[j]*w1; }
  76330. #define DRMP3_S2(k) { int j; DRMP3_LOAD(k); for (j = 0; j < 4; j++) b[j] += vz[j]*w1 + vy[j]*w0, a[j] += vy[j]*w1 - vz[j]*w0; }
  76331. float a[4], b[4];
  76332. zlin[4*i] = xl[18*(31 - i)];
  76333. zlin[4*i + 1] = xr[18*(31 - i)];
  76334. zlin[4*i + 2] = xl[1 + 18*(31 - i)];
  76335. zlin[4*i + 3] = xr[1 + 18*(31 - i)];
  76336. zlin[4*(i + 16)] = xl[1 + 18*(1 + i)];
  76337. zlin[4*(i + 16) + 1] = xr[1 + 18*(1 + i)];
  76338. zlin[4*(i - 16) + 2] = xl[18*(1 + i)];
  76339. zlin[4*(i - 16) + 3] = xr[18*(1 + i)];
  76340. DRMP3_S0(0) DRMP3_S2(1) DRMP3_S1(2) DRMP3_S2(3) DRMP3_S1(4) DRMP3_S2(5) DRMP3_S1(6) DRMP3_S2(7)
  76341. dstr[(15 - i)*nch] = drmp3d_scale_pcm(a[1]);
  76342. dstr[(17 + i)*nch] = drmp3d_scale_pcm(b[1]);
  76343. dstl[(15 - i)*nch] = drmp3d_scale_pcm(a[0]);
  76344. dstl[(17 + i)*nch] = drmp3d_scale_pcm(b[0]);
  76345. dstr[(47 - i)*nch] = drmp3d_scale_pcm(a[3]);
  76346. dstr[(49 + i)*nch] = drmp3d_scale_pcm(b[3]);
  76347. dstl[(47 - i)*nch] = drmp3d_scale_pcm(a[2]);
  76348. dstl[(49 + i)*nch] = drmp3d_scale_pcm(b[2]);
  76349. }
  76350. #endif
  76351. }
  76352. static void drmp3d_synth_granule(float *qmf_state, float *grbuf, int nbands, int nch, drmp3d_sample_t *pcm, float *lins)
  76353. {
  76354. int i;
  76355. for (i = 0; i < nch; i++)
  76356. {
  76357. drmp3d_DCT_II(grbuf + 576*i, nbands);
  76358. }
  76359. DRMP3_COPY_MEMORY(lins, qmf_state, sizeof(float)*15*64);
  76360. for (i = 0; i < nbands; i += 2)
  76361. {
  76362. drmp3d_synth(grbuf + i, pcm + 32*nch*i, nch, lins + i*64);
  76363. }
  76364. #ifndef DR_MP3_NONSTANDARD_BUT_LOGICAL
  76365. if (nch == 1)
  76366. {
  76367. for (i = 0; i < 15*64; i += 2)
  76368. {
  76369. qmf_state[i] = lins[nbands*64 + i];
  76370. }
  76371. } else
  76372. #endif
  76373. {
  76374. DRMP3_COPY_MEMORY(qmf_state, lins + nbands*64, sizeof(float)*15*64);
  76375. }
  76376. }
  76377. static int drmp3d_match_frame(const drmp3_uint8 *hdr, int mp3_bytes, int frame_bytes)
  76378. {
  76379. int i, nmatch;
  76380. for (i = 0, nmatch = 0; nmatch < DRMP3_MAX_FRAME_SYNC_MATCHES; nmatch++)
  76381. {
  76382. i += drmp3_hdr_frame_bytes(hdr + i, frame_bytes) + drmp3_hdr_padding(hdr + i);
  76383. if (i + DRMP3_HDR_SIZE > mp3_bytes)
  76384. return nmatch > 0;
  76385. if (!drmp3_hdr_compare(hdr, hdr + i))
  76386. return 0;
  76387. }
  76388. return 1;
  76389. }
  76390. static int drmp3d_find_frame(const drmp3_uint8 *mp3, int mp3_bytes, int *free_format_bytes, int *ptr_frame_bytes)
  76391. {
  76392. int i, k;
  76393. for (i = 0; i < mp3_bytes - DRMP3_HDR_SIZE; i++, mp3++)
  76394. {
  76395. if (drmp3_hdr_valid(mp3))
  76396. {
  76397. int frame_bytes = drmp3_hdr_frame_bytes(mp3, *free_format_bytes);
  76398. int frame_and_padding = frame_bytes + drmp3_hdr_padding(mp3);
  76399. for (k = DRMP3_HDR_SIZE; !frame_bytes && k < DRMP3_MAX_FREE_FORMAT_FRAME_SIZE && i + 2*k < mp3_bytes - DRMP3_HDR_SIZE; k++)
  76400. {
  76401. if (drmp3_hdr_compare(mp3, mp3 + k))
  76402. {
  76403. int fb = k - drmp3_hdr_padding(mp3);
  76404. int nextfb = fb + drmp3_hdr_padding(mp3 + k);
  76405. if (i + k + nextfb + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + k + nextfb))
  76406. continue;
  76407. frame_and_padding = k;
  76408. frame_bytes = fb;
  76409. *free_format_bytes = fb;
  76410. }
  76411. }
  76412. if ((frame_bytes && i + frame_and_padding <= mp3_bytes &&
  76413. drmp3d_match_frame(mp3, mp3_bytes - i, frame_bytes)) ||
  76414. (!i && frame_and_padding == mp3_bytes))
  76415. {
  76416. *ptr_frame_bytes = frame_and_padding;
  76417. return i;
  76418. }
  76419. *free_format_bytes = 0;
  76420. }
  76421. }
  76422. *ptr_frame_bytes = 0;
  76423. return mp3_bytes;
  76424. }
  76425. DRMP3_API void drmp3dec_init(drmp3dec *dec)
  76426. {
  76427. dec->header[0] = 0;
  76428. }
  76429. DRMP3_API int drmp3dec_decode_frame(drmp3dec *dec, const drmp3_uint8 *mp3, int mp3_bytes, void *pcm, drmp3dec_frame_info *info)
  76430. {
  76431. int i = 0, igr, frame_size = 0, success = 1;
  76432. const drmp3_uint8 *hdr;
  76433. drmp3_bs bs_frame[1];
  76434. drmp3dec_scratch scratch;
  76435. if (mp3_bytes > 4 && dec->header[0] == 0xff && drmp3_hdr_compare(dec->header, mp3))
  76436. {
  76437. frame_size = drmp3_hdr_frame_bytes(mp3, dec->free_format_bytes) + drmp3_hdr_padding(mp3);
  76438. if (frame_size != mp3_bytes && (frame_size + DRMP3_HDR_SIZE > mp3_bytes || !drmp3_hdr_compare(mp3, mp3 + frame_size)))
  76439. {
  76440. frame_size = 0;
  76441. }
  76442. }
  76443. if (!frame_size)
  76444. {
  76445. DRMP3_ZERO_MEMORY(dec, sizeof(drmp3dec));
  76446. i = drmp3d_find_frame(mp3, mp3_bytes, &dec->free_format_bytes, &frame_size);
  76447. if (!frame_size || i + frame_size > mp3_bytes)
  76448. {
  76449. info->frame_bytes = i;
  76450. return 0;
  76451. }
  76452. }
  76453. hdr = mp3 + i;
  76454. DRMP3_COPY_MEMORY(dec->header, hdr, DRMP3_HDR_SIZE);
  76455. info->frame_bytes = i + frame_size;
  76456. info->channels = DRMP3_HDR_IS_MONO(hdr) ? 1 : 2;
  76457. info->hz = drmp3_hdr_sample_rate_hz(hdr);
  76458. info->layer = 4 - DRMP3_HDR_GET_LAYER(hdr);
  76459. info->bitrate_kbps = drmp3_hdr_bitrate_kbps(hdr);
  76460. drmp3_bs_init(bs_frame, hdr + DRMP3_HDR_SIZE, frame_size - DRMP3_HDR_SIZE);
  76461. if (DRMP3_HDR_IS_CRC(hdr))
  76462. {
  76463. drmp3_bs_get_bits(bs_frame, 16);
  76464. }
  76465. if (info->layer == 3)
  76466. {
  76467. int main_data_begin = drmp3_L3_read_side_info(bs_frame, scratch.gr_info, hdr);
  76468. if (main_data_begin < 0 || bs_frame->pos > bs_frame->limit)
  76469. {
  76470. drmp3dec_init(dec);
  76471. return 0;
  76472. }
  76473. success = drmp3_L3_restore_reservoir(dec, bs_frame, &scratch, main_data_begin);
  76474. if (success && pcm != NULL)
  76475. {
  76476. for (igr = 0; igr < (DRMP3_HDR_TEST_MPEG1(hdr) ? 2 : 1); igr++, pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*576*info->channels))
  76477. {
  76478. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  76479. drmp3_L3_decode(dec, &scratch, scratch.gr_info + igr*info->channels, info->channels);
  76480. drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 18, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
  76481. }
  76482. }
  76483. drmp3_L3_save_reservoir(dec, &scratch);
  76484. } else
  76485. {
  76486. #ifdef DR_MP3_ONLY_MP3
  76487. return 0;
  76488. #else
  76489. drmp3_L12_scale_info sci[1];
  76490. if (pcm == NULL) {
  76491. return drmp3_hdr_frame_samples(hdr);
  76492. }
  76493. drmp3_L12_read_scale_info(hdr, bs_frame, sci);
  76494. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  76495. for (i = 0, igr = 0; igr < 3; igr++)
  76496. {
  76497. if (12 == (i += drmp3_L12_dequantize_granule(scratch.grbuf[0] + i, bs_frame, sci, info->layer | 1)))
  76498. {
  76499. i = 0;
  76500. drmp3_L12_apply_scf_384(sci, sci->scf + igr, scratch.grbuf[0]);
  76501. drmp3d_synth_granule(dec->qmf_state, scratch.grbuf[0], 12, info->channels, (drmp3d_sample_t*)pcm, scratch.syn[0]);
  76502. DRMP3_ZERO_MEMORY(scratch.grbuf[0], 576*2*sizeof(float));
  76503. pcm = DRMP3_OFFSET_PTR(pcm, sizeof(drmp3d_sample_t)*384*info->channels);
  76504. }
  76505. if (bs_frame->pos > bs_frame->limit)
  76506. {
  76507. drmp3dec_init(dec);
  76508. return 0;
  76509. }
  76510. }
  76511. #endif
  76512. }
  76513. return success*drmp3_hdr_frame_samples(dec->header);
  76514. }
  76515. DRMP3_API void drmp3dec_f32_to_s16(const float *in, drmp3_int16 *out, size_t num_samples)
  76516. {
  76517. size_t i = 0;
  76518. #if DRMP3_HAVE_SIMD
  76519. size_t aligned_count = num_samples & ~7;
  76520. for(; i < aligned_count; i+=8)
  76521. {
  76522. drmp3_f4 scale = DRMP3_VSET(32768.0f);
  76523. drmp3_f4 a = DRMP3_VMUL(DRMP3_VLD(&in[i ]), scale);
  76524. drmp3_f4 b = DRMP3_VMUL(DRMP3_VLD(&in[i+4]), scale);
  76525. #if DRMP3_HAVE_SSE
  76526. drmp3_f4 s16max = DRMP3_VSET( 32767.0f);
  76527. drmp3_f4 s16min = DRMP3_VSET(-32768.0f);
  76528. __m128i pcm8 = _mm_packs_epi32(_mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(a, s16max), s16min)),
  76529. _mm_cvtps_epi32(_mm_max_ps(_mm_min_ps(b, s16max), s16min)));
  76530. out[i ] = (drmp3_int16)_mm_extract_epi16(pcm8, 0);
  76531. out[i+1] = (drmp3_int16)_mm_extract_epi16(pcm8, 1);
  76532. out[i+2] = (drmp3_int16)_mm_extract_epi16(pcm8, 2);
  76533. out[i+3] = (drmp3_int16)_mm_extract_epi16(pcm8, 3);
  76534. out[i+4] = (drmp3_int16)_mm_extract_epi16(pcm8, 4);
  76535. out[i+5] = (drmp3_int16)_mm_extract_epi16(pcm8, 5);
  76536. out[i+6] = (drmp3_int16)_mm_extract_epi16(pcm8, 6);
  76537. out[i+7] = (drmp3_int16)_mm_extract_epi16(pcm8, 7);
  76538. #else
  76539. int16x4_t pcma, pcmb;
  76540. a = DRMP3_VADD(a, DRMP3_VSET(0.5f));
  76541. b = DRMP3_VADD(b, DRMP3_VSET(0.5f));
  76542. pcma = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(a), vreinterpretq_s32_u32(vcltq_f32(a, DRMP3_VSET(0)))));
  76543. pcmb = vqmovn_s32(vqaddq_s32(vcvtq_s32_f32(b), vreinterpretq_s32_u32(vcltq_f32(b, DRMP3_VSET(0)))));
  76544. vst1_lane_s16(out+i , pcma, 0);
  76545. vst1_lane_s16(out+i+1, pcma, 1);
  76546. vst1_lane_s16(out+i+2, pcma, 2);
  76547. vst1_lane_s16(out+i+3, pcma, 3);
  76548. vst1_lane_s16(out+i+4, pcmb, 0);
  76549. vst1_lane_s16(out+i+5, pcmb, 1);
  76550. vst1_lane_s16(out+i+6, pcmb, 2);
  76551. vst1_lane_s16(out+i+7, pcmb, 3);
  76552. #endif
  76553. }
  76554. #endif
  76555. for(; i < num_samples; i++)
  76556. {
  76557. float sample = in[i] * 32768.0f;
  76558. if (sample >= 32766.5)
  76559. out[i] = (drmp3_int16) 32767;
  76560. else if (sample <= -32767.5)
  76561. out[i] = (drmp3_int16)-32768;
  76562. else
  76563. {
  76564. short s = (drmp3_int16)(sample + .5f);
  76565. s -= (s < 0);
  76566. out[i] = s;
  76567. }
  76568. }
  76569. }
  76570. #if defined(SIZE_MAX)
  76571. #define DRMP3_SIZE_MAX SIZE_MAX
  76572. #else
  76573. #if defined(_WIN64) || defined(_LP64) || defined(__LP64__)
  76574. #define DRMP3_SIZE_MAX ((drmp3_uint64)0xFFFFFFFFFFFFFFFF)
  76575. #else
  76576. #define DRMP3_SIZE_MAX 0xFFFFFFFF
  76577. #endif
  76578. #endif
  76579. #ifndef DRMP3_SEEK_LEADING_MP3_FRAMES
  76580. #define DRMP3_SEEK_LEADING_MP3_FRAMES 2
  76581. #endif
  76582. #define DRMP3_MIN_DATA_CHUNK_SIZE 16384
  76583. #ifndef DRMP3_DATA_CHUNK_SIZE
  76584. #define DRMP3_DATA_CHUNK_SIZE (DRMP3_MIN_DATA_CHUNK_SIZE*4)
  76585. #endif
  76586. #define DRMP3_COUNTOF(x) (sizeof(x) / sizeof(x[0]))
  76587. #define DRMP3_CLAMP(x, lo, hi) (DRMP3_MAX(lo, DRMP3_MIN(x, hi)))
  76588. #ifndef DRMP3_PI_D
  76589. #define DRMP3_PI_D 3.14159265358979323846264
  76590. #endif
  76591. #define DRMP3_DEFAULT_RESAMPLER_LPF_ORDER 2
  76592. static DRMP3_INLINE float drmp3_mix_f32(float x, float y, float a)
  76593. {
  76594. return x*(1-a) + y*a;
  76595. }
  76596. static DRMP3_INLINE float drmp3_mix_f32_fast(float x, float y, float a)
  76597. {
  76598. float r0 = (y - x);
  76599. float r1 = r0*a;
  76600. return x + r1;
  76601. }
  76602. static DRMP3_INLINE drmp3_uint32 drmp3_gcf_u32(drmp3_uint32 a, drmp3_uint32 b)
  76603. {
  76604. for (;;) {
  76605. if (b == 0) {
  76606. break;
  76607. } else {
  76608. drmp3_uint32 t = a;
  76609. a = b;
  76610. b = t % a;
  76611. }
  76612. }
  76613. return a;
  76614. }
  76615. static void* drmp3__malloc_default(size_t sz, void* pUserData)
  76616. {
  76617. (void)pUserData;
  76618. return DRMP3_MALLOC(sz);
  76619. }
  76620. static void* drmp3__realloc_default(void* p, size_t sz, void* pUserData)
  76621. {
  76622. (void)pUserData;
  76623. return DRMP3_REALLOC(p, sz);
  76624. }
  76625. static void drmp3__free_default(void* p, void* pUserData)
  76626. {
  76627. (void)pUserData;
  76628. DRMP3_FREE(p);
  76629. }
  76630. static void* drmp3__malloc_from_callbacks(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76631. {
  76632. if (pAllocationCallbacks == NULL) {
  76633. return NULL;
  76634. }
  76635. if (pAllocationCallbacks->onMalloc != NULL) {
  76636. return pAllocationCallbacks->onMalloc(sz, pAllocationCallbacks->pUserData);
  76637. }
  76638. if (pAllocationCallbacks->onRealloc != NULL) {
  76639. return pAllocationCallbacks->onRealloc(NULL, sz, pAllocationCallbacks->pUserData);
  76640. }
  76641. return NULL;
  76642. }
  76643. static void* drmp3__realloc_from_callbacks(void* p, size_t szNew, size_t szOld, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76644. {
  76645. if (pAllocationCallbacks == NULL) {
  76646. return NULL;
  76647. }
  76648. if (pAllocationCallbacks->onRealloc != NULL) {
  76649. return pAllocationCallbacks->onRealloc(p, szNew, pAllocationCallbacks->pUserData);
  76650. }
  76651. if (pAllocationCallbacks->onMalloc != NULL && pAllocationCallbacks->onFree != NULL) {
  76652. void* p2;
  76653. p2 = pAllocationCallbacks->onMalloc(szNew, pAllocationCallbacks->pUserData);
  76654. if (p2 == NULL) {
  76655. return NULL;
  76656. }
  76657. if (p != NULL) {
  76658. DRMP3_COPY_MEMORY(p2, p, szOld);
  76659. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  76660. }
  76661. return p2;
  76662. }
  76663. return NULL;
  76664. }
  76665. static void drmp3__free_from_callbacks(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76666. {
  76667. if (p == NULL || pAllocationCallbacks == NULL) {
  76668. return;
  76669. }
  76670. if (pAllocationCallbacks->onFree != NULL) {
  76671. pAllocationCallbacks->onFree(p, pAllocationCallbacks->pUserData);
  76672. }
  76673. }
  76674. static drmp3_allocation_callbacks drmp3_copy_allocation_callbacks_or_defaults(const drmp3_allocation_callbacks* pAllocationCallbacks)
  76675. {
  76676. if (pAllocationCallbacks != NULL) {
  76677. return *pAllocationCallbacks;
  76678. } else {
  76679. drmp3_allocation_callbacks allocationCallbacks;
  76680. allocationCallbacks.pUserData = NULL;
  76681. allocationCallbacks.onMalloc = drmp3__malloc_default;
  76682. allocationCallbacks.onRealloc = drmp3__realloc_default;
  76683. allocationCallbacks.onFree = drmp3__free_default;
  76684. return allocationCallbacks;
  76685. }
  76686. }
  76687. static size_t drmp3__on_read(drmp3* pMP3, void* pBufferOut, size_t bytesToRead)
  76688. {
  76689. size_t bytesRead = pMP3->onRead(pMP3->pUserData, pBufferOut, bytesToRead);
  76690. pMP3->streamCursor += bytesRead;
  76691. return bytesRead;
  76692. }
  76693. static drmp3_bool32 drmp3__on_seek(drmp3* pMP3, int offset, drmp3_seek_origin origin)
  76694. {
  76695. DRMP3_ASSERT(offset >= 0);
  76696. if (!pMP3->onSeek(pMP3->pUserData, offset, origin)) {
  76697. return DRMP3_FALSE;
  76698. }
  76699. if (origin == drmp3_seek_origin_start) {
  76700. pMP3->streamCursor = (drmp3_uint64)offset;
  76701. } else {
  76702. pMP3->streamCursor += offset;
  76703. }
  76704. return DRMP3_TRUE;
  76705. }
  76706. static drmp3_bool32 drmp3__on_seek_64(drmp3* pMP3, drmp3_uint64 offset, drmp3_seek_origin origin)
  76707. {
  76708. if (offset <= 0x7FFFFFFF) {
  76709. return drmp3__on_seek(pMP3, (int)offset, origin);
  76710. }
  76711. if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_start)) {
  76712. return DRMP3_FALSE;
  76713. }
  76714. offset -= 0x7FFFFFFF;
  76715. while (offset > 0) {
  76716. if (offset <= 0x7FFFFFFF) {
  76717. if (!drmp3__on_seek(pMP3, (int)offset, drmp3_seek_origin_current)) {
  76718. return DRMP3_FALSE;
  76719. }
  76720. offset = 0;
  76721. } else {
  76722. if (!drmp3__on_seek(pMP3, 0x7FFFFFFF, drmp3_seek_origin_current)) {
  76723. return DRMP3_FALSE;
  76724. }
  76725. offset -= 0x7FFFFFFF;
  76726. }
  76727. }
  76728. return DRMP3_TRUE;
  76729. }
  76730. static drmp3_uint32 drmp3_decode_next_frame_ex__callbacks(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  76731. {
  76732. drmp3_uint32 pcmFramesRead = 0;
  76733. DRMP3_ASSERT(pMP3 != NULL);
  76734. DRMP3_ASSERT(pMP3->onRead != NULL);
  76735. if (pMP3->atEnd) {
  76736. return 0;
  76737. }
  76738. for (;;) {
  76739. drmp3dec_frame_info info;
  76740. if (pMP3->dataSize < DRMP3_MIN_DATA_CHUNK_SIZE) {
  76741. size_t bytesRead;
  76742. if (pMP3->pData != NULL) {
  76743. DRMP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  76744. }
  76745. pMP3->dataConsumed = 0;
  76746. if (pMP3->dataCapacity < DRMP3_DATA_CHUNK_SIZE) {
  76747. drmp3_uint8* pNewData;
  76748. size_t newDataCap;
  76749. newDataCap = DRMP3_DATA_CHUNK_SIZE;
  76750. pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  76751. if (pNewData == NULL) {
  76752. return 0;
  76753. }
  76754. pMP3->pData = pNewData;
  76755. pMP3->dataCapacity = newDataCap;
  76756. }
  76757. bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  76758. if (bytesRead == 0) {
  76759. if (pMP3->dataSize == 0) {
  76760. pMP3->atEnd = DRMP3_TRUE;
  76761. return 0;
  76762. }
  76763. }
  76764. pMP3->dataSize += bytesRead;
  76765. }
  76766. if (pMP3->dataSize > INT_MAX) {
  76767. pMP3->atEnd = DRMP3_TRUE;
  76768. return 0;
  76769. }
  76770. DRMP3_ASSERT(pMP3->pData != NULL);
  76771. DRMP3_ASSERT(pMP3->dataCapacity > 0);
  76772. pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->pData + pMP3->dataConsumed, (int)pMP3->dataSize, pPCMFrames, &info);
  76773. if (info.frame_bytes > 0) {
  76774. pMP3->dataConsumed += (size_t)info.frame_bytes;
  76775. pMP3->dataSize -= (size_t)info.frame_bytes;
  76776. }
  76777. if (pcmFramesRead > 0) {
  76778. pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header);
  76779. pMP3->pcmFramesConsumedInMP3Frame = 0;
  76780. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  76781. pMP3->mp3FrameChannels = info.channels;
  76782. pMP3->mp3FrameSampleRate = info.hz;
  76783. break;
  76784. } else if (info.frame_bytes == 0) {
  76785. size_t bytesRead;
  76786. DRMP3_MOVE_MEMORY(pMP3->pData, pMP3->pData + pMP3->dataConsumed, pMP3->dataSize);
  76787. pMP3->dataConsumed = 0;
  76788. if (pMP3->dataCapacity == pMP3->dataSize) {
  76789. drmp3_uint8* pNewData;
  76790. size_t newDataCap;
  76791. newDataCap = pMP3->dataCapacity + DRMP3_DATA_CHUNK_SIZE;
  76792. pNewData = (drmp3_uint8*)drmp3__realloc_from_callbacks(pMP3->pData, newDataCap, pMP3->dataCapacity, &pMP3->allocationCallbacks);
  76793. if (pNewData == NULL) {
  76794. return 0;
  76795. }
  76796. pMP3->pData = pNewData;
  76797. pMP3->dataCapacity = newDataCap;
  76798. }
  76799. bytesRead = drmp3__on_read(pMP3, pMP3->pData + pMP3->dataSize, (pMP3->dataCapacity - pMP3->dataSize));
  76800. if (bytesRead == 0) {
  76801. pMP3->atEnd = DRMP3_TRUE;
  76802. return 0;
  76803. }
  76804. pMP3->dataSize += bytesRead;
  76805. }
  76806. };
  76807. return pcmFramesRead;
  76808. }
  76809. static drmp3_uint32 drmp3_decode_next_frame_ex__memory(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  76810. {
  76811. drmp3_uint32 pcmFramesRead = 0;
  76812. drmp3dec_frame_info info;
  76813. DRMP3_ASSERT(pMP3 != NULL);
  76814. DRMP3_ASSERT(pMP3->memory.pData != NULL);
  76815. if (pMP3->atEnd) {
  76816. return 0;
  76817. }
  76818. for (;;) {
  76819. pcmFramesRead = drmp3dec_decode_frame(&pMP3->decoder, pMP3->memory.pData + pMP3->memory.currentReadPos, (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos), pPCMFrames, &info);
  76820. if (pcmFramesRead > 0) {
  76821. pcmFramesRead = drmp3_hdr_frame_samples(pMP3->decoder.header);
  76822. pMP3->pcmFramesConsumedInMP3Frame = 0;
  76823. pMP3->pcmFramesRemainingInMP3Frame = pcmFramesRead;
  76824. pMP3->mp3FrameChannels = info.channels;
  76825. pMP3->mp3FrameSampleRate = info.hz;
  76826. break;
  76827. } else if (info.frame_bytes > 0) {
  76828. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  76829. } else {
  76830. break;
  76831. }
  76832. }
  76833. pMP3->memory.currentReadPos += (size_t)info.frame_bytes;
  76834. return pcmFramesRead;
  76835. }
  76836. static drmp3_uint32 drmp3_decode_next_frame_ex(drmp3* pMP3, drmp3d_sample_t* pPCMFrames)
  76837. {
  76838. if (pMP3->memory.pData != NULL && pMP3->memory.dataSize > 0) {
  76839. return drmp3_decode_next_frame_ex__memory(pMP3, pPCMFrames);
  76840. } else {
  76841. return drmp3_decode_next_frame_ex__callbacks(pMP3, pPCMFrames);
  76842. }
  76843. }
  76844. static drmp3_uint32 drmp3_decode_next_frame(drmp3* pMP3)
  76845. {
  76846. DRMP3_ASSERT(pMP3 != NULL);
  76847. return drmp3_decode_next_frame_ex(pMP3, (drmp3d_sample_t*)pMP3->pcmFrames);
  76848. }
  76849. #if 0
  76850. static drmp3_uint32 drmp3_seek_next_frame(drmp3* pMP3)
  76851. {
  76852. drmp3_uint32 pcmFrameCount;
  76853. DRMP3_ASSERT(pMP3 != NULL);
  76854. pcmFrameCount = drmp3_decode_next_frame_ex(pMP3, NULL);
  76855. if (pcmFrameCount == 0) {
  76856. return 0;
  76857. }
  76858. pMP3->currentPCMFrame += pcmFrameCount;
  76859. pMP3->pcmFramesConsumedInMP3Frame = pcmFrameCount;
  76860. pMP3->pcmFramesRemainingInMP3Frame = 0;
  76861. return pcmFrameCount;
  76862. }
  76863. #endif
  76864. static drmp3_bool32 drmp3_init_internal(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76865. {
  76866. DRMP3_ASSERT(pMP3 != NULL);
  76867. DRMP3_ASSERT(onRead != NULL);
  76868. drmp3dec_init(&pMP3->decoder);
  76869. pMP3->onRead = onRead;
  76870. pMP3->onSeek = onSeek;
  76871. pMP3->pUserData = pUserData;
  76872. pMP3->allocationCallbacks = drmp3_copy_allocation_callbacks_or_defaults(pAllocationCallbacks);
  76873. if (pMP3->allocationCallbacks.onFree == NULL || (pMP3->allocationCallbacks.onMalloc == NULL && pMP3->allocationCallbacks.onRealloc == NULL)) {
  76874. return DRMP3_FALSE;
  76875. }
  76876. if (drmp3_decode_next_frame(pMP3) == 0) {
  76877. drmp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  76878. return DRMP3_FALSE;
  76879. }
  76880. pMP3->channels = pMP3->mp3FrameChannels;
  76881. pMP3->sampleRate = pMP3->mp3FrameSampleRate;
  76882. return DRMP3_TRUE;
  76883. }
  76884. DRMP3_API drmp3_bool32 drmp3_init(drmp3* pMP3, drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76885. {
  76886. if (pMP3 == NULL || onRead == NULL) {
  76887. return DRMP3_FALSE;
  76888. }
  76889. DRMP3_ZERO_OBJECT(pMP3);
  76890. return drmp3_init_internal(pMP3, onRead, onSeek, pUserData, pAllocationCallbacks);
  76891. }
  76892. static size_t drmp3__on_read_memory(void* pUserData, void* pBufferOut, size_t bytesToRead)
  76893. {
  76894. drmp3* pMP3 = (drmp3*)pUserData;
  76895. size_t bytesRemaining;
  76896. DRMP3_ASSERT(pMP3 != NULL);
  76897. DRMP3_ASSERT(pMP3->memory.dataSize >= pMP3->memory.currentReadPos);
  76898. bytesRemaining = pMP3->memory.dataSize - pMP3->memory.currentReadPos;
  76899. if (bytesToRead > bytesRemaining) {
  76900. bytesToRead = bytesRemaining;
  76901. }
  76902. if (bytesToRead > 0) {
  76903. DRMP3_COPY_MEMORY(pBufferOut, pMP3->memory.pData + pMP3->memory.currentReadPos, bytesToRead);
  76904. pMP3->memory.currentReadPos += bytesToRead;
  76905. }
  76906. return bytesToRead;
  76907. }
  76908. static drmp3_bool32 drmp3__on_seek_memory(void* pUserData, int byteOffset, drmp3_seek_origin origin)
  76909. {
  76910. drmp3* pMP3 = (drmp3*)pUserData;
  76911. DRMP3_ASSERT(pMP3 != NULL);
  76912. if (origin == drmp3_seek_origin_current) {
  76913. if (byteOffset > 0) {
  76914. if (pMP3->memory.currentReadPos + byteOffset > pMP3->memory.dataSize) {
  76915. byteOffset = (int)(pMP3->memory.dataSize - pMP3->memory.currentReadPos);
  76916. }
  76917. } else {
  76918. if (pMP3->memory.currentReadPos < (size_t)-byteOffset) {
  76919. byteOffset = -(int)pMP3->memory.currentReadPos;
  76920. }
  76921. }
  76922. pMP3->memory.currentReadPos += byteOffset;
  76923. } else {
  76924. if ((drmp3_uint32)byteOffset <= pMP3->memory.dataSize) {
  76925. pMP3->memory.currentReadPos = byteOffset;
  76926. } else {
  76927. pMP3->memory.currentReadPos = pMP3->memory.dataSize;
  76928. }
  76929. }
  76930. return DRMP3_TRUE;
  76931. }
  76932. DRMP3_API drmp3_bool32 drmp3_init_memory(drmp3* pMP3, const void* pData, size_t dataSize, const drmp3_allocation_callbacks* pAllocationCallbacks)
  76933. {
  76934. if (pMP3 == NULL) {
  76935. return DRMP3_FALSE;
  76936. }
  76937. DRMP3_ZERO_OBJECT(pMP3);
  76938. if (pData == NULL || dataSize == 0) {
  76939. return DRMP3_FALSE;
  76940. }
  76941. pMP3->memory.pData = (const drmp3_uint8*)pData;
  76942. pMP3->memory.dataSize = dataSize;
  76943. pMP3->memory.currentReadPos = 0;
  76944. return drmp3_init_internal(pMP3, drmp3__on_read_memory, drmp3__on_seek_memory, pMP3, pAllocationCallbacks);
  76945. }
  76946. #ifndef DR_MP3_NO_STDIO
  76947. #include <stdio.h>
  76948. #include <wchar.h>
  76949. #include <errno.h>
  76950. static drmp3_result drmp3_result_from_errno(int e)
  76951. {
  76952. switch (e)
  76953. {
  76954. case 0: return DRMP3_SUCCESS;
  76955. #ifdef EPERM
  76956. case EPERM: return DRMP3_INVALID_OPERATION;
  76957. #endif
  76958. #ifdef ENOENT
  76959. case ENOENT: return DRMP3_DOES_NOT_EXIST;
  76960. #endif
  76961. #ifdef ESRCH
  76962. case ESRCH: return DRMP3_DOES_NOT_EXIST;
  76963. #endif
  76964. #ifdef EINTR
  76965. case EINTR: return DRMP3_INTERRUPT;
  76966. #endif
  76967. #ifdef EIO
  76968. case EIO: return DRMP3_IO_ERROR;
  76969. #endif
  76970. #ifdef ENXIO
  76971. case ENXIO: return DRMP3_DOES_NOT_EXIST;
  76972. #endif
  76973. #ifdef E2BIG
  76974. case E2BIG: return DRMP3_INVALID_ARGS;
  76975. #endif
  76976. #ifdef ENOEXEC
  76977. case ENOEXEC: return DRMP3_INVALID_FILE;
  76978. #endif
  76979. #ifdef EBADF
  76980. case EBADF: return DRMP3_INVALID_FILE;
  76981. #endif
  76982. #ifdef ECHILD
  76983. case ECHILD: return DRMP3_ERROR;
  76984. #endif
  76985. #ifdef EAGAIN
  76986. case EAGAIN: return DRMP3_UNAVAILABLE;
  76987. #endif
  76988. #ifdef ENOMEM
  76989. case ENOMEM: return DRMP3_OUT_OF_MEMORY;
  76990. #endif
  76991. #ifdef EACCES
  76992. case EACCES: return DRMP3_ACCESS_DENIED;
  76993. #endif
  76994. #ifdef EFAULT
  76995. case EFAULT: return DRMP3_BAD_ADDRESS;
  76996. #endif
  76997. #ifdef ENOTBLK
  76998. case ENOTBLK: return DRMP3_ERROR;
  76999. #endif
  77000. #ifdef EBUSY
  77001. case EBUSY: return DRMP3_BUSY;
  77002. #endif
  77003. #ifdef EEXIST
  77004. case EEXIST: return DRMP3_ALREADY_EXISTS;
  77005. #endif
  77006. #ifdef EXDEV
  77007. case EXDEV: return DRMP3_ERROR;
  77008. #endif
  77009. #ifdef ENODEV
  77010. case ENODEV: return DRMP3_DOES_NOT_EXIST;
  77011. #endif
  77012. #ifdef ENOTDIR
  77013. case ENOTDIR: return DRMP3_NOT_DIRECTORY;
  77014. #endif
  77015. #ifdef EISDIR
  77016. case EISDIR: return DRMP3_IS_DIRECTORY;
  77017. #endif
  77018. #ifdef EINVAL
  77019. case EINVAL: return DRMP3_INVALID_ARGS;
  77020. #endif
  77021. #ifdef ENFILE
  77022. case ENFILE: return DRMP3_TOO_MANY_OPEN_FILES;
  77023. #endif
  77024. #ifdef EMFILE
  77025. case EMFILE: return DRMP3_TOO_MANY_OPEN_FILES;
  77026. #endif
  77027. #ifdef ENOTTY
  77028. case ENOTTY: return DRMP3_INVALID_OPERATION;
  77029. #endif
  77030. #ifdef ETXTBSY
  77031. case ETXTBSY: return DRMP3_BUSY;
  77032. #endif
  77033. #ifdef EFBIG
  77034. case EFBIG: return DRMP3_TOO_BIG;
  77035. #endif
  77036. #ifdef ENOSPC
  77037. case ENOSPC: return DRMP3_NO_SPACE;
  77038. #endif
  77039. #ifdef ESPIPE
  77040. case ESPIPE: return DRMP3_BAD_SEEK;
  77041. #endif
  77042. #ifdef EROFS
  77043. case EROFS: return DRMP3_ACCESS_DENIED;
  77044. #endif
  77045. #ifdef EMLINK
  77046. case EMLINK: return DRMP3_TOO_MANY_LINKS;
  77047. #endif
  77048. #ifdef EPIPE
  77049. case EPIPE: return DRMP3_BAD_PIPE;
  77050. #endif
  77051. #ifdef EDOM
  77052. case EDOM: return DRMP3_OUT_OF_RANGE;
  77053. #endif
  77054. #ifdef ERANGE
  77055. case ERANGE: return DRMP3_OUT_OF_RANGE;
  77056. #endif
  77057. #ifdef EDEADLK
  77058. case EDEADLK: return DRMP3_DEADLOCK;
  77059. #endif
  77060. #ifdef ENAMETOOLONG
  77061. case ENAMETOOLONG: return DRMP3_PATH_TOO_LONG;
  77062. #endif
  77063. #ifdef ENOLCK
  77064. case ENOLCK: return DRMP3_ERROR;
  77065. #endif
  77066. #ifdef ENOSYS
  77067. case ENOSYS: return DRMP3_NOT_IMPLEMENTED;
  77068. #endif
  77069. #ifdef ENOTEMPTY
  77070. case ENOTEMPTY: return DRMP3_DIRECTORY_NOT_EMPTY;
  77071. #endif
  77072. #ifdef ELOOP
  77073. case ELOOP: return DRMP3_TOO_MANY_LINKS;
  77074. #endif
  77075. #ifdef ENOMSG
  77076. case ENOMSG: return DRMP3_NO_MESSAGE;
  77077. #endif
  77078. #ifdef EIDRM
  77079. case EIDRM: return DRMP3_ERROR;
  77080. #endif
  77081. #ifdef ECHRNG
  77082. case ECHRNG: return DRMP3_ERROR;
  77083. #endif
  77084. #ifdef EL2NSYNC
  77085. case EL2NSYNC: return DRMP3_ERROR;
  77086. #endif
  77087. #ifdef EL3HLT
  77088. case EL3HLT: return DRMP3_ERROR;
  77089. #endif
  77090. #ifdef EL3RST
  77091. case EL3RST: return DRMP3_ERROR;
  77092. #endif
  77093. #ifdef ELNRNG
  77094. case ELNRNG: return DRMP3_OUT_OF_RANGE;
  77095. #endif
  77096. #ifdef EUNATCH
  77097. case EUNATCH: return DRMP3_ERROR;
  77098. #endif
  77099. #ifdef ENOCSI
  77100. case ENOCSI: return DRMP3_ERROR;
  77101. #endif
  77102. #ifdef EL2HLT
  77103. case EL2HLT: return DRMP3_ERROR;
  77104. #endif
  77105. #ifdef EBADE
  77106. case EBADE: return DRMP3_ERROR;
  77107. #endif
  77108. #ifdef EBADR
  77109. case EBADR: return DRMP3_ERROR;
  77110. #endif
  77111. #ifdef EXFULL
  77112. case EXFULL: return DRMP3_ERROR;
  77113. #endif
  77114. #ifdef ENOANO
  77115. case ENOANO: return DRMP3_ERROR;
  77116. #endif
  77117. #ifdef EBADRQC
  77118. case EBADRQC: return DRMP3_ERROR;
  77119. #endif
  77120. #ifdef EBADSLT
  77121. case EBADSLT: return DRMP3_ERROR;
  77122. #endif
  77123. #ifdef EBFONT
  77124. case EBFONT: return DRMP3_INVALID_FILE;
  77125. #endif
  77126. #ifdef ENOSTR
  77127. case ENOSTR: return DRMP3_ERROR;
  77128. #endif
  77129. #ifdef ENODATA
  77130. case ENODATA: return DRMP3_NO_DATA_AVAILABLE;
  77131. #endif
  77132. #ifdef ETIME
  77133. case ETIME: return DRMP3_TIMEOUT;
  77134. #endif
  77135. #ifdef ENOSR
  77136. case ENOSR: return DRMP3_NO_DATA_AVAILABLE;
  77137. #endif
  77138. #ifdef ENONET
  77139. case ENONET: return DRMP3_NO_NETWORK;
  77140. #endif
  77141. #ifdef ENOPKG
  77142. case ENOPKG: return DRMP3_ERROR;
  77143. #endif
  77144. #ifdef EREMOTE
  77145. case EREMOTE: return DRMP3_ERROR;
  77146. #endif
  77147. #ifdef ENOLINK
  77148. case ENOLINK: return DRMP3_ERROR;
  77149. #endif
  77150. #ifdef EADV
  77151. case EADV: return DRMP3_ERROR;
  77152. #endif
  77153. #ifdef ESRMNT
  77154. case ESRMNT: return DRMP3_ERROR;
  77155. #endif
  77156. #ifdef ECOMM
  77157. case ECOMM: return DRMP3_ERROR;
  77158. #endif
  77159. #ifdef EPROTO
  77160. case EPROTO: return DRMP3_ERROR;
  77161. #endif
  77162. #ifdef EMULTIHOP
  77163. case EMULTIHOP: return DRMP3_ERROR;
  77164. #endif
  77165. #ifdef EDOTDOT
  77166. case EDOTDOT: return DRMP3_ERROR;
  77167. #endif
  77168. #ifdef EBADMSG
  77169. case EBADMSG: return DRMP3_BAD_MESSAGE;
  77170. #endif
  77171. #ifdef EOVERFLOW
  77172. case EOVERFLOW: return DRMP3_TOO_BIG;
  77173. #endif
  77174. #ifdef ENOTUNIQ
  77175. case ENOTUNIQ: return DRMP3_NOT_UNIQUE;
  77176. #endif
  77177. #ifdef EBADFD
  77178. case EBADFD: return DRMP3_ERROR;
  77179. #endif
  77180. #ifdef EREMCHG
  77181. case EREMCHG: return DRMP3_ERROR;
  77182. #endif
  77183. #ifdef ELIBACC
  77184. case ELIBACC: return DRMP3_ACCESS_DENIED;
  77185. #endif
  77186. #ifdef ELIBBAD
  77187. case ELIBBAD: return DRMP3_INVALID_FILE;
  77188. #endif
  77189. #ifdef ELIBSCN
  77190. case ELIBSCN: return DRMP3_INVALID_FILE;
  77191. #endif
  77192. #ifdef ELIBMAX
  77193. case ELIBMAX: return DRMP3_ERROR;
  77194. #endif
  77195. #ifdef ELIBEXEC
  77196. case ELIBEXEC: return DRMP3_ERROR;
  77197. #endif
  77198. #ifdef EILSEQ
  77199. case EILSEQ: return DRMP3_INVALID_DATA;
  77200. #endif
  77201. #ifdef ERESTART
  77202. case ERESTART: return DRMP3_ERROR;
  77203. #endif
  77204. #ifdef ESTRPIPE
  77205. case ESTRPIPE: return DRMP3_ERROR;
  77206. #endif
  77207. #ifdef EUSERS
  77208. case EUSERS: return DRMP3_ERROR;
  77209. #endif
  77210. #ifdef ENOTSOCK
  77211. case ENOTSOCK: return DRMP3_NOT_SOCKET;
  77212. #endif
  77213. #ifdef EDESTADDRREQ
  77214. case EDESTADDRREQ: return DRMP3_NO_ADDRESS;
  77215. #endif
  77216. #ifdef EMSGSIZE
  77217. case EMSGSIZE: return DRMP3_TOO_BIG;
  77218. #endif
  77219. #ifdef EPROTOTYPE
  77220. case EPROTOTYPE: return DRMP3_BAD_PROTOCOL;
  77221. #endif
  77222. #ifdef ENOPROTOOPT
  77223. case ENOPROTOOPT: return DRMP3_PROTOCOL_UNAVAILABLE;
  77224. #endif
  77225. #ifdef EPROTONOSUPPORT
  77226. case EPROTONOSUPPORT: return DRMP3_PROTOCOL_NOT_SUPPORTED;
  77227. #endif
  77228. #ifdef ESOCKTNOSUPPORT
  77229. case ESOCKTNOSUPPORT: return DRMP3_SOCKET_NOT_SUPPORTED;
  77230. #endif
  77231. #ifdef EOPNOTSUPP
  77232. case EOPNOTSUPP: return DRMP3_INVALID_OPERATION;
  77233. #endif
  77234. #ifdef EPFNOSUPPORT
  77235. case EPFNOSUPPORT: return DRMP3_PROTOCOL_FAMILY_NOT_SUPPORTED;
  77236. #endif
  77237. #ifdef EAFNOSUPPORT
  77238. case EAFNOSUPPORT: return DRMP3_ADDRESS_FAMILY_NOT_SUPPORTED;
  77239. #endif
  77240. #ifdef EADDRINUSE
  77241. case EADDRINUSE: return DRMP3_ALREADY_IN_USE;
  77242. #endif
  77243. #ifdef EADDRNOTAVAIL
  77244. case EADDRNOTAVAIL: return DRMP3_ERROR;
  77245. #endif
  77246. #ifdef ENETDOWN
  77247. case ENETDOWN: return DRMP3_NO_NETWORK;
  77248. #endif
  77249. #ifdef ENETUNREACH
  77250. case ENETUNREACH: return DRMP3_NO_NETWORK;
  77251. #endif
  77252. #ifdef ENETRESET
  77253. case ENETRESET: return DRMP3_NO_NETWORK;
  77254. #endif
  77255. #ifdef ECONNABORTED
  77256. case ECONNABORTED: return DRMP3_NO_NETWORK;
  77257. #endif
  77258. #ifdef ECONNRESET
  77259. case ECONNRESET: return DRMP3_CONNECTION_RESET;
  77260. #endif
  77261. #ifdef ENOBUFS
  77262. case ENOBUFS: return DRMP3_NO_SPACE;
  77263. #endif
  77264. #ifdef EISCONN
  77265. case EISCONN: return DRMP3_ALREADY_CONNECTED;
  77266. #endif
  77267. #ifdef ENOTCONN
  77268. case ENOTCONN: return DRMP3_NOT_CONNECTED;
  77269. #endif
  77270. #ifdef ESHUTDOWN
  77271. case ESHUTDOWN: return DRMP3_ERROR;
  77272. #endif
  77273. #ifdef ETOOMANYREFS
  77274. case ETOOMANYREFS: return DRMP3_ERROR;
  77275. #endif
  77276. #ifdef ETIMEDOUT
  77277. case ETIMEDOUT: return DRMP3_TIMEOUT;
  77278. #endif
  77279. #ifdef ECONNREFUSED
  77280. case ECONNREFUSED: return DRMP3_CONNECTION_REFUSED;
  77281. #endif
  77282. #ifdef EHOSTDOWN
  77283. case EHOSTDOWN: return DRMP3_NO_HOST;
  77284. #endif
  77285. #ifdef EHOSTUNREACH
  77286. case EHOSTUNREACH: return DRMP3_NO_HOST;
  77287. #endif
  77288. #ifdef EALREADY
  77289. case EALREADY: return DRMP3_IN_PROGRESS;
  77290. #endif
  77291. #ifdef EINPROGRESS
  77292. case EINPROGRESS: return DRMP3_IN_PROGRESS;
  77293. #endif
  77294. #ifdef ESTALE
  77295. case ESTALE: return DRMP3_INVALID_FILE;
  77296. #endif
  77297. #ifdef EUCLEAN
  77298. case EUCLEAN: return DRMP3_ERROR;
  77299. #endif
  77300. #ifdef ENOTNAM
  77301. case ENOTNAM: return DRMP3_ERROR;
  77302. #endif
  77303. #ifdef ENAVAIL
  77304. case ENAVAIL: return DRMP3_ERROR;
  77305. #endif
  77306. #ifdef EISNAM
  77307. case EISNAM: return DRMP3_ERROR;
  77308. #endif
  77309. #ifdef EREMOTEIO
  77310. case EREMOTEIO: return DRMP3_IO_ERROR;
  77311. #endif
  77312. #ifdef EDQUOT
  77313. case EDQUOT: return DRMP3_NO_SPACE;
  77314. #endif
  77315. #ifdef ENOMEDIUM
  77316. case ENOMEDIUM: return DRMP3_DOES_NOT_EXIST;
  77317. #endif
  77318. #ifdef EMEDIUMTYPE
  77319. case EMEDIUMTYPE: return DRMP3_ERROR;
  77320. #endif
  77321. #ifdef ECANCELED
  77322. case ECANCELED: return DRMP3_CANCELLED;
  77323. #endif
  77324. #ifdef ENOKEY
  77325. case ENOKEY: return DRMP3_ERROR;
  77326. #endif
  77327. #ifdef EKEYEXPIRED
  77328. case EKEYEXPIRED: return DRMP3_ERROR;
  77329. #endif
  77330. #ifdef EKEYREVOKED
  77331. case EKEYREVOKED: return DRMP3_ERROR;
  77332. #endif
  77333. #ifdef EKEYREJECTED
  77334. case EKEYREJECTED: return DRMP3_ERROR;
  77335. #endif
  77336. #ifdef EOWNERDEAD
  77337. case EOWNERDEAD: return DRMP3_ERROR;
  77338. #endif
  77339. #ifdef ENOTRECOVERABLE
  77340. case ENOTRECOVERABLE: return DRMP3_ERROR;
  77341. #endif
  77342. #ifdef ERFKILL
  77343. case ERFKILL: return DRMP3_ERROR;
  77344. #endif
  77345. #ifdef EHWPOISON
  77346. case EHWPOISON: return DRMP3_ERROR;
  77347. #endif
  77348. default: return DRMP3_ERROR;
  77349. }
  77350. }
  77351. static drmp3_result drmp3_fopen(FILE** ppFile, const char* pFilePath, const char* pOpenMode)
  77352. {
  77353. #if defined(_MSC_VER) && _MSC_VER >= 1400
  77354. errno_t err;
  77355. #endif
  77356. if (ppFile != NULL) {
  77357. *ppFile = NULL;
  77358. }
  77359. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  77360. return DRMP3_INVALID_ARGS;
  77361. }
  77362. #if defined(_MSC_VER) && _MSC_VER >= 1400
  77363. err = fopen_s(ppFile, pFilePath, pOpenMode);
  77364. if (err != 0) {
  77365. return drmp3_result_from_errno(err);
  77366. }
  77367. #else
  77368. #if defined(_WIN32) || defined(__APPLE__)
  77369. *ppFile = fopen(pFilePath, pOpenMode);
  77370. #else
  77371. #if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64 && defined(_LARGEFILE64_SOURCE)
  77372. *ppFile = fopen64(pFilePath, pOpenMode);
  77373. #else
  77374. *ppFile = fopen(pFilePath, pOpenMode);
  77375. #endif
  77376. #endif
  77377. if (*ppFile == NULL) {
  77378. drmp3_result result = drmp3_result_from_errno(errno);
  77379. if (result == DRMP3_SUCCESS) {
  77380. result = DRMP3_ERROR;
  77381. }
  77382. return result;
  77383. }
  77384. #endif
  77385. return DRMP3_SUCCESS;
  77386. }
  77387. #if defined(_WIN32)
  77388. #if defined(_MSC_VER) || defined(__MINGW64__) || (!defined(__STRICT_ANSI__) && !defined(_NO_EXT_KEYS))
  77389. #define DRMP3_HAS_WFOPEN
  77390. #endif
  77391. #endif
  77392. static drmp3_result drmp3_wfopen(FILE** ppFile, const wchar_t* pFilePath, const wchar_t* pOpenMode, const drmp3_allocation_callbacks* pAllocationCallbacks)
  77393. {
  77394. if (ppFile != NULL) {
  77395. *ppFile = NULL;
  77396. }
  77397. if (pFilePath == NULL || pOpenMode == NULL || ppFile == NULL) {
  77398. return DRMP3_INVALID_ARGS;
  77399. }
  77400. #if defined(DRMP3_HAS_WFOPEN)
  77401. {
  77402. #if defined(_MSC_VER) && _MSC_VER >= 1400
  77403. errno_t err = _wfopen_s(ppFile, pFilePath, pOpenMode);
  77404. if (err != 0) {
  77405. return drmp3_result_from_errno(err);
  77406. }
  77407. #else
  77408. *ppFile = _wfopen(pFilePath, pOpenMode);
  77409. if (*ppFile == NULL) {
  77410. return drmp3_result_from_errno(errno);
  77411. }
  77412. #endif
  77413. (void)pAllocationCallbacks;
  77414. }
  77415. #else
  77416. #if defined(__DJGPP__)
  77417. {
  77418. }
  77419. #else
  77420. {
  77421. mbstate_t mbs;
  77422. size_t lenMB;
  77423. const wchar_t* pFilePathTemp = pFilePath;
  77424. char* pFilePathMB = NULL;
  77425. char pOpenModeMB[32] = {0};
  77426. DRMP3_ZERO_OBJECT(&mbs);
  77427. lenMB = wcsrtombs(NULL, &pFilePathTemp, 0, &mbs);
  77428. if (lenMB == (size_t)-1) {
  77429. return drmp3_result_from_errno(errno);
  77430. }
  77431. pFilePathMB = (char*)drmp3__malloc_from_callbacks(lenMB + 1, pAllocationCallbacks);
  77432. if (pFilePathMB == NULL) {
  77433. return DRMP3_OUT_OF_MEMORY;
  77434. }
  77435. pFilePathTemp = pFilePath;
  77436. DRMP3_ZERO_OBJECT(&mbs);
  77437. wcsrtombs(pFilePathMB, &pFilePathTemp, lenMB + 1, &mbs);
  77438. {
  77439. size_t i = 0;
  77440. for (;;) {
  77441. if (pOpenMode[i] == 0) {
  77442. pOpenModeMB[i] = '\0';
  77443. break;
  77444. }
  77445. pOpenModeMB[i] = (char)pOpenMode[i];
  77446. i += 1;
  77447. }
  77448. }
  77449. *ppFile = fopen(pFilePathMB, pOpenModeMB);
  77450. drmp3__free_from_callbacks(pFilePathMB, pAllocationCallbacks);
  77451. }
  77452. #endif
  77453. if (*ppFile == NULL) {
  77454. return DRMP3_ERROR;
  77455. }
  77456. #endif
  77457. return DRMP3_SUCCESS;
  77458. }
  77459. static size_t drmp3__on_read_stdio(void* pUserData, void* pBufferOut, size_t bytesToRead)
  77460. {
  77461. return fread(pBufferOut, 1, bytesToRead, (FILE*)pUserData);
  77462. }
  77463. static drmp3_bool32 drmp3__on_seek_stdio(void* pUserData, int offset, drmp3_seek_origin origin)
  77464. {
  77465. return fseek((FILE*)pUserData, offset, (origin == drmp3_seek_origin_current) ? SEEK_CUR : SEEK_SET) == 0;
  77466. }
  77467. DRMP3_API drmp3_bool32 drmp3_init_file(drmp3* pMP3, const char* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks)
  77468. {
  77469. drmp3_bool32 result;
  77470. FILE* pFile;
  77471. if (drmp3_fopen(&pFile, pFilePath, "rb") != DRMP3_SUCCESS) {
  77472. return DRMP3_FALSE;
  77473. }
  77474. result = drmp3_init(pMP3, drmp3__on_read_stdio, drmp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  77475. if (result != DRMP3_TRUE) {
  77476. fclose(pFile);
  77477. return result;
  77478. }
  77479. return DRMP3_TRUE;
  77480. }
  77481. DRMP3_API drmp3_bool32 drmp3_init_file_w(drmp3* pMP3, const wchar_t* pFilePath, const drmp3_allocation_callbacks* pAllocationCallbacks)
  77482. {
  77483. drmp3_bool32 result;
  77484. FILE* pFile;
  77485. if (drmp3_wfopen(&pFile, pFilePath, L"rb", pAllocationCallbacks) != DRMP3_SUCCESS) {
  77486. return DRMP3_FALSE;
  77487. }
  77488. result = drmp3_init(pMP3, drmp3__on_read_stdio, drmp3__on_seek_stdio, (void*)pFile, pAllocationCallbacks);
  77489. if (result != DRMP3_TRUE) {
  77490. fclose(pFile);
  77491. return result;
  77492. }
  77493. return DRMP3_TRUE;
  77494. }
  77495. #endif
  77496. DRMP3_API void drmp3_uninit(drmp3* pMP3)
  77497. {
  77498. if (pMP3 == NULL) {
  77499. return;
  77500. }
  77501. #ifndef DR_MP3_NO_STDIO
  77502. if (pMP3->onRead == drmp3__on_read_stdio) {
  77503. FILE* pFile = (FILE*)pMP3->pUserData;
  77504. if (pFile != NULL) {
  77505. fclose(pFile);
  77506. pMP3->pUserData = NULL;
  77507. }
  77508. }
  77509. #endif
  77510. drmp3__free_from_callbacks(pMP3->pData, &pMP3->allocationCallbacks);
  77511. }
  77512. #if defined(DR_MP3_FLOAT_OUTPUT)
  77513. static void drmp3_f32_to_s16(drmp3_int16* dst, const float* src, drmp3_uint64 sampleCount)
  77514. {
  77515. drmp3_uint64 i;
  77516. drmp3_uint64 i4;
  77517. drmp3_uint64 sampleCount4;
  77518. i = 0;
  77519. sampleCount4 = sampleCount >> 2;
  77520. for (i4 = 0; i4 < sampleCount4; i4 += 1) {
  77521. float x0 = src[i+0];
  77522. float x1 = src[i+1];
  77523. float x2 = src[i+2];
  77524. float x3 = src[i+3];
  77525. x0 = ((x0 < -1) ? -1 : ((x0 > 1) ? 1 : x0));
  77526. x1 = ((x1 < -1) ? -1 : ((x1 > 1) ? 1 : x1));
  77527. x2 = ((x2 < -1) ? -1 : ((x2 > 1) ? 1 : x2));
  77528. x3 = ((x3 < -1) ? -1 : ((x3 > 1) ? 1 : x3));
  77529. x0 = x0 * 32767.0f;
  77530. x1 = x1 * 32767.0f;
  77531. x2 = x2 * 32767.0f;
  77532. x3 = x3 * 32767.0f;
  77533. dst[i+0] = (drmp3_int16)x0;
  77534. dst[i+1] = (drmp3_int16)x1;
  77535. dst[i+2] = (drmp3_int16)x2;
  77536. dst[i+3] = (drmp3_int16)x3;
  77537. i += 4;
  77538. }
  77539. for (; i < sampleCount; i += 1) {
  77540. float x = src[i];
  77541. x = ((x < -1) ? -1 : ((x > 1) ? 1 : x));
  77542. x = x * 32767.0f;
  77543. dst[i] = (drmp3_int16)x;
  77544. }
  77545. }
  77546. #endif
  77547. #if !defined(DR_MP3_FLOAT_OUTPUT)
  77548. static void drmp3_s16_to_f32(float* dst, const drmp3_int16* src, drmp3_uint64 sampleCount)
  77549. {
  77550. drmp3_uint64 i;
  77551. for (i = 0; i < sampleCount; i += 1) {
  77552. float x = (float)src[i];
  77553. x = x * 0.000030517578125f;
  77554. dst[i] = x;
  77555. }
  77556. }
  77557. #endif
  77558. static drmp3_uint64 drmp3_read_pcm_frames_raw(drmp3* pMP3, drmp3_uint64 framesToRead, void* pBufferOut)
  77559. {
  77560. drmp3_uint64 totalFramesRead = 0;
  77561. DRMP3_ASSERT(pMP3 != NULL);
  77562. DRMP3_ASSERT(pMP3->onRead != NULL);
  77563. while (framesToRead > 0) {
  77564. drmp3_uint32 framesToConsume = (drmp3_uint32)DRMP3_MIN(pMP3->pcmFramesRemainingInMP3Frame, framesToRead);
  77565. if (pBufferOut != NULL) {
  77566. #if defined(DR_MP3_FLOAT_OUTPUT)
  77567. float* pFramesOutF32 = (float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalFramesRead * pMP3->channels);
  77568. float* pFramesInF32 = (float*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(float) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  77569. DRMP3_COPY_MEMORY(pFramesOutF32, pFramesInF32, sizeof(float) * framesToConsume * pMP3->channels);
  77570. #else
  77571. drmp3_int16* pFramesOutS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalFramesRead * pMP3->channels);
  77572. drmp3_int16* pFramesInS16 = (drmp3_int16*)DRMP3_OFFSET_PTR(&pMP3->pcmFrames[0], sizeof(drmp3_int16) * pMP3->pcmFramesConsumedInMP3Frame * pMP3->mp3FrameChannels);
  77573. DRMP3_COPY_MEMORY(pFramesOutS16, pFramesInS16, sizeof(drmp3_int16) * framesToConsume * pMP3->channels);
  77574. #endif
  77575. }
  77576. pMP3->currentPCMFrame += framesToConsume;
  77577. pMP3->pcmFramesConsumedInMP3Frame += framesToConsume;
  77578. pMP3->pcmFramesRemainingInMP3Frame -= framesToConsume;
  77579. totalFramesRead += framesToConsume;
  77580. framesToRead -= framesToConsume;
  77581. if (framesToRead == 0) {
  77582. break;
  77583. }
  77584. DRMP3_ASSERT(pMP3->pcmFramesRemainingInMP3Frame == 0);
  77585. if (drmp3_decode_next_frame(pMP3) == 0) {
  77586. break;
  77587. }
  77588. }
  77589. return totalFramesRead;
  77590. }
  77591. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_f32(drmp3* pMP3, drmp3_uint64 framesToRead, float* pBufferOut)
  77592. {
  77593. if (pMP3 == NULL || pMP3->onRead == NULL) {
  77594. return 0;
  77595. }
  77596. #if defined(DR_MP3_FLOAT_OUTPUT)
  77597. return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  77598. #else
  77599. {
  77600. drmp3_int16 pTempS16[8192];
  77601. drmp3_uint64 totalPCMFramesRead = 0;
  77602. while (totalPCMFramesRead < framesToRead) {
  77603. drmp3_uint64 framesJustRead;
  77604. drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  77605. drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempS16) / pMP3->channels;
  77606. if (framesToReadNow > framesRemaining) {
  77607. framesToReadNow = framesRemaining;
  77608. }
  77609. framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempS16);
  77610. if (framesJustRead == 0) {
  77611. break;
  77612. }
  77613. drmp3_s16_to_f32((float*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(float) * totalPCMFramesRead * pMP3->channels), pTempS16, framesJustRead * pMP3->channels);
  77614. totalPCMFramesRead += framesJustRead;
  77615. }
  77616. return totalPCMFramesRead;
  77617. }
  77618. #endif
  77619. }
  77620. DRMP3_API drmp3_uint64 drmp3_read_pcm_frames_s16(drmp3* pMP3, drmp3_uint64 framesToRead, drmp3_int16* pBufferOut)
  77621. {
  77622. if (pMP3 == NULL || pMP3->onRead == NULL) {
  77623. return 0;
  77624. }
  77625. #if !defined(DR_MP3_FLOAT_OUTPUT)
  77626. return drmp3_read_pcm_frames_raw(pMP3, framesToRead, pBufferOut);
  77627. #else
  77628. {
  77629. float pTempF32[4096];
  77630. drmp3_uint64 totalPCMFramesRead = 0;
  77631. while (totalPCMFramesRead < framesToRead) {
  77632. drmp3_uint64 framesJustRead;
  77633. drmp3_uint64 framesRemaining = framesToRead - totalPCMFramesRead;
  77634. drmp3_uint64 framesToReadNow = DRMP3_COUNTOF(pTempF32) / pMP3->channels;
  77635. if (framesToReadNow > framesRemaining) {
  77636. framesToReadNow = framesRemaining;
  77637. }
  77638. framesJustRead = drmp3_read_pcm_frames_raw(pMP3, framesToReadNow, pTempF32);
  77639. if (framesJustRead == 0) {
  77640. break;
  77641. }
  77642. drmp3_f32_to_s16((drmp3_int16*)DRMP3_OFFSET_PTR(pBufferOut, sizeof(drmp3_int16) * totalPCMFramesRead * pMP3->channels), pTempF32, framesJustRead * pMP3->channels);
  77643. totalPCMFramesRead += framesJustRead;
  77644. }
  77645. return totalPCMFramesRead;
  77646. }
  77647. #endif
  77648. }
  77649. static void drmp3_reset(drmp3* pMP3)
  77650. {
  77651. DRMP3_ASSERT(pMP3 != NULL);
  77652. pMP3->pcmFramesConsumedInMP3Frame = 0;
  77653. pMP3->pcmFramesRemainingInMP3Frame = 0;
  77654. pMP3->currentPCMFrame = 0;
  77655. pMP3->dataSize = 0;
  77656. pMP3->atEnd = DRMP3_FALSE;
  77657. drmp3dec_init(&pMP3->decoder);
  77658. }
  77659. static drmp3_bool32 drmp3_seek_to_start_of_stream(drmp3* pMP3)
  77660. {
  77661. DRMP3_ASSERT(pMP3 != NULL);
  77662. DRMP3_ASSERT(pMP3->onSeek != NULL);
  77663. if (!drmp3__on_seek(pMP3, 0, drmp3_seek_origin_start)) {
  77664. return DRMP3_FALSE;
  77665. }
  77666. drmp3_reset(pMP3);
  77667. return DRMP3_TRUE;
  77668. }
  77669. static drmp3_bool32 drmp3_seek_forward_by_pcm_frames__brute_force(drmp3* pMP3, drmp3_uint64 frameOffset)
  77670. {
  77671. drmp3_uint64 framesRead;
  77672. #if defined(DR_MP3_FLOAT_OUTPUT)
  77673. framesRead = drmp3_read_pcm_frames_f32(pMP3, frameOffset, NULL);
  77674. #else
  77675. framesRead = drmp3_read_pcm_frames_s16(pMP3, frameOffset, NULL);
  77676. #endif
  77677. if (framesRead != frameOffset) {
  77678. return DRMP3_FALSE;
  77679. }
  77680. return DRMP3_TRUE;
  77681. }
  77682. static drmp3_bool32 drmp3_seek_to_pcm_frame__brute_force(drmp3* pMP3, drmp3_uint64 frameIndex)
  77683. {
  77684. DRMP3_ASSERT(pMP3 != NULL);
  77685. if (frameIndex == pMP3->currentPCMFrame) {
  77686. return DRMP3_TRUE;
  77687. }
  77688. if (frameIndex < pMP3->currentPCMFrame) {
  77689. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  77690. return DRMP3_FALSE;
  77691. }
  77692. }
  77693. DRMP3_ASSERT(frameIndex >= pMP3->currentPCMFrame);
  77694. return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, (frameIndex - pMP3->currentPCMFrame));
  77695. }
  77696. static drmp3_bool32 drmp3_find_closest_seek_point(drmp3* pMP3, drmp3_uint64 frameIndex, drmp3_uint32* pSeekPointIndex)
  77697. {
  77698. drmp3_uint32 iSeekPoint;
  77699. DRMP3_ASSERT(pSeekPointIndex != NULL);
  77700. *pSeekPointIndex = 0;
  77701. if (frameIndex < pMP3->pSeekPoints[0].pcmFrameIndex) {
  77702. return DRMP3_FALSE;
  77703. }
  77704. for (iSeekPoint = 0; iSeekPoint < pMP3->seekPointCount; ++iSeekPoint) {
  77705. if (pMP3->pSeekPoints[iSeekPoint].pcmFrameIndex > frameIndex) {
  77706. break;
  77707. }
  77708. *pSeekPointIndex = iSeekPoint;
  77709. }
  77710. return DRMP3_TRUE;
  77711. }
  77712. static drmp3_bool32 drmp3_seek_to_pcm_frame__seek_table(drmp3* pMP3, drmp3_uint64 frameIndex)
  77713. {
  77714. drmp3_seek_point seekPoint;
  77715. drmp3_uint32 priorSeekPointIndex;
  77716. drmp3_uint16 iMP3Frame;
  77717. drmp3_uint64 leftoverFrames;
  77718. DRMP3_ASSERT(pMP3 != NULL);
  77719. DRMP3_ASSERT(pMP3->pSeekPoints != NULL);
  77720. DRMP3_ASSERT(pMP3->seekPointCount > 0);
  77721. if (drmp3_find_closest_seek_point(pMP3, frameIndex, &priorSeekPointIndex)) {
  77722. seekPoint = pMP3->pSeekPoints[priorSeekPointIndex];
  77723. } else {
  77724. seekPoint.seekPosInBytes = 0;
  77725. seekPoint.pcmFrameIndex = 0;
  77726. seekPoint.mp3FramesToDiscard = 0;
  77727. seekPoint.pcmFramesToDiscard = 0;
  77728. }
  77729. if (!drmp3__on_seek_64(pMP3, seekPoint.seekPosInBytes, drmp3_seek_origin_start)) {
  77730. return DRMP3_FALSE;
  77731. }
  77732. drmp3_reset(pMP3);
  77733. for (iMP3Frame = 0; iMP3Frame < seekPoint.mp3FramesToDiscard; ++iMP3Frame) {
  77734. drmp3_uint32 pcmFramesRead;
  77735. drmp3d_sample_t* pPCMFrames;
  77736. pPCMFrames = NULL;
  77737. if (iMP3Frame == seekPoint.mp3FramesToDiscard-1) {
  77738. pPCMFrames = (drmp3d_sample_t*)pMP3->pcmFrames;
  77739. }
  77740. pcmFramesRead = drmp3_decode_next_frame_ex(pMP3, pPCMFrames);
  77741. if (pcmFramesRead == 0) {
  77742. return DRMP3_FALSE;
  77743. }
  77744. }
  77745. pMP3->currentPCMFrame = seekPoint.pcmFrameIndex - seekPoint.pcmFramesToDiscard;
  77746. leftoverFrames = frameIndex - pMP3->currentPCMFrame;
  77747. return drmp3_seek_forward_by_pcm_frames__brute_force(pMP3, leftoverFrames);
  77748. }
  77749. DRMP3_API drmp3_bool32 drmp3_seek_to_pcm_frame(drmp3* pMP3, drmp3_uint64 frameIndex)
  77750. {
  77751. if (pMP3 == NULL || pMP3->onSeek == NULL) {
  77752. return DRMP3_FALSE;
  77753. }
  77754. if (frameIndex == 0) {
  77755. return drmp3_seek_to_start_of_stream(pMP3);
  77756. }
  77757. if (pMP3->pSeekPoints != NULL && pMP3->seekPointCount > 0) {
  77758. return drmp3_seek_to_pcm_frame__seek_table(pMP3, frameIndex);
  77759. } else {
  77760. return drmp3_seek_to_pcm_frame__brute_force(pMP3, frameIndex);
  77761. }
  77762. }
  77763. DRMP3_API drmp3_bool32 drmp3_get_mp3_and_pcm_frame_count(drmp3* pMP3, drmp3_uint64* pMP3FrameCount, drmp3_uint64* pPCMFrameCount)
  77764. {
  77765. drmp3_uint64 currentPCMFrame;
  77766. drmp3_uint64 totalPCMFrameCount;
  77767. drmp3_uint64 totalMP3FrameCount;
  77768. if (pMP3 == NULL) {
  77769. return DRMP3_FALSE;
  77770. }
  77771. if (pMP3->onSeek == NULL) {
  77772. return DRMP3_FALSE;
  77773. }
  77774. currentPCMFrame = pMP3->currentPCMFrame;
  77775. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  77776. return DRMP3_FALSE;
  77777. }
  77778. totalPCMFrameCount = 0;
  77779. totalMP3FrameCount = 0;
  77780. for (;;) {
  77781. drmp3_uint32 pcmFramesInCurrentMP3Frame;
  77782. pcmFramesInCurrentMP3Frame = drmp3_decode_next_frame_ex(pMP3, NULL);
  77783. if (pcmFramesInCurrentMP3Frame == 0) {
  77784. break;
  77785. }
  77786. totalPCMFrameCount += pcmFramesInCurrentMP3Frame;
  77787. totalMP3FrameCount += 1;
  77788. }
  77789. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  77790. return DRMP3_FALSE;
  77791. }
  77792. if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  77793. return DRMP3_FALSE;
  77794. }
  77795. if (pMP3FrameCount != NULL) {
  77796. *pMP3FrameCount = totalMP3FrameCount;
  77797. }
  77798. if (pPCMFrameCount != NULL) {
  77799. *pPCMFrameCount = totalPCMFrameCount;
  77800. }
  77801. return DRMP3_TRUE;
  77802. }
  77803. DRMP3_API drmp3_uint64 drmp3_get_pcm_frame_count(drmp3* pMP3)
  77804. {
  77805. drmp3_uint64 totalPCMFrameCount;
  77806. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, NULL, &totalPCMFrameCount)) {
  77807. return 0;
  77808. }
  77809. return totalPCMFrameCount;
  77810. }
  77811. DRMP3_API drmp3_uint64 drmp3_get_mp3_frame_count(drmp3* pMP3)
  77812. {
  77813. drmp3_uint64 totalMP3FrameCount;
  77814. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, NULL)) {
  77815. return 0;
  77816. }
  77817. return totalMP3FrameCount;
  77818. }
  77819. static void drmp3__accumulate_running_pcm_frame_count(drmp3* pMP3, drmp3_uint32 pcmFrameCountIn, drmp3_uint64* pRunningPCMFrameCount, float* pRunningPCMFrameCountFractionalPart)
  77820. {
  77821. float srcRatio;
  77822. float pcmFrameCountOutF;
  77823. drmp3_uint32 pcmFrameCountOut;
  77824. srcRatio = (float)pMP3->mp3FrameSampleRate / (float)pMP3->sampleRate;
  77825. DRMP3_ASSERT(srcRatio > 0);
  77826. pcmFrameCountOutF = *pRunningPCMFrameCountFractionalPart + (pcmFrameCountIn / srcRatio);
  77827. pcmFrameCountOut = (drmp3_uint32)pcmFrameCountOutF;
  77828. *pRunningPCMFrameCountFractionalPart = pcmFrameCountOutF - pcmFrameCountOut;
  77829. *pRunningPCMFrameCount += pcmFrameCountOut;
  77830. }
  77831. typedef struct
  77832. {
  77833. drmp3_uint64 bytePos;
  77834. drmp3_uint64 pcmFrameIndex;
  77835. } drmp3__seeking_mp3_frame_info;
  77836. DRMP3_API drmp3_bool32 drmp3_calculate_seek_points(drmp3* pMP3, drmp3_uint32* pSeekPointCount, drmp3_seek_point* pSeekPoints)
  77837. {
  77838. drmp3_uint32 seekPointCount;
  77839. drmp3_uint64 currentPCMFrame;
  77840. drmp3_uint64 totalMP3FrameCount;
  77841. drmp3_uint64 totalPCMFrameCount;
  77842. if (pMP3 == NULL || pSeekPointCount == NULL || pSeekPoints == NULL) {
  77843. return DRMP3_FALSE;
  77844. }
  77845. seekPointCount = *pSeekPointCount;
  77846. if (seekPointCount == 0) {
  77847. return DRMP3_FALSE;
  77848. }
  77849. currentPCMFrame = pMP3->currentPCMFrame;
  77850. if (!drmp3_get_mp3_and_pcm_frame_count(pMP3, &totalMP3FrameCount, &totalPCMFrameCount)) {
  77851. return DRMP3_FALSE;
  77852. }
  77853. if (totalMP3FrameCount < DRMP3_SEEK_LEADING_MP3_FRAMES+1) {
  77854. seekPointCount = 1;
  77855. pSeekPoints[0].seekPosInBytes = 0;
  77856. pSeekPoints[0].pcmFrameIndex = 0;
  77857. pSeekPoints[0].mp3FramesToDiscard = 0;
  77858. pSeekPoints[0].pcmFramesToDiscard = 0;
  77859. } else {
  77860. drmp3_uint64 pcmFramesBetweenSeekPoints;
  77861. drmp3__seeking_mp3_frame_info mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES+1];
  77862. drmp3_uint64 runningPCMFrameCount = 0;
  77863. float runningPCMFrameCountFractionalPart = 0;
  77864. drmp3_uint64 nextTargetPCMFrame;
  77865. drmp3_uint32 iMP3Frame;
  77866. drmp3_uint32 iSeekPoint;
  77867. if (seekPointCount > totalMP3FrameCount-1) {
  77868. seekPointCount = (drmp3_uint32)totalMP3FrameCount-1;
  77869. }
  77870. pcmFramesBetweenSeekPoints = totalPCMFrameCount / (seekPointCount+1);
  77871. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  77872. return DRMP3_FALSE;
  77873. }
  77874. for (iMP3Frame = 0; iMP3Frame < DRMP3_SEEK_LEADING_MP3_FRAMES+1; ++iMP3Frame) {
  77875. drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
  77876. DRMP3_ASSERT(pMP3->streamCursor >= pMP3->dataSize);
  77877. mp3FrameInfo[iMP3Frame].bytePos = pMP3->streamCursor - pMP3->dataSize;
  77878. mp3FrameInfo[iMP3Frame].pcmFrameIndex = runningPCMFrameCount;
  77879. pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
  77880. if (pcmFramesInCurrentMP3FrameIn == 0) {
  77881. return DRMP3_FALSE;
  77882. }
  77883. drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  77884. }
  77885. nextTargetPCMFrame = 0;
  77886. for (iSeekPoint = 0; iSeekPoint < seekPointCount; ++iSeekPoint) {
  77887. nextTargetPCMFrame += pcmFramesBetweenSeekPoints;
  77888. for (;;) {
  77889. if (nextTargetPCMFrame < runningPCMFrameCount) {
  77890. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  77891. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  77892. pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
  77893. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  77894. break;
  77895. } else {
  77896. size_t i;
  77897. drmp3_uint32 pcmFramesInCurrentMP3FrameIn;
  77898. for (i = 0; i < DRMP3_COUNTOF(mp3FrameInfo)-1; ++i) {
  77899. mp3FrameInfo[i] = mp3FrameInfo[i+1];
  77900. }
  77901. mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].bytePos = pMP3->streamCursor - pMP3->dataSize;
  77902. mp3FrameInfo[DRMP3_COUNTOF(mp3FrameInfo)-1].pcmFrameIndex = runningPCMFrameCount;
  77903. pcmFramesInCurrentMP3FrameIn = drmp3_decode_next_frame_ex(pMP3, NULL);
  77904. if (pcmFramesInCurrentMP3FrameIn == 0) {
  77905. pSeekPoints[iSeekPoint].seekPosInBytes = mp3FrameInfo[0].bytePos;
  77906. pSeekPoints[iSeekPoint].pcmFrameIndex = nextTargetPCMFrame;
  77907. pSeekPoints[iSeekPoint].mp3FramesToDiscard = DRMP3_SEEK_LEADING_MP3_FRAMES;
  77908. pSeekPoints[iSeekPoint].pcmFramesToDiscard = (drmp3_uint16)(nextTargetPCMFrame - mp3FrameInfo[DRMP3_SEEK_LEADING_MP3_FRAMES-1].pcmFrameIndex);
  77909. break;
  77910. }
  77911. drmp3__accumulate_running_pcm_frame_count(pMP3, pcmFramesInCurrentMP3FrameIn, &runningPCMFrameCount, &runningPCMFrameCountFractionalPart);
  77912. }
  77913. }
  77914. }
  77915. if (!drmp3_seek_to_start_of_stream(pMP3)) {
  77916. return DRMP3_FALSE;
  77917. }
  77918. if (!drmp3_seek_to_pcm_frame(pMP3, currentPCMFrame)) {
  77919. return DRMP3_FALSE;
  77920. }
  77921. }
  77922. *pSeekPointCount = seekPointCount;
  77923. return DRMP3_TRUE;
  77924. }
  77925. DRMP3_API drmp3_bool32 drmp3_bind_seek_table(drmp3* pMP3, drmp3_uint32 seekPointCount, drmp3_seek_point* pSeekPoints)
  77926. {
  77927. if (pMP3 == NULL) {
  77928. return DRMP3_FALSE;
  77929. }
  77930. if (seekPointCount == 0 || pSeekPoints == NULL) {
  77931. pMP3->seekPointCount = 0;
  77932. pMP3->pSeekPoints = NULL;
  77933. } else {
  77934. pMP3->seekPointCount = seekPointCount;
  77935. pMP3->pSeekPoints = pSeekPoints;
  77936. }
  77937. return DRMP3_TRUE;
  77938. }
  77939. static float* drmp3__full_read_and_close_f32(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
  77940. {
  77941. drmp3_uint64 totalFramesRead = 0;
  77942. drmp3_uint64 framesCapacity = 0;
  77943. float* pFrames = NULL;
  77944. float temp[4096];
  77945. DRMP3_ASSERT(pMP3 != NULL);
  77946. for (;;) {
  77947. drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
  77948. drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_f32(pMP3, framesToReadRightNow, temp);
  77949. if (framesJustRead == 0) {
  77950. break;
  77951. }
  77952. if (framesCapacity < totalFramesRead + framesJustRead) {
  77953. drmp3_uint64 oldFramesBufferSize;
  77954. drmp3_uint64 newFramesBufferSize;
  77955. drmp3_uint64 newFramesCap;
  77956. float* pNewFrames;
  77957. newFramesCap = framesCapacity * 2;
  77958. if (newFramesCap < totalFramesRead + framesJustRead) {
  77959. newFramesCap = totalFramesRead + framesJustRead;
  77960. }
  77961. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(float);
  77962. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(float);
  77963. if (newFramesBufferSize > (drmp3_uint64)DRMP3_SIZE_MAX) {
  77964. break;
  77965. }
  77966. pNewFrames = (float*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  77967. if (pNewFrames == NULL) {
  77968. drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  77969. break;
  77970. }
  77971. pFrames = pNewFrames;
  77972. framesCapacity = newFramesCap;
  77973. }
  77974. DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(float)));
  77975. totalFramesRead += framesJustRead;
  77976. if (framesJustRead != framesToReadRightNow) {
  77977. break;
  77978. }
  77979. }
  77980. if (pConfig != NULL) {
  77981. pConfig->channels = pMP3->channels;
  77982. pConfig->sampleRate = pMP3->sampleRate;
  77983. }
  77984. drmp3_uninit(pMP3);
  77985. if (pTotalFrameCount) {
  77986. *pTotalFrameCount = totalFramesRead;
  77987. }
  77988. return pFrames;
  77989. }
  77990. static drmp3_int16* drmp3__full_read_and_close_s16(drmp3* pMP3, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount)
  77991. {
  77992. drmp3_uint64 totalFramesRead = 0;
  77993. drmp3_uint64 framesCapacity = 0;
  77994. drmp3_int16* pFrames = NULL;
  77995. drmp3_int16 temp[4096];
  77996. DRMP3_ASSERT(pMP3 != NULL);
  77997. for (;;) {
  77998. drmp3_uint64 framesToReadRightNow = DRMP3_COUNTOF(temp) / pMP3->channels;
  77999. drmp3_uint64 framesJustRead = drmp3_read_pcm_frames_s16(pMP3, framesToReadRightNow, temp);
  78000. if (framesJustRead == 0) {
  78001. break;
  78002. }
  78003. if (framesCapacity < totalFramesRead + framesJustRead) {
  78004. drmp3_uint64 newFramesBufferSize;
  78005. drmp3_uint64 oldFramesBufferSize;
  78006. drmp3_uint64 newFramesCap;
  78007. drmp3_int16* pNewFrames;
  78008. newFramesCap = framesCapacity * 2;
  78009. if (newFramesCap < totalFramesRead + framesJustRead) {
  78010. newFramesCap = totalFramesRead + framesJustRead;
  78011. }
  78012. oldFramesBufferSize = framesCapacity * pMP3->channels * sizeof(drmp3_int16);
  78013. newFramesBufferSize = newFramesCap * pMP3->channels * sizeof(drmp3_int16);
  78014. if (newFramesBufferSize > (drmp3_uint64)DRMP3_SIZE_MAX) {
  78015. break;
  78016. }
  78017. pNewFrames = (drmp3_int16*)drmp3__realloc_from_callbacks(pFrames, (size_t)newFramesBufferSize, (size_t)oldFramesBufferSize, &pMP3->allocationCallbacks);
  78018. if (pNewFrames == NULL) {
  78019. drmp3__free_from_callbacks(pFrames, &pMP3->allocationCallbacks);
  78020. break;
  78021. }
  78022. pFrames = pNewFrames;
  78023. framesCapacity = newFramesCap;
  78024. }
  78025. DRMP3_COPY_MEMORY(pFrames + totalFramesRead*pMP3->channels, temp, (size_t)(framesJustRead*pMP3->channels*sizeof(drmp3_int16)));
  78026. totalFramesRead += framesJustRead;
  78027. if (framesJustRead != framesToReadRightNow) {
  78028. break;
  78029. }
  78030. }
  78031. if (pConfig != NULL) {
  78032. pConfig->channels = pMP3->channels;
  78033. pConfig->sampleRate = pMP3->sampleRate;
  78034. }
  78035. drmp3_uninit(pMP3);
  78036. if (pTotalFrameCount) {
  78037. *pTotalFrameCount = totalFramesRead;
  78038. }
  78039. return pFrames;
  78040. }
  78041. DRMP3_API float* drmp3_open_and_read_pcm_frames_f32(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78042. {
  78043. drmp3 mp3;
  78044. if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  78045. return NULL;
  78046. }
  78047. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78048. }
  78049. DRMP3_API drmp3_int16* drmp3_open_and_read_pcm_frames_s16(drmp3_read_proc onRead, drmp3_seek_proc onSeek, void* pUserData, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78050. {
  78051. drmp3 mp3;
  78052. if (!drmp3_init(&mp3, onRead, onSeek, pUserData, pAllocationCallbacks)) {
  78053. return NULL;
  78054. }
  78055. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78056. }
  78057. DRMP3_API float* drmp3_open_memory_and_read_pcm_frames_f32(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78058. {
  78059. drmp3 mp3;
  78060. if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  78061. return NULL;
  78062. }
  78063. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78064. }
  78065. DRMP3_API drmp3_int16* drmp3_open_memory_and_read_pcm_frames_s16(const void* pData, size_t dataSize, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78066. {
  78067. drmp3 mp3;
  78068. if (!drmp3_init_memory(&mp3, pData, dataSize, pAllocationCallbacks)) {
  78069. return NULL;
  78070. }
  78071. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78072. }
  78073. #ifndef DR_MP3_NO_STDIO
  78074. DRMP3_API float* drmp3_open_file_and_read_pcm_frames_f32(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78075. {
  78076. drmp3 mp3;
  78077. if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  78078. return NULL;
  78079. }
  78080. return drmp3__full_read_and_close_f32(&mp3, pConfig, pTotalFrameCount);
  78081. }
  78082. DRMP3_API drmp3_int16* drmp3_open_file_and_read_pcm_frames_s16(const char* filePath, drmp3_config* pConfig, drmp3_uint64* pTotalFrameCount, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78083. {
  78084. drmp3 mp3;
  78085. if (!drmp3_init_file(&mp3, filePath, pAllocationCallbacks)) {
  78086. return NULL;
  78087. }
  78088. return drmp3__full_read_and_close_s16(&mp3, pConfig, pTotalFrameCount);
  78089. }
  78090. #endif
  78091. DRMP3_API void* drmp3_malloc(size_t sz, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78092. {
  78093. if (pAllocationCallbacks != NULL) {
  78094. return drmp3__malloc_from_callbacks(sz, pAllocationCallbacks);
  78095. } else {
  78096. return drmp3__malloc_default(sz, NULL);
  78097. }
  78098. }
  78099. DRMP3_API void drmp3_free(void* p, const drmp3_allocation_callbacks* pAllocationCallbacks)
  78100. {
  78101. if (pAllocationCallbacks != NULL) {
  78102. drmp3__free_from_callbacks(p, pAllocationCallbacks);
  78103. } else {
  78104. drmp3__free_default(p, NULL);
  78105. }
  78106. }
  78107. #endif
  78108. /* dr_mp3_c end */
  78109. #endif /* DRMP3_IMPLEMENTATION */
  78110. #endif /* MA_NO_MP3 */
  78111. /* End globally disabled warnings. */
  78112. #if defined(_MSC_VER)
  78113. #pragma warning(pop)
  78114. #endif
  78115. #endif /* miniaudio_c */
  78116. #endif /* MINIAUDIO_IMPLEMENTATION */
  78117. /*
  78118. This software is available as a choice of the following licenses. Choose
  78119. whichever you prefer.
  78120. ===============================================================================
  78121. ALTERNATIVE 1 - Public Domain (www.unlicense.org)
  78122. ===============================================================================
  78123. This is free and unencumbered software released into the public domain.
  78124. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this
  78125. software, either in source code form or as a compiled binary, for any purpose,
  78126. commercial or non-commercial, and by any means.
  78127. In jurisdictions that recognize copyright laws, the author or authors of this
  78128. software dedicate any and all copyright interest in the software to the public
  78129. domain. We make this dedication for the benefit of the public at large and to
  78130. the detriment of our heirs and successors. We intend this dedication to be an
  78131. overt act of relinquishment in perpetuity of all present and future rights to
  78132. this software under copyright law.
  78133. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  78134. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  78135. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  78136. AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  78137. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  78138. WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  78139. For more information, please refer to <http://unlicense.org/>
  78140. ===============================================================================
  78141. ALTERNATIVE 2 - MIT No Attribution
  78142. ===============================================================================
  78143. Copyright 2020 David Reid
  78144. Permission is hereby granted, free of charge, to any person obtaining a copy of
  78145. this software and associated documentation files (the "Software"), to deal in
  78146. the Software without restriction, including without limitation the rights to
  78147. use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  78148. of the Software, and to permit persons to whom the Software is furnished to do
  78149. so.
  78150. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  78151. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  78152. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  78153. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  78154. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  78155. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  78156. SOFTWARE.
  78157. */