stb-vorbis.c 165 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066
  1. // Ogg Vorbis audio decoder - v1.09 - public domain
  2. // http://nothings.org/stb_vorbis/
  3. //
  4. // Original version written by Sean Barrett in 2007.
  5. //
  6. // Originally sponsored by RAD Game Tools. Seeking sponsored
  7. // by Phillip Bennefall, Marc Andersen, Aaron Baker, Elias Software,
  8. // Aras Pranckevicius, and Sean Barrett.
  9. //
  10. // LICENSE
  11. //
  12. // This software is dual-licensed to the public domain and under the following
  13. // license: you are granted a perpetual, irrevocable license to copy, modify,
  14. // publish, and distribute this file as you see fit.
  15. //
  16. // No warranty for any purpose is expressed or implied by the author (nor
  17. // by RAD Game Tools). Report bugs and send enhancements to the author.
  18. //
  19. // Limitations:
  20. //
  21. // - floor 0 not supported (used in old ogg vorbis files pre-2004)
  22. // - lossless sample-truncation at beginning ignored
  23. // - cannot concatenate multiple vorbis streams
  24. // - sample positions are 32-bit, limiting seekable 192Khz
  25. // files to around 6 hours (Ogg supports 64-bit)
  26. //
  27. // Feature contributors:
  28. // Dougall Johnson (sample-exact seeking)
  29. //
  30. // Bugfix/warning contributors:
  31. // Terje Mathisen Niklas Frykholm Andy Hill
  32. // Casey Muratori John Bolton Gargaj
  33. // Laurent Gomila Marc LeBlanc Ronny Chevalier
  34. // Bernhard Wodo Evan Balster alxprd@github
  35. // Tom Beaumont Ingo Leitgeb Nicolas Guillemot
  36. // Phillip Bennefall Rohit Thiago Goulart
  37. // manxorist@github saga musix
  38. //
  39. // Partial history:
  40. // 1.09 - 2016/04/04 - back out 'truncation of last frame' fix from previous version
  41. // 1.08 - 2016/04/02 - warnings; setup memory leaks; truncation of last frame
  42. // 1.07 - 2015/01/16 - fixes for crashes on invalid files; warning fixes; const
  43. // 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
  44. // some crash fixes when out of memory or with corrupt files
  45. // fix some inappropriately signed shifts
  46. // 1.05 - 2015/04/19 - don't define __forceinline if it's redundant
  47. // 1.04 - 2014/08/27 - fix missing const-correct case in API
  48. // 1.03 - 2014/08/07 - warning fixes
  49. // 1.02 - 2014/07/09 - declare qsort comparison as explicitly _cdecl in Windows
  50. // 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float (interleaved was correct)
  51. // 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in >2-channel;
  52. // (API change) report sample rate for decode-full-file funcs
  53. //
  54. // See end of file for full version history.
  55. #include "stb-vorbis.h"
  56. #ifndef STB_VORBIS_HEADER_ONLY
  57. // global configuration settings (e.g. set these in the project/makefile),
  58. // or just set them in this file at the top (although ideally the first few
  59. // should be visible when the header file is compiled too, although it's not
  60. // crucial)
  61. // STB_VORBIS_NO_PUSHDATA_API
  62. // does not compile the code for the various stb_vorbis_*_pushdata()
  63. // functions
  64. // #define STB_VORBIS_NO_PUSHDATA_API
  65. // STB_VORBIS_NO_PULLDATA_API
  66. // does not compile the code for the non-pushdata APIs
  67. // #define STB_VORBIS_NO_PULLDATA_API
  68. // STB_VORBIS_NO_STDIO
  69. // does not compile the code for the APIs that use FILE *s internally
  70. // or externally (implied by STB_VORBIS_NO_PULLDATA_API)
  71. // #define STB_VORBIS_NO_STDIO
  72. // STB_VORBIS_NO_INTEGER_CONVERSION
  73. // does not compile the code for converting audio sample data from
  74. // float to integer (implied by STB_VORBIS_NO_PULLDATA_API)
  75. // #define STB_VORBIS_NO_INTEGER_CONVERSION
  76. // STB_VORBIS_NO_FAST_SCALED_FLOAT
  77. // does not use a fast float-to-int trick to accelerate float-to-int on
  78. // most platforms which requires endianness be defined correctly.
  79. //#define STB_VORBIS_NO_FAST_SCALED_FLOAT
  80. // STB_VORBIS_MAX_CHANNELS [number]
  81. // globally define this to the maximum number of channels you need.
  82. // The spec does not put a restriction on channels except that
  83. // the count is stored in a byte, so 255 is the hard limit.
  84. // Reducing this saves about 16 bytes per value, so using 16 saves
  85. // (255-16)*16 or around 4KB. Plus anything other memory usage
  86. // I forgot to account for. Can probably go as low as 8 (7.1 audio),
  87. // 6 (5.1 audio), or 2 (stereo only).
  88. #ifndef STB_VORBIS_MAX_CHANNELS
  89. #define STB_VORBIS_MAX_CHANNELS 16 // enough for anyone?
  90. #endif
  91. // STB_VORBIS_PUSHDATA_CRC_COUNT [number]
  92. // after a flush_pushdata(), stb_vorbis begins scanning for the
  93. // next valid page, without backtracking. when it finds something
  94. // that looks like a page, it streams through it and verifies its
  95. // CRC32. Should that validation fail, it keeps scanning. But it's
  96. // possible that _while_ streaming through to check the CRC32 of
  97. // one candidate page, it sees another candidate page. This #define
  98. // determines how many "overlapping" candidate pages it can search
  99. // at once. Note that "real" pages are typically ~4KB to ~8KB, whereas
  100. // garbage pages could be as big as 64KB, but probably average ~16KB.
  101. // So don't hose ourselves by scanning an apparent 64KB page and
  102. // missing a ton of real ones in the interim; so minimum of 2
  103. #ifndef STB_VORBIS_PUSHDATA_CRC_COUNT
  104. #define STB_VORBIS_PUSHDATA_CRC_COUNT 4
  105. #endif
  106. // STB_VORBIS_FAST_HUFFMAN_LENGTH [number]
  107. // sets the log size of the huffman-acceleration table. Maximum
  108. // supported value is 24. with larger numbers, more decodings are O(1),
  109. // but the table size is larger so worse cache missing, so you'll have
  110. // to probe (and try multiple ogg vorbis files) to find the sweet spot.
  111. #ifndef STB_VORBIS_FAST_HUFFMAN_LENGTH
  112. #define STB_VORBIS_FAST_HUFFMAN_LENGTH 10
  113. #endif
  114. // STB_VORBIS_FAST_BINARY_LENGTH [number]
  115. // sets the log size of the binary-search acceleration table. this
  116. // is used in similar fashion to the fast-huffman size to set initial
  117. // parameters for the binary search
  118. // STB_VORBIS_FAST_HUFFMAN_INT
  119. // The fast huffman tables are much more efficient if they can be
  120. // stored as 16-bit results instead of 32-bit results. This restricts
  121. // the codebooks to having only 65535 possible outcomes, though.
  122. // (At least, accelerated by the huffman table.)
  123. #ifndef STB_VORBIS_FAST_HUFFMAN_INT
  124. #define STB_VORBIS_FAST_HUFFMAN_SHORT
  125. #endif
  126. // STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  127. // If the 'fast huffman' search doesn't succeed, then stb_vorbis falls
  128. // back on binary searching for the correct one. This requires storing
  129. // extra tables with the huffman codes in sorted order. Defining this
  130. // symbol trades off space for speed by forcing a linear search in the
  131. // non-fast case, except for "sparse" codebooks.
  132. // #define STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  133. // STB_VORBIS_DIVIDES_IN_RESIDUE
  134. // stb_vorbis precomputes the result of the scalar residue decoding
  135. // that would otherwise require a divide per chunk. you can trade off
  136. // space for time by defining this symbol.
  137. // #define STB_VORBIS_DIVIDES_IN_RESIDUE
  138. // STB_VORBIS_DIVIDES_IN_CODEBOOK
  139. // vorbis VQ codebooks can be encoded two ways: with every case explicitly
  140. // stored, or with all elements being chosen from a small range of values,
  141. // and all values possible in all elements. By default, stb_vorbis expands
  142. // this latter kind out to look like the former kind for ease of decoding,
  143. // because otherwise an integer divide-per-vector-element is required to
  144. // unpack the index. If you define STB_VORBIS_DIVIDES_IN_CODEBOOK, you can
  145. // trade off storage for speed.
  146. //#define STB_VORBIS_DIVIDES_IN_CODEBOOK
  147. #ifdef STB_VORBIS_CODEBOOK_SHORTS
  148. #error "STB_VORBIS_CODEBOOK_SHORTS is no longer supported as it produced incorrect results for some input formats"
  149. #endif
  150. // STB_VORBIS_DIVIDE_TABLE
  151. // this replaces small integer divides in the floor decode loop with
  152. // table lookups. made less than 1% difference, so disabled by default.
  153. // STB_VORBIS_NO_INLINE_DECODE
  154. // disables the inlining of the scalar codebook fast-huffman decode.
  155. // might save a little codespace; useful for debugging
  156. // #define STB_VORBIS_NO_INLINE_DECODE
  157. // STB_VORBIS_NO_DEFER_FLOOR
  158. // Normally we only decode the floor without synthesizing the actual
  159. // full curve. We can instead synthesize the curve immediately. This
  160. // requires more memory and is very likely slower, so I don't think
  161. // you'd ever want to do it except for debugging.
  162. // #define STB_VORBIS_NO_DEFER_FLOOR
  163. //////////////////////////////////////////////////////////////////////////////
  164. #ifdef STB_VORBIS_NO_PULLDATA_API
  165. #define STB_VORBIS_NO_INTEGER_CONVERSION
  166. #define STB_VORBIS_NO_STDIO
  167. #endif
  168. #if defined(STB_VORBIS_NO_CRT) && !defined(STB_VORBIS_NO_STDIO)
  169. #define STB_VORBIS_NO_STDIO 1
  170. #endif
  171. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  172. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  173. // only need endianness for fast-float-to-int, which we don't
  174. // use for pushdata
  175. #ifndef STB_VORBIS_BIG_ENDIAN
  176. #define STB_VORBIS_ENDIAN 0
  177. #else
  178. #define STB_VORBIS_ENDIAN 1
  179. #endif
  180. #endif
  181. #endif
  182. #ifndef STB_VORBIS_NO_STDIO
  183. #include <stdio.h>
  184. #endif
  185. #ifndef STB_VORBIS_NO_CRT
  186. #include <stdlib.h>
  187. #include <string.h>
  188. #include <assert.h>
  189. #include <math.h>
  190. #if !(defined(__APPLE__) || defined(MACOSX) || defined(macintosh) || defined(Macintosh))
  191. #include <malloc.h>
  192. #if defined(__linux__) || defined(__linux) || defined(__EMSCRIPTEN__)
  193. #include <alloca.h>
  194. #endif
  195. #endif
  196. #else // STB_VORBIS_NO_CRT
  197. #define NULL 0
  198. #define malloc(s) 0
  199. #define free(s) ((void) 0)
  200. #define realloc(s) 0
  201. #endif // STB_VORBIS_NO_CRT
  202. #include <limits.h>
  203. #ifdef __MINGW32__
  204. // eff you mingw:
  205. // "fixed":
  206. // http://sourceforge.net/p/mingw-w64/mailman/message/32882927/
  207. // "no that broke the build, reverted, who cares about C":
  208. // http://sourceforge.net/p/mingw-w64/mailman/message/32890381/
  209. #ifdef __forceinline
  210. #undef __forceinline
  211. #endif
  212. #define __forceinline
  213. #elif !defined(_MSC_VER)
  214. #if __GNUC__
  215. #define __forceinline inline
  216. #else
  217. #define __forceinline
  218. #endif
  219. #endif
  220. #if STB_VORBIS_MAX_CHANNELS > 256
  221. #error "Value of STB_VORBIS_MAX_CHANNELS outside of allowed range"
  222. #endif
  223. #if STB_VORBIS_FAST_HUFFMAN_LENGTH > 24
  224. #error "Value of STB_VORBIS_FAST_HUFFMAN_LENGTH outside of allowed range"
  225. #endif
  226. #if 0
  227. #include <crtdbg.h>
  228. #define CHECK(f) _CrtIsValidHeapPointer(f->channel_buffers[1])
  229. #else
  230. #define CHECK(f) ((void) 0)
  231. #endif
  232. #define MAX_BLOCKSIZE_LOG 13 // from specification
  233. #define MAX_BLOCKSIZE (1 << MAX_BLOCKSIZE_LOG)
  234. typedef unsigned char uint8;
  235. typedef signed char int8;
  236. typedef unsigned short uint16;
  237. typedef signed short int16;
  238. typedef unsigned int uint32;
  239. typedef signed int int32;
  240. #ifndef TRUE
  241. #define TRUE 1
  242. #define FALSE 0
  243. #endif
  244. typedef float codetype;
  245. // @NOTE
  246. //
  247. // Some arrays below are tagged "//varies", which means it's actually
  248. // a variable-sized piece of data, but rather than malloc I assume it's
  249. // small enough it's better to just allocate it all together with the
  250. // main thing
  251. //
  252. // Most of the variables are specified with the smallest size I could pack
  253. // them into. It might give better performance to make them all full-sized
  254. // integers. It should be safe to freely rearrange the structures or change
  255. // the sizes larger--nothing relies on silently truncating etc., nor the
  256. // order of variables.
  257. #define FAST_HUFFMAN_TABLE_SIZE (1 << STB_VORBIS_FAST_HUFFMAN_LENGTH)
  258. #define FAST_HUFFMAN_TABLE_MASK (FAST_HUFFMAN_TABLE_SIZE - 1)
  259. typedef struct
  260. {
  261. int dimensions, entries;
  262. uint8 *codeword_lengths;
  263. float minimum_value;
  264. float delta_value;
  265. uint8 value_bits;
  266. uint8 lookup_type;
  267. uint8 sequence_p;
  268. uint8 sparse;
  269. uint32 lookup_values;
  270. codetype *multiplicands;
  271. uint32 *codewords;
  272. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  273. int16 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  274. #else
  275. int32 fast_huffman[FAST_HUFFMAN_TABLE_SIZE];
  276. #endif
  277. uint32 *sorted_codewords;
  278. int *sorted_values;
  279. int sorted_entries;
  280. } Codebook;
  281. typedef struct
  282. {
  283. uint8 order;
  284. uint16 rate;
  285. uint16 bark_map_size;
  286. uint8 amplitude_bits;
  287. uint8 amplitude_offset;
  288. uint8 number_of_books;
  289. uint8 book_list[16]; // varies
  290. } Floor0;
  291. typedef struct
  292. {
  293. uint8 partitions;
  294. uint8 partition_class_list[32]; // varies
  295. uint8 class_dimensions[16]; // varies
  296. uint8 class_subclasses[16]; // varies
  297. uint8 class_masterbooks[16]; // varies
  298. int16 subclass_books[16][8]; // varies
  299. uint16 Xlist[31*8+2]; // varies
  300. uint8 sorted_order[31*8+2];
  301. uint8 neighbors[31*8+2][2];
  302. uint8 floor1_multiplier;
  303. uint8 rangebits;
  304. int values;
  305. } Floor1;
  306. typedef union
  307. {
  308. Floor0 floor0;
  309. Floor1 floor1;
  310. } Floor;
  311. typedef struct
  312. {
  313. uint32 begin, end;
  314. uint32 part_size;
  315. uint8 classifications;
  316. uint8 classbook;
  317. uint8 **classdata;
  318. int16 (*residue_books)[8];
  319. } Residue;
  320. typedef struct
  321. {
  322. uint8 magnitude;
  323. uint8 angle;
  324. uint8 mux;
  325. } MappingChannel;
  326. typedef struct
  327. {
  328. uint16 coupling_steps;
  329. MappingChannel *chan;
  330. uint8 submaps;
  331. uint8 submap_floor[15]; // varies
  332. uint8 submap_residue[15]; // varies
  333. } Mapping;
  334. typedef struct
  335. {
  336. uint8 blockflag;
  337. uint8 mapping;
  338. uint16 windowtype;
  339. uint16 transformtype;
  340. } Mode;
  341. typedef struct
  342. {
  343. uint32 goal_crc; // expected crc if match
  344. int bytes_left; // bytes left in packet
  345. uint32 crc_so_far; // running crc
  346. int bytes_done; // bytes processed in _current_ chunk
  347. uint32 sample_loc; // granule pos encoded in page
  348. } CRCscan;
  349. typedef struct
  350. {
  351. uint32 page_start, page_end;
  352. uint32 last_decoded_sample;
  353. } ProbedPage;
  354. struct stb_vorbis
  355. {
  356. // user-accessible info
  357. unsigned int sample_rate;
  358. int channels;
  359. unsigned int setup_memory_required;
  360. unsigned int temp_memory_required;
  361. unsigned int setup_temp_memory_required;
  362. // input config
  363. #ifndef STB_VORBIS_NO_STDIO
  364. FILE *f;
  365. uint32 f_start;
  366. int close_on_free;
  367. #endif
  368. uint8 *stream;
  369. uint8 *stream_start;
  370. uint8 *stream_end;
  371. uint32 stream_len;
  372. uint8 push_mode;
  373. uint32 first_audio_page_offset;
  374. ProbedPage p_first, p_last;
  375. // memory management
  376. stb_vorbis_alloc alloc;
  377. int setup_offset;
  378. int temp_offset;
  379. // run-time results
  380. int eof;
  381. enum STBVorbisError error;
  382. // user-useful data
  383. // header info
  384. int blocksize[2];
  385. int blocksize_0, blocksize_1;
  386. int codebook_count;
  387. Codebook *codebooks;
  388. int floor_count;
  389. uint16 floor_types[64]; // varies
  390. Floor *floor_config;
  391. int residue_count;
  392. uint16 residue_types[64]; // varies
  393. Residue *residue_config;
  394. int mapping_count;
  395. Mapping *mapping;
  396. int mode_count;
  397. Mode mode_config[64]; // varies
  398. uint32 total_samples;
  399. // decode buffer
  400. float *channel_buffers[STB_VORBIS_MAX_CHANNELS];
  401. float *outputs [STB_VORBIS_MAX_CHANNELS];
  402. float *previous_window[STB_VORBIS_MAX_CHANNELS];
  403. int previous_length;
  404. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  405. int16 *finalY[STB_VORBIS_MAX_CHANNELS];
  406. #else
  407. float *floor_buffers[STB_VORBIS_MAX_CHANNELS];
  408. #endif
  409. uint32 current_loc; // sample location of next frame to decode
  410. int current_loc_valid;
  411. // per-blocksize precomputed data
  412. // twiddle factors
  413. float *A[2],*B[2],*C[2];
  414. float *window[2];
  415. uint16 *bit_reverse[2];
  416. // current page/packet/segment streaming info
  417. uint32 serial; // stream serial number for verification
  418. int last_page;
  419. int segment_count;
  420. uint8 segments[255];
  421. uint8 page_flag;
  422. uint8 bytes_in_seg;
  423. uint8 first_decode;
  424. int next_seg;
  425. int last_seg; // flag that we're on the last segment
  426. int last_seg_which; // what was the segment number of the last seg?
  427. uint32 acc;
  428. int valid_bits;
  429. int packet_bytes;
  430. int end_seg_with_known_loc;
  431. uint32 known_loc_for_packet;
  432. int discard_samples_deferred;
  433. uint32 samples_output;
  434. // push mode scanning
  435. int page_crc_tests; // only in push_mode: number of tests active; -1 if not searching
  436. #ifndef STB_VORBIS_NO_PUSHDATA_API
  437. CRCscan scan[STB_VORBIS_PUSHDATA_CRC_COUNT];
  438. #endif
  439. // sample-access
  440. int channel_buffer_start;
  441. int channel_buffer_end;
  442. };
  443. #if defined(STB_VORBIS_NO_PUSHDATA_API)
  444. #define IS_PUSH_MODE(f) FALSE
  445. #elif defined(STB_VORBIS_NO_PULLDATA_API)
  446. #define IS_PUSH_MODE(f) TRUE
  447. #else
  448. #define IS_PUSH_MODE(f) ((f)->push_mode)
  449. #endif
  450. typedef struct stb_vorbis vorb;
  451. static int error(vorb *f, enum STBVorbisError e)
  452. {
  453. f->error = e;
  454. if (!f->eof && e != VORBIS_need_more_data) {
  455. f->error=e; // breakpoint for debugging
  456. }
  457. return 0;
  458. }
  459. // these functions are used for allocating temporary memory
  460. // while decoding. if you can afford the stack space, use
  461. // alloca(); otherwise, provide a temp buffer and it will
  462. // allocate out of those.
  463. #define array_size_required(count,size) (count*(sizeof(void *)+(size)))
  464. #define temp_alloc(f,size) (f->alloc.alloc_buffer ? setup_temp_malloc(f,size) : alloca(size))
  465. #ifdef dealloca
  466. #define temp_free(f,p) (f->alloc.alloc_buffer ? 0 : dealloca(size))
  467. #else
  468. #define temp_free(f,p) 0
  469. #endif
  470. #define temp_alloc_save(f) ((f)->temp_offset)
  471. #define temp_alloc_restore(f,p) ((f)->temp_offset = (p))
  472. #define temp_block_array(f,count,size) make_block_array(temp_alloc(f,array_size_required(count,size)), count, size)
  473. // given a sufficiently large block of memory, make an array of pointers to subblocks of it
  474. static void *make_block_array(void *mem, int count, int size)
  475. {
  476. int i;
  477. void ** p = (void **) mem;
  478. char *q = (char *) (p + count);
  479. for (i=0; i < count; ++i) {
  480. p[i] = q;
  481. q += size;
  482. }
  483. return p;
  484. }
  485. static void *setup_malloc(vorb *f, int sz)
  486. {
  487. sz = (sz+3) & ~3;
  488. f->setup_memory_required += sz;
  489. if (f->alloc.alloc_buffer) {
  490. void *p = (char *) f->alloc.alloc_buffer + f->setup_offset;
  491. if (f->setup_offset + sz > f->temp_offset) return NULL;
  492. f->setup_offset += sz;
  493. return p;
  494. }
  495. return sz ? malloc(sz) : NULL;
  496. }
  497. static void setup_free(vorb *f, void *p)
  498. {
  499. if (f->alloc.alloc_buffer) return; // do nothing; setup mem is a stack
  500. free(p);
  501. }
  502. static void *setup_temp_malloc(vorb *f, int sz)
  503. {
  504. sz = (sz+3) & ~3;
  505. if (f->alloc.alloc_buffer) {
  506. if (f->temp_offset - sz < f->setup_offset) return NULL;
  507. f->temp_offset -= sz;
  508. return (char *) f->alloc.alloc_buffer + f->temp_offset;
  509. }
  510. return malloc(sz);
  511. }
  512. static void setup_temp_free(vorb *f, void *p, int sz)
  513. {
  514. if (f->alloc.alloc_buffer) {
  515. f->temp_offset += (sz+3)&~3;
  516. return;
  517. }
  518. free(p);
  519. }
  520. #define CRC32_POLY 0x04c11db7 // from spec
  521. static uint32 crc_table[256];
  522. static void crc32_init(void)
  523. {
  524. int i,j;
  525. uint32 s;
  526. for(i=0; i < 256; i++) {
  527. for (s=(uint32) i << 24, j=0; j < 8; ++j)
  528. s = (s << 1) ^ (s >= (1U<<31) ? CRC32_POLY : 0);
  529. crc_table[i] = s;
  530. }
  531. }
  532. static __forceinline uint32 crc32_update(uint32 crc, uint8 byte)
  533. {
  534. return (crc << 8) ^ crc_table[byte ^ (crc >> 24)];
  535. }
  536. // used in setup, and for huffman that doesn't go fast path
  537. static unsigned int bit_reverse(unsigned int n)
  538. {
  539. n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
  540. n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
  541. n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
  542. n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8);
  543. return (n >> 16) | (n << 16);
  544. }
  545. static float square(float x)
  546. {
  547. return x*x;
  548. }
  549. // this is a weird definition of log2() for which log2(1) = 1, log2(2) = 2, log2(4) = 3
  550. // as required by the specification. fast(?) implementation from stb.h
  551. // @OPTIMIZE: called multiple times per-packet with "constants"; move to setup
  552. static int ilog(int32 n)
  553. {
  554. static signed char log2_4[16] = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 };
  555. // 2 compares if n < 16, 3 compares otherwise (4 if signed or n > 1<<29)
  556. if (n < (1 << 14))
  557. if (n < (1 << 4)) return 0 + log2_4[n ];
  558. else if (n < (1 << 9)) return 5 + log2_4[n >> 5];
  559. else return 10 + log2_4[n >> 10];
  560. else if (n < (1 << 24))
  561. if (n < (1 << 19)) return 15 + log2_4[n >> 15];
  562. else return 20 + log2_4[n >> 20];
  563. else if (n < (1 << 29)) return 25 + log2_4[n >> 25];
  564. else if (n < (1 << 31)) return 30 + log2_4[n >> 30];
  565. else return 0; // signed n returns 0
  566. }
  567. #ifndef M_PI
  568. #define M_PI 3.14159265358979323846264f // from CRC
  569. #endif
  570. // code length assigned to a value with no huffman encoding
  571. #define NO_CODE 255
  572. /////////////////////// LEAF SETUP FUNCTIONS //////////////////////////
  573. //
  574. // these functions are only called at setup, and only a few times
  575. // per file
  576. static float float32_unpack(uint32 x)
  577. {
  578. // from the specification
  579. uint32 mantissa = x & 0x1fffff;
  580. uint32 sign = x & 0x80000000;
  581. uint32 exp = (x & 0x7fe00000) >> 21;
  582. double res = sign ? -(double)mantissa : (double)mantissa;
  583. return (float) ldexp((float)res, exp-788);
  584. }
  585. // zlib & jpeg huffman tables assume that the output symbols
  586. // can either be arbitrarily arranged, or have monotonically
  587. // increasing frequencies--they rely on the lengths being sorted;
  588. // this makes for a very simple generation algorithm.
  589. // vorbis allows a huffman table with non-sorted lengths. This
  590. // requires a more sophisticated construction, since symbols in
  591. // order do not map to huffman codes "in order".
  592. static void add_entry(Codebook *c, uint32 huff_code, int symbol, int count, int len, uint32 *values)
  593. {
  594. if (!c->sparse) {
  595. c->codewords [symbol] = huff_code;
  596. } else {
  597. c->codewords [count] = huff_code;
  598. c->codeword_lengths[count] = len;
  599. values [count] = symbol;
  600. }
  601. }
  602. static int compute_codewords(Codebook *c, uint8 *len, int n, uint32 *values)
  603. {
  604. int i,k,m=0;
  605. uint32 available[32];
  606. memset(available, 0, sizeof(available));
  607. // find the first entry
  608. for (k=0; k < n; ++k) if (len[k] < NO_CODE) break;
  609. if (k == n) { assert(c->sorted_entries == 0); return TRUE; }
  610. // add to the list
  611. add_entry(c, 0, k, m++, len[k], values);
  612. // add all available leaves
  613. for (i=1; i <= len[k]; ++i)
  614. available[i] = 1U << (32-i);
  615. // note that the above code treats the first case specially,
  616. // but it's really the same as the following code, so they
  617. // could probably be combined (except the initial code is 0,
  618. // and I use 0 in available[] to mean 'empty')
  619. for (i=k+1; i < n; ++i) {
  620. uint32 res;
  621. int z = len[i], y;
  622. if (z == NO_CODE) continue;
  623. // find lowest available leaf (should always be earliest,
  624. // which is what the specification calls for)
  625. // note that this property, and the fact we can never have
  626. // more than one free leaf at a given level, isn't totally
  627. // trivial to prove, but it seems true and the assert never
  628. // fires, so!
  629. while (z > 0 && !available[z]) --z;
  630. if (z == 0) { return FALSE; }
  631. res = available[z];
  632. assert(z >= 0 && z < 32);
  633. available[z] = 0;
  634. add_entry(c, bit_reverse(res), i, m++, len[i], values);
  635. // propogate availability up the tree
  636. if (z != len[i]) {
  637. assert(len[i] >= 0 && len[i] < 32);
  638. for (y=len[i]; y > z; --y) {
  639. assert(available[y] == 0);
  640. available[y] = res + (1 << (32-y));
  641. }
  642. }
  643. }
  644. return TRUE;
  645. }
  646. // accelerated huffman table allows fast O(1) match of all symbols
  647. // of length <= STB_VORBIS_FAST_HUFFMAN_LENGTH
  648. static void compute_accelerated_huffman(Codebook *c)
  649. {
  650. int i, len;
  651. for (i=0; i < FAST_HUFFMAN_TABLE_SIZE; ++i)
  652. c->fast_huffman[i] = -1;
  653. len = c->sparse ? c->sorted_entries : c->entries;
  654. #ifdef STB_VORBIS_FAST_HUFFMAN_SHORT
  655. if (len > 32767) len = 32767; // largest possible value we can encode!
  656. #endif
  657. for (i=0; i < len; ++i) {
  658. if (c->codeword_lengths[i] <= STB_VORBIS_FAST_HUFFMAN_LENGTH) {
  659. uint32 z = c->sparse ? bit_reverse(c->sorted_codewords[i]) : c->codewords[i];
  660. // set table entries for all bit combinations in the higher bits
  661. while (z < FAST_HUFFMAN_TABLE_SIZE) {
  662. c->fast_huffman[z] = i;
  663. z += 1 << c->codeword_lengths[i];
  664. }
  665. }
  666. }
  667. }
  668. #ifdef _MSC_VER
  669. #define STBV_CDECL __cdecl
  670. #else
  671. #define STBV_CDECL
  672. #endif
  673. static int STBV_CDECL uint32_compare(const void *p, const void *q)
  674. {
  675. uint32 x = * (uint32 *) p;
  676. uint32 y = * (uint32 *) q;
  677. return x < y ? -1 : x > y;
  678. }
  679. static int include_in_sort(Codebook *c, uint8 len)
  680. {
  681. if (c->sparse) { assert(len != NO_CODE); return TRUE; }
  682. if (len == NO_CODE) return FALSE;
  683. if (len > STB_VORBIS_FAST_HUFFMAN_LENGTH) return TRUE;
  684. return FALSE;
  685. }
  686. // if the fast table above doesn't work, we want to binary
  687. // search them... need to reverse the bits
  688. static void compute_sorted_huffman(Codebook *c, uint8 *lengths, uint32 *values)
  689. {
  690. int i, len;
  691. // build a list of all the entries
  692. // OPTIMIZATION: don't include the short ones, since they'll be caught by FAST_HUFFMAN.
  693. // this is kind of a frivolous optimization--I don't see any performance improvement,
  694. // but it's like 4 extra lines of code, so.
  695. if (!c->sparse) {
  696. int k = 0;
  697. for (i=0; i < c->entries; ++i)
  698. if (include_in_sort(c, lengths[i]))
  699. c->sorted_codewords[k++] = bit_reverse(c->codewords[i]);
  700. assert(k == c->sorted_entries);
  701. } else {
  702. for (i=0; i < c->sorted_entries; ++i)
  703. c->sorted_codewords[i] = bit_reverse(c->codewords[i]);
  704. }
  705. qsort(c->sorted_codewords, c->sorted_entries, sizeof(c->sorted_codewords[0]), uint32_compare);
  706. c->sorted_codewords[c->sorted_entries] = 0xffffffff;
  707. len = c->sparse ? c->sorted_entries : c->entries;
  708. // now we need to indicate how they correspond; we could either
  709. // #1: sort a different data structure that says who they correspond to
  710. // #2: for each sorted entry, search the original list to find who corresponds
  711. // #3: for each original entry, find the sorted entry
  712. // #1 requires extra storage, #2 is slow, #3 can use binary search!
  713. for (i=0; i < len; ++i) {
  714. int huff_len = c->sparse ? lengths[values[i]] : lengths[i];
  715. if (include_in_sort(c,huff_len)) {
  716. uint32 code = bit_reverse(c->codewords[i]);
  717. int x=0, n=c->sorted_entries;
  718. while (n > 1) {
  719. // invariant: sc[x] <= code < sc[x+n]
  720. int m = x + (n >> 1);
  721. if (c->sorted_codewords[m] <= code) {
  722. x = m;
  723. n -= (n>>1);
  724. } else {
  725. n >>= 1;
  726. }
  727. }
  728. assert(c->sorted_codewords[x] == code);
  729. if (c->sparse) {
  730. c->sorted_values[x] = values[i];
  731. c->codeword_lengths[x] = huff_len;
  732. } else {
  733. c->sorted_values[x] = i;
  734. }
  735. }
  736. }
  737. }
  738. // only run while parsing the header (3 times)
  739. static int vorbis_validate(uint8 *data)
  740. {
  741. static uint8 vorbis[6] = { 'v', 'o', 'r', 'b', 'i', 's' };
  742. return memcmp(data, vorbis, 6) == 0;
  743. }
  744. // called from setup only, once per code book
  745. // (formula implied by specification)
  746. static int lookup1_values(int entries, int dim)
  747. {
  748. int r = (int) floor(exp((float) log((float) entries) / dim));
  749. if ((int) floor(pow((float) r+1, dim)) <= entries) // (int) cast for MinGW warning;
  750. ++r; // floor() to avoid _ftol() when non-CRT
  751. assert(pow((float) r+1, dim) > entries);
  752. assert((int) floor(pow((float) r, dim)) <= entries); // (int),floor() as above
  753. return r;
  754. }
  755. // called twice per file
  756. static void compute_twiddle_factors(int n, float *A, float *B, float *C)
  757. {
  758. int n4 = n >> 2, n8 = n >> 3;
  759. int k,k2;
  760. for (k=k2=0; k < n4; ++k,k2+=2) {
  761. A[k2 ] = (float) cos(4*k*M_PI/n);
  762. A[k2+1] = (float) -sin(4*k*M_PI/n);
  763. B[k2 ] = (float) cos((k2+1)*M_PI/n/2) * 0.5f;
  764. B[k2+1] = (float) sin((k2+1)*M_PI/n/2) * 0.5f;
  765. }
  766. for (k=k2=0; k < n8; ++k,k2+=2) {
  767. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  768. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  769. }
  770. }
  771. static void compute_window(int n, float *window)
  772. {
  773. int n2 = n >> 1, i;
  774. for (i=0; i < n2; ++i)
  775. window[i] = (float) sin(0.5 * M_PI * square((float) sin((i - 0 + 0.5) / n2 * 0.5 * M_PI)));
  776. }
  777. static void compute_bitreverse(int n, uint16 *rev)
  778. {
  779. int ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  780. int i, n8 = n >> 3;
  781. for (i=0; i < n8; ++i)
  782. rev[i] = (bit_reverse(i) >> (32-ld+3)) << 2;
  783. }
  784. static int init_blocksize(vorb *f, int b, int n)
  785. {
  786. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3;
  787. f->A[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  788. f->B[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  789. f->C[b] = (float *) setup_malloc(f, sizeof(float) * n4);
  790. if (!f->A[b] || !f->B[b] || !f->C[b]) return error(f, VORBIS_outofmem);
  791. compute_twiddle_factors(n, f->A[b], f->B[b], f->C[b]);
  792. f->window[b] = (float *) setup_malloc(f, sizeof(float) * n2);
  793. if (!f->window[b]) return error(f, VORBIS_outofmem);
  794. compute_window(n, f->window[b]);
  795. f->bit_reverse[b] = (uint16 *) setup_malloc(f, sizeof(uint16) * n8);
  796. if (!f->bit_reverse[b]) return error(f, VORBIS_outofmem);
  797. compute_bitreverse(n, f->bit_reverse[b]);
  798. return TRUE;
  799. }
  800. static void neighbors(uint16 *x, int n, int *plow, int *phigh)
  801. {
  802. int low = -1;
  803. int high = 65536;
  804. int i;
  805. for (i=0; i < n; ++i) {
  806. if (x[i] > low && x[i] < x[n]) { *plow = i; low = x[i]; }
  807. if (x[i] < high && x[i] > x[n]) { *phigh = i; high = x[i]; }
  808. }
  809. }
  810. // this has been repurposed so y is now the original index instead of y
  811. typedef struct
  812. {
  813. uint16 x,y;
  814. } Point;
  815. static int STBV_CDECL point_compare(const void *p, const void *q)
  816. {
  817. Point *a = (Point *) p;
  818. Point *b = (Point *) q;
  819. return a->x < b->x ? -1 : a->x > b->x;
  820. }
  821. //
  822. /////////////////////// END LEAF SETUP FUNCTIONS //////////////////////////
  823. #if defined(STB_VORBIS_NO_STDIO)
  824. #define USE_MEMORY(z) TRUE
  825. #else
  826. #define USE_MEMORY(z) ((z)->stream)
  827. #endif
  828. static uint8 get8(vorb *z)
  829. {
  830. if (USE_MEMORY(z)) {
  831. if (z->stream >= z->stream_end) { z->eof = TRUE; return 0; }
  832. return *z->stream++;
  833. }
  834. #ifndef STB_VORBIS_NO_STDIO
  835. {
  836. int c = fgetc(z->f);
  837. if (c == EOF) { z->eof = TRUE; return 0; }
  838. return c;
  839. }
  840. #endif
  841. }
  842. static uint32 get32(vorb *f)
  843. {
  844. uint32 x;
  845. x = get8(f);
  846. x += get8(f) << 8;
  847. x += get8(f) << 16;
  848. x += (uint32) get8(f) << 24;
  849. return x;
  850. }
  851. static int getn(vorb *z, uint8 *data, int n)
  852. {
  853. if (USE_MEMORY(z)) {
  854. if (z->stream+n > z->stream_end) { z->eof = 1; return 0; }
  855. memcpy(data, z->stream, n);
  856. z->stream += n;
  857. return 1;
  858. }
  859. #ifndef STB_VORBIS_NO_STDIO
  860. if (fread(data, n, 1, z->f) == 1)
  861. return 1;
  862. else {
  863. z->eof = 1;
  864. return 0;
  865. }
  866. #endif
  867. }
  868. static void skip(vorb *z, int n)
  869. {
  870. if (USE_MEMORY(z)) {
  871. z->stream += n;
  872. if (z->stream >= z->stream_end) z->eof = 1;
  873. return;
  874. }
  875. #ifndef STB_VORBIS_NO_STDIO
  876. {
  877. long x = ftell(z->f);
  878. fseek(z->f, x+n, SEEK_SET);
  879. }
  880. #endif
  881. }
  882. static int set_file_offset(stb_vorbis *f, unsigned int loc)
  883. {
  884. #ifndef STB_VORBIS_NO_PUSHDATA_API
  885. if (f->push_mode) return 0;
  886. #endif
  887. f->eof = 0;
  888. if (USE_MEMORY(f)) {
  889. if (f->stream_start + loc >= f->stream_end || f->stream_start + loc < f->stream_start) {
  890. f->stream = f->stream_end;
  891. f->eof = 1;
  892. return 0;
  893. } else {
  894. f->stream = f->stream_start + loc;
  895. return 1;
  896. }
  897. }
  898. #ifndef STB_VORBIS_NO_STDIO
  899. if (loc + f->f_start < loc || loc >= 0x80000000) {
  900. loc = 0x7fffffff;
  901. f->eof = 1;
  902. } else {
  903. loc += f->f_start;
  904. }
  905. if (!fseek(f->f, loc, SEEK_SET))
  906. return 1;
  907. f->eof = 1;
  908. fseek(f->f, f->f_start, SEEK_END);
  909. return 0;
  910. #endif
  911. }
  912. static uint8 ogg_page_header[4] = { 0x4f, 0x67, 0x67, 0x53 };
  913. static int capture_pattern(vorb *f)
  914. {
  915. if (0x4f != get8(f)) return FALSE;
  916. if (0x67 != get8(f)) return FALSE;
  917. if (0x67 != get8(f)) return FALSE;
  918. if (0x53 != get8(f)) return FALSE;
  919. return TRUE;
  920. }
  921. #define PAGEFLAG_continued_packet 1
  922. #define PAGEFLAG_first_page 2
  923. #define PAGEFLAG_last_page 4
  924. static int start_page_no_capturepattern(vorb *f)
  925. {
  926. uint32 loc0,loc1,n;
  927. // stream structure version
  928. if (0 != get8(f)) return error(f, VORBIS_invalid_stream_structure_version);
  929. // header flag
  930. f->page_flag = get8(f);
  931. // absolute granule position
  932. loc0 = get32(f);
  933. loc1 = get32(f);
  934. // @TODO: validate loc0,loc1 as valid positions?
  935. // stream serial number -- vorbis doesn't interleave, so discard
  936. get32(f);
  937. //if (f->serial != get32(f)) return error(f, VORBIS_incorrect_stream_serial_number);
  938. // page sequence number
  939. n = get32(f);
  940. f->last_page = n;
  941. // CRC32
  942. get32(f);
  943. // page_segments
  944. f->segment_count = get8(f);
  945. if (!getn(f, f->segments, f->segment_count))
  946. return error(f, VORBIS_unexpected_eof);
  947. // assume we _don't_ know any the sample position of any segments
  948. f->end_seg_with_known_loc = -2;
  949. if (loc0 != ~0U || loc1 != ~0U) {
  950. int i;
  951. // determine which packet is the last one that will complete
  952. for (i=f->segment_count-1; i >= 0; --i)
  953. if (f->segments[i] < 255)
  954. break;
  955. // 'i' is now the index of the _last_ segment of a packet that ends
  956. if (i >= 0) {
  957. f->end_seg_with_known_loc = i;
  958. f->known_loc_for_packet = loc0;
  959. }
  960. }
  961. if (f->first_decode) {
  962. int i,len;
  963. ProbedPage p;
  964. len = 0;
  965. for (i=0; i < f->segment_count; ++i)
  966. len += f->segments[i];
  967. len += 27 + f->segment_count;
  968. p.page_start = f->first_audio_page_offset;
  969. p.page_end = p.page_start + len;
  970. p.last_decoded_sample = loc0;
  971. f->p_first = p;
  972. }
  973. f->next_seg = 0;
  974. return TRUE;
  975. }
  976. static int start_page(vorb *f)
  977. {
  978. if (!capture_pattern(f)) return error(f, VORBIS_missing_capture_pattern);
  979. return start_page_no_capturepattern(f);
  980. }
  981. static int start_packet(vorb *f)
  982. {
  983. while (f->next_seg == -1) {
  984. if (!start_page(f)) return FALSE;
  985. if (f->page_flag & PAGEFLAG_continued_packet)
  986. return error(f, VORBIS_continued_packet_flag_invalid);
  987. }
  988. f->last_seg = FALSE;
  989. f->valid_bits = 0;
  990. f->packet_bytes = 0;
  991. f->bytes_in_seg = 0;
  992. // f->next_seg is now valid
  993. return TRUE;
  994. }
  995. static int maybe_start_packet(vorb *f)
  996. {
  997. if (f->next_seg == -1) {
  998. int x = get8(f);
  999. if (f->eof) return FALSE; // EOF at page boundary is not an error!
  1000. if (0x4f != x ) return error(f, VORBIS_missing_capture_pattern);
  1001. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1002. if (0x67 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1003. if (0x53 != get8(f)) return error(f, VORBIS_missing_capture_pattern);
  1004. if (!start_page_no_capturepattern(f)) return FALSE;
  1005. if (f->page_flag & PAGEFLAG_continued_packet) {
  1006. // set up enough state that we can read this packet if we want,
  1007. // e.g. during recovery
  1008. f->last_seg = FALSE;
  1009. f->bytes_in_seg = 0;
  1010. return error(f, VORBIS_continued_packet_flag_invalid);
  1011. }
  1012. }
  1013. return start_packet(f);
  1014. }
  1015. static int next_segment(vorb *f)
  1016. {
  1017. int len;
  1018. if (f->last_seg) return 0;
  1019. if (f->next_seg == -1) {
  1020. f->last_seg_which = f->segment_count-1; // in case start_page fails
  1021. if (!start_page(f)) { f->last_seg = 1; return 0; }
  1022. if (!(f->page_flag & PAGEFLAG_continued_packet)) return error(f, VORBIS_continued_packet_flag_invalid);
  1023. }
  1024. len = f->segments[f->next_seg++];
  1025. if (len < 255) {
  1026. f->last_seg = TRUE;
  1027. f->last_seg_which = f->next_seg-1;
  1028. }
  1029. if (f->next_seg >= f->segment_count)
  1030. f->next_seg = -1;
  1031. assert(f->bytes_in_seg == 0);
  1032. f->bytes_in_seg = len;
  1033. return len;
  1034. }
  1035. #define EOP (-1)
  1036. #define INVALID_BITS (-1)
  1037. static int get8_packet_raw(vorb *f)
  1038. {
  1039. if (!f->bytes_in_seg) { // CLANG!
  1040. if (f->last_seg) return EOP;
  1041. else if (!next_segment(f)) return EOP;
  1042. }
  1043. assert(f->bytes_in_seg > 0);
  1044. --f->bytes_in_seg;
  1045. ++f->packet_bytes;
  1046. return get8(f);
  1047. }
  1048. static int get8_packet(vorb *f)
  1049. {
  1050. int x = get8_packet_raw(f);
  1051. f->valid_bits = 0;
  1052. return x;
  1053. }
  1054. static void flush_packet(vorb *f)
  1055. {
  1056. while (get8_packet_raw(f) != EOP);
  1057. }
  1058. // @OPTIMIZE: this is the secondary bit decoder, so it's probably not as important
  1059. // as the huffman decoder?
  1060. static uint32 get_bits(vorb *f, int n)
  1061. {
  1062. uint32 z;
  1063. if (f->valid_bits < 0) return 0;
  1064. if (f->valid_bits < n) {
  1065. if (n > 24) {
  1066. // the accumulator technique below would not work correctly in this case
  1067. z = get_bits(f, 24);
  1068. z += get_bits(f, n-24) << 24;
  1069. return z;
  1070. }
  1071. if (f->valid_bits == 0) f->acc = 0;
  1072. while (f->valid_bits < n) {
  1073. int z = get8_packet_raw(f);
  1074. if (z == EOP) {
  1075. f->valid_bits = INVALID_BITS;
  1076. return 0;
  1077. }
  1078. f->acc += z << f->valid_bits;
  1079. f->valid_bits += 8;
  1080. }
  1081. }
  1082. if (f->valid_bits < 0) return 0;
  1083. z = f->acc & ((1 << n)-1);
  1084. f->acc >>= n;
  1085. f->valid_bits -= n;
  1086. return z;
  1087. }
  1088. // @OPTIMIZE: primary accumulator for huffman
  1089. // expand the buffer to as many bits as possible without reading off end of packet
  1090. // it might be nice to allow f->valid_bits and f->acc to be stored in registers,
  1091. // e.g. cache them locally and decode locally
  1092. static __forceinline void prep_huffman(vorb *f)
  1093. {
  1094. if (f->valid_bits <= 24) {
  1095. if (f->valid_bits == 0) f->acc = 0;
  1096. do {
  1097. int z;
  1098. if (f->last_seg && !f->bytes_in_seg) return;
  1099. z = get8_packet_raw(f);
  1100. if (z == EOP) return;
  1101. f->acc += (unsigned) z << f->valid_bits;
  1102. f->valid_bits += 8;
  1103. } while (f->valid_bits <= 24);
  1104. }
  1105. }
  1106. enum
  1107. {
  1108. VORBIS_packet_id = 1,
  1109. VORBIS_packet_comment = 3,
  1110. VORBIS_packet_setup = 5
  1111. };
  1112. static int codebook_decode_scalar_raw(vorb *f, Codebook *c)
  1113. {
  1114. int i;
  1115. prep_huffman(f);
  1116. if (c->codewords == NULL && c->sorted_codewords == NULL)
  1117. return -1;
  1118. // cases to use binary search: sorted_codewords && !c->codewords
  1119. // sorted_codewords && c->entries > 8
  1120. if (c->entries > 8 ? c->sorted_codewords!=NULL : !c->codewords) {
  1121. // binary search
  1122. uint32 code = bit_reverse(f->acc);
  1123. int x=0, n=c->sorted_entries, len;
  1124. while (n > 1) {
  1125. // invariant: sc[x] <= code < sc[x+n]
  1126. int m = x + (n >> 1);
  1127. if (c->sorted_codewords[m] <= code) {
  1128. x = m;
  1129. n -= (n>>1);
  1130. } else {
  1131. n >>= 1;
  1132. }
  1133. }
  1134. // x is now the sorted index
  1135. if (!c->sparse) x = c->sorted_values[x];
  1136. // x is now sorted index if sparse, or symbol otherwise
  1137. len = c->codeword_lengths[x];
  1138. if (f->valid_bits >= len) {
  1139. f->acc >>= len;
  1140. f->valid_bits -= len;
  1141. return x;
  1142. }
  1143. f->valid_bits = 0;
  1144. return -1;
  1145. }
  1146. // if small, linear search
  1147. assert(!c->sparse);
  1148. for (i=0; i < c->entries; ++i) {
  1149. if (c->codeword_lengths[i] == NO_CODE) continue;
  1150. if (c->codewords[i] == (f->acc & ((1 << c->codeword_lengths[i])-1))) {
  1151. if (f->valid_bits >= c->codeword_lengths[i]) {
  1152. f->acc >>= c->codeword_lengths[i];
  1153. f->valid_bits -= c->codeword_lengths[i];
  1154. return i;
  1155. }
  1156. f->valid_bits = 0;
  1157. return -1;
  1158. }
  1159. }
  1160. error(f, VORBIS_invalid_stream);
  1161. f->valid_bits = 0;
  1162. return -1;
  1163. }
  1164. #ifndef STB_VORBIS_NO_INLINE_DECODE
  1165. #define DECODE_RAW(var, f,c) \
  1166. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH) \
  1167. prep_huffman(f); \
  1168. var = f->acc & FAST_HUFFMAN_TABLE_MASK; \
  1169. var = c->fast_huffman[var]; \
  1170. if (var >= 0) { \
  1171. int n = c->codeword_lengths[var]; \
  1172. f->acc >>= n; \
  1173. f->valid_bits -= n; \
  1174. if (f->valid_bits < 0) { f->valid_bits = 0; var = -1; } \
  1175. } else { \
  1176. var = codebook_decode_scalar_raw(f,c); \
  1177. }
  1178. #else
  1179. static int codebook_decode_scalar(vorb *f, Codebook *c)
  1180. {
  1181. int i;
  1182. if (f->valid_bits < STB_VORBIS_FAST_HUFFMAN_LENGTH)
  1183. prep_huffman(f);
  1184. // fast huffman table lookup
  1185. i = f->acc & FAST_HUFFMAN_TABLE_MASK;
  1186. i = c->fast_huffman[i];
  1187. if (i >= 0) {
  1188. f->acc >>= c->codeword_lengths[i];
  1189. f->valid_bits -= c->codeword_lengths[i];
  1190. if (f->valid_bits < 0) { f->valid_bits = 0; return -1; }
  1191. return i;
  1192. }
  1193. return codebook_decode_scalar_raw(f,c);
  1194. }
  1195. #define DECODE_RAW(var,f,c) var = codebook_decode_scalar(f,c);
  1196. #endif
  1197. #define DECODE(var,f,c) \
  1198. DECODE_RAW(var,f,c) \
  1199. if (c->sparse) var = c->sorted_values[var];
  1200. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1201. #define DECODE_VQ(var,f,c) DECODE_RAW(var,f,c)
  1202. #else
  1203. #define DECODE_VQ(var,f,c) DECODE(var,f,c)
  1204. #endif
  1205. // CODEBOOK_ELEMENT_FAST is an optimization for the CODEBOOK_FLOATS case
  1206. // where we avoid one addition
  1207. #define CODEBOOK_ELEMENT(c,off) (c->multiplicands[off])
  1208. #define CODEBOOK_ELEMENT_FAST(c,off) (c->multiplicands[off])
  1209. #define CODEBOOK_ELEMENT_BASE(c) (0)
  1210. static int codebook_decode_start(vorb *f, Codebook *c)
  1211. {
  1212. int z = -1;
  1213. // type 0 is only legal in a scalar context
  1214. if (c->lookup_type == 0)
  1215. error(f, VORBIS_invalid_stream);
  1216. else {
  1217. DECODE_VQ(z,f,c);
  1218. if (c->sparse) assert(z < c->sorted_entries);
  1219. if (z < 0) { // check for EOP
  1220. if (!f->bytes_in_seg)
  1221. if (f->last_seg)
  1222. return z;
  1223. error(f, VORBIS_invalid_stream);
  1224. }
  1225. }
  1226. return z;
  1227. }
  1228. static int codebook_decode(vorb *f, Codebook *c, float *output, int len)
  1229. {
  1230. int i,z = codebook_decode_start(f,c);
  1231. if (z < 0) return FALSE;
  1232. if (len > c->dimensions) len = c->dimensions;
  1233. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1234. if (c->lookup_type == 1) {
  1235. float last = CODEBOOK_ELEMENT_BASE(c);
  1236. int div = 1;
  1237. for (i=0; i < len; ++i) {
  1238. int off = (z / div) % c->lookup_values;
  1239. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1240. output[i] += val;
  1241. if (c->sequence_p) last = val + c->minimum_value;
  1242. div *= c->lookup_values;
  1243. }
  1244. return TRUE;
  1245. }
  1246. #endif
  1247. z *= c->dimensions;
  1248. if (c->sequence_p) {
  1249. float last = CODEBOOK_ELEMENT_BASE(c);
  1250. for (i=0; i < len; ++i) {
  1251. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1252. output[i] += val;
  1253. last = val + c->minimum_value;
  1254. }
  1255. } else {
  1256. float last = CODEBOOK_ELEMENT_BASE(c);
  1257. for (i=0; i < len; ++i) {
  1258. output[i] += CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1259. }
  1260. }
  1261. return TRUE;
  1262. }
  1263. static int codebook_decode_step(vorb *f, Codebook *c, float *output, int len, int step)
  1264. {
  1265. int i,z = codebook_decode_start(f,c);
  1266. float last = CODEBOOK_ELEMENT_BASE(c);
  1267. if (z < 0) return FALSE;
  1268. if (len > c->dimensions) len = c->dimensions;
  1269. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1270. if (c->lookup_type == 1) {
  1271. int div = 1;
  1272. for (i=0; i < len; ++i) {
  1273. int off = (z / div) % c->lookup_values;
  1274. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1275. output[i*step] += val;
  1276. if (c->sequence_p) last = val;
  1277. div *= c->lookup_values;
  1278. }
  1279. return TRUE;
  1280. }
  1281. #endif
  1282. z *= c->dimensions;
  1283. for (i=0; i < len; ++i) {
  1284. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1285. output[i*step] += val;
  1286. if (c->sequence_p) last = val;
  1287. }
  1288. return TRUE;
  1289. }
  1290. static int codebook_decode_deinterleave_repeat(vorb *f, Codebook *c, float **outputs, int ch, int *c_inter_p, int *p_inter_p, int len, int total_decode)
  1291. {
  1292. int c_inter = *c_inter_p;
  1293. int p_inter = *p_inter_p;
  1294. int i,z, effective = c->dimensions;
  1295. // type 0 is only legal in a scalar context
  1296. if (c->lookup_type == 0) return error(f, VORBIS_invalid_stream);
  1297. while (total_decode > 0) {
  1298. float last = CODEBOOK_ELEMENT_BASE(c);
  1299. DECODE_VQ(z,f,c);
  1300. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1301. assert(!c->sparse || z < c->sorted_entries);
  1302. #endif
  1303. if (z < 0) {
  1304. if (!f->bytes_in_seg)
  1305. if (f->last_seg) return FALSE;
  1306. return error(f, VORBIS_invalid_stream);
  1307. }
  1308. // if this will take us off the end of the buffers, stop short!
  1309. // we check by computing the length of the virtual interleaved
  1310. // buffer (len*ch), our current offset within it (p_inter*ch)+(c_inter),
  1311. // and the length we'll be using (effective)
  1312. if (c_inter + p_inter*ch + effective > len * ch) {
  1313. effective = len*ch - (p_inter*ch - c_inter);
  1314. }
  1315. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1316. if (c->lookup_type == 1) {
  1317. int div = 1;
  1318. for (i=0; i < effective; ++i) {
  1319. int off = (z / div) % c->lookup_values;
  1320. float val = CODEBOOK_ELEMENT_FAST(c,off) + last;
  1321. if (outputs[c_inter])
  1322. outputs[c_inter][p_inter] += val;
  1323. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1324. if (c->sequence_p) last = val;
  1325. div *= c->lookup_values;
  1326. }
  1327. } else
  1328. #endif
  1329. {
  1330. z *= c->dimensions;
  1331. if (c->sequence_p) {
  1332. for (i=0; i < effective; ++i) {
  1333. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1334. if (outputs[c_inter])
  1335. outputs[c_inter][p_inter] += val;
  1336. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1337. last = val;
  1338. }
  1339. } else {
  1340. for (i=0; i < effective; ++i) {
  1341. float val = CODEBOOK_ELEMENT_FAST(c,z+i) + last;
  1342. if (outputs[c_inter])
  1343. outputs[c_inter][p_inter] += val;
  1344. if (++c_inter == ch) { c_inter = 0; ++p_inter; }
  1345. }
  1346. }
  1347. }
  1348. total_decode -= effective;
  1349. }
  1350. *c_inter_p = c_inter;
  1351. *p_inter_p = p_inter;
  1352. return TRUE;
  1353. }
  1354. static int predict_point(int x, int x0, int x1, int y0, int y1)
  1355. {
  1356. int dy = y1 - y0;
  1357. int adx = x1 - x0;
  1358. // @OPTIMIZE: force int division to round in the right direction... is this necessary on x86?
  1359. int err = abs(dy) * (x - x0);
  1360. int off = err / adx;
  1361. return dy < 0 ? y0 - off : y0 + off;
  1362. }
  1363. // the following table is block-copied from the specification
  1364. static float inverse_db_table[256] =
  1365. {
  1366. 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f,
  1367. 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f,
  1368. 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.1287530e-07f,
  1369. 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f,
  1370. 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f,
  1371. 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f,
  1372. 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f,
  1373. 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f,
  1374. 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f,
  1375. 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f,
  1376. 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f,
  1377. 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f,
  1378. 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f,
  1379. 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f,
  1380. 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f,
  1381. 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f,
  1382. 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f,
  1383. 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f,
  1384. 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f,
  1385. 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f,
  1386. 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f,
  1387. 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f,
  1388. 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f,
  1389. 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f,
  1390. 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f,
  1391. 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f,
  1392. 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f,
  1393. 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f,
  1394. 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f,
  1395. 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f,
  1396. 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f,
  1397. 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f,
  1398. 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f,
  1399. 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f,
  1400. 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f,
  1401. 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f,
  1402. 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f,
  1403. 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f,
  1404. 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f,
  1405. 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f,
  1406. 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f,
  1407. 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f,
  1408. 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f,
  1409. 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f,
  1410. 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f,
  1411. 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f,
  1412. 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f,
  1413. 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f,
  1414. 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f,
  1415. 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f,
  1416. 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f,
  1417. 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f,
  1418. 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f,
  1419. 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f,
  1420. 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f,
  1421. 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f,
  1422. 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f,
  1423. 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f,
  1424. 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f,
  1425. 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f,
  1426. 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f,
  1427. 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f,
  1428. 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f,
  1429. 0.82788260f, 0.88168307f, 0.9389798f, 1.0f
  1430. };
  1431. // @OPTIMIZE: if you want to replace this bresenham line-drawing routine,
  1432. // note that you must produce bit-identical output to decode correctly;
  1433. // this specific sequence of operations is specified in the spec (it's
  1434. // drawing integer-quantized frequency-space lines that the encoder
  1435. // expects to be exactly the same)
  1436. // ... also, isn't the whole point of Bresenham's algorithm to NOT
  1437. // have to divide in the setup? sigh.
  1438. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  1439. #define LINE_OP(a,b) a *= b
  1440. #else
  1441. #define LINE_OP(a,b) a = b
  1442. #endif
  1443. #ifdef STB_VORBIS_DIVIDE_TABLE
  1444. #define DIVTAB_NUMER 32
  1445. #define DIVTAB_DENOM 64
  1446. int8 integer_divide_table[DIVTAB_NUMER][DIVTAB_DENOM]; // 2KB
  1447. #endif
  1448. static __forceinline void draw_line(float *output, int x0, int y0, int x1, int y1, int n)
  1449. {
  1450. int dy = y1 - y0;
  1451. int adx = x1 - x0;
  1452. int ady = abs(dy);
  1453. int base;
  1454. int x=x0,y=y0;
  1455. int err = 0;
  1456. int sy;
  1457. #ifdef STB_VORBIS_DIVIDE_TABLE
  1458. if (adx < DIVTAB_DENOM && ady < DIVTAB_NUMER) {
  1459. if (dy < 0) {
  1460. base = -integer_divide_table[ady][adx];
  1461. sy = base-1;
  1462. } else {
  1463. base = integer_divide_table[ady][adx];
  1464. sy = base+1;
  1465. }
  1466. } else {
  1467. base = dy / adx;
  1468. if (dy < 0)
  1469. sy = base - 1;
  1470. else
  1471. sy = base+1;
  1472. }
  1473. #else
  1474. base = dy / adx;
  1475. if (dy < 0)
  1476. sy = base - 1;
  1477. else
  1478. sy = base+1;
  1479. #endif
  1480. ady -= abs(base) * adx;
  1481. if (x1 > n) x1 = n;
  1482. if (x < x1) {
  1483. LINE_OP(output[x], inverse_db_table[y]);
  1484. for (++x; x < x1; ++x) {
  1485. err += ady;
  1486. if (err >= adx) {
  1487. err -= adx;
  1488. y += sy;
  1489. } else
  1490. y += base;
  1491. LINE_OP(output[x], inverse_db_table[y]);
  1492. }
  1493. }
  1494. }
  1495. static int residue_decode(vorb *f, Codebook *book, float *target, int offset, int n, int rtype)
  1496. {
  1497. int k;
  1498. if (rtype == 0) {
  1499. int step = n / book->dimensions;
  1500. for (k=0; k < step; ++k)
  1501. if (!codebook_decode_step(f, book, target+offset+k, n-offset-k, step))
  1502. return FALSE;
  1503. } else {
  1504. for (k=0; k < n; ) {
  1505. if (!codebook_decode(f, book, target+offset, n-k))
  1506. return FALSE;
  1507. k += book->dimensions;
  1508. offset += book->dimensions;
  1509. }
  1510. }
  1511. return TRUE;
  1512. }
  1513. static void decode_residue(vorb *f, float *residue_buffers[], int ch, int n, int rn, uint8 *do_not_decode)
  1514. {
  1515. int i,j,pass;
  1516. Residue *r = f->residue_config + rn;
  1517. int rtype = f->residue_types[rn];
  1518. int c = r->classbook;
  1519. int classwords = f->codebooks[c].dimensions;
  1520. int n_read = r->end - r->begin;
  1521. int part_read = n_read / r->part_size;
  1522. int temp_alloc_point = temp_alloc_save(f);
  1523. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1524. uint8 ***part_classdata = (uint8 ***) temp_block_array(f,f->channels, part_read * sizeof(**part_classdata));
  1525. #else
  1526. int **classifications = (int **) temp_block_array(f,f->channels, part_read * sizeof(**classifications));
  1527. #endif
  1528. CHECK(f);
  1529. for (i=0; i < ch; ++i)
  1530. if (!do_not_decode[i])
  1531. memset(residue_buffers[i], 0, sizeof(float) * n);
  1532. if (rtype == 2 && ch != 1) {
  1533. for (j=0; j < ch; ++j)
  1534. if (!do_not_decode[j])
  1535. break;
  1536. if (j == ch)
  1537. goto done;
  1538. for (pass=0; pass < 8; ++pass) {
  1539. int pcount = 0, class_set = 0;
  1540. if (ch == 2) {
  1541. while (pcount < part_read) {
  1542. int z = r->begin + pcount*r->part_size;
  1543. int c_inter = (z & 1), p_inter = z>>1;
  1544. if (pass == 0) {
  1545. Codebook *c = f->codebooks+r->classbook;
  1546. int q;
  1547. DECODE(q,f,c);
  1548. if (q == EOP) goto done;
  1549. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1550. part_classdata[0][class_set] = r->classdata[q];
  1551. #else
  1552. for (i=classwords-1; i >= 0; --i) {
  1553. classifications[0][i+pcount] = q % r->classifications;
  1554. q /= r->classifications;
  1555. }
  1556. #endif
  1557. }
  1558. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1559. int z = r->begin + pcount*r->part_size;
  1560. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1561. int c = part_classdata[0][class_set][i];
  1562. #else
  1563. int c = classifications[0][pcount];
  1564. #endif
  1565. int b = r->residue_books[c][pass];
  1566. if (b >= 0) {
  1567. Codebook *book = f->codebooks + b;
  1568. #ifdef STB_VORBIS_DIVIDES_IN_CODEBOOK
  1569. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1570. goto done;
  1571. #else
  1572. // saves 1%
  1573. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1574. goto done;
  1575. #endif
  1576. } else {
  1577. z += r->part_size;
  1578. c_inter = z & 1;
  1579. p_inter = z >> 1;
  1580. }
  1581. }
  1582. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1583. ++class_set;
  1584. #endif
  1585. }
  1586. } else if (ch == 1) {
  1587. while (pcount < part_read) {
  1588. int z = r->begin + pcount*r->part_size;
  1589. int c_inter = 0, p_inter = z;
  1590. if (pass == 0) {
  1591. Codebook *c = f->codebooks+r->classbook;
  1592. int q;
  1593. DECODE(q,f,c);
  1594. if (q == EOP) goto done;
  1595. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1596. part_classdata[0][class_set] = r->classdata[q];
  1597. #else
  1598. for (i=classwords-1; i >= 0; --i) {
  1599. classifications[0][i+pcount] = q % r->classifications;
  1600. q /= r->classifications;
  1601. }
  1602. #endif
  1603. }
  1604. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1605. int z = r->begin + pcount*r->part_size;
  1606. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1607. int c = part_classdata[0][class_set][i];
  1608. #else
  1609. int c = classifications[0][pcount];
  1610. #endif
  1611. int b = r->residue_books[c][pass];
  1612. if (b >= 0) {
  1613. Codebook *book = f->codebooks + b;
  1614. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1615. goto done;
  1616. } else {
  1617. z += r->part_size;
  1618. c_inter = 0;
  1619. p_inter = z;
  1620. }
  1621. }
  1622. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1623. ++class_set;
  1624. #endif
  1625. }
  1626. } else {
  1627. while (pcount < part_read) {
  1628. int z = r->begin + pcount*r->part_size;
  1629. int c_inter = z % ch, p_inter = z/ch;
  1630. if (pass == 0) {
  1631. Codebook *c = f->codebooks+r->classbook;
  1632. int q;
  1633. DECODE(q,f,c);
  1634. if (q == EOP) goto done;
  1635. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1636. part_classdata[0][class_set] = r->classdata[q];
  1637. #else
  1638. for (i=classwords-1; i >= 0; --i) {
  1639. classifications[0][i+pcount] = q % r->classifications;
  1640. q /= r->classifications;
  1641. }
  1642. #endif
  1643. }
  1644. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1645. int z = r->begin + pcount*r->part_size;
  1646. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1647. int c = part_classdata[0][class_set][i];
  1648. #else
  1649. int c = classifications[0][pcount];
  1650. #endif
  1651. int b = r->residue_books[c][pass];
  1652. if (b >= 0) {
  1653. Codebook *book = f->codebooks + b;
  1654. if (!codebook_decode_deinterleave_repeat(f, book, residue_buffers, ch, &c_inter, &p_inter, n, r->part_size))
  1655. goto done;
  1656. } else {
  1657. z += r->part_size;
  1658. c_inter = z % ch;
  1659. p_inter = z / ch;
  1660. }
  1661. }
  1662. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1663. ++class_set;
  1664. #endif
  1665. }
  1666. }
  1667. }
  1668. goto done;
  1669. }
  1670. CHECK(f);
  1671. for (pass=0; pass < 8; ++pass) {
  1672. int pcount = 0, class_set=0;
  1673. while (pcount < part_read) {
  1674. if (pass == 0) {
  1675. for (j=0; j < ch; ++j) {
  1676. if (!do_not_decode[j]) {
  1677. Codebook *c = f->codebooks+r->classbook;
  1678. int temp;
  1679. DECODE(temp,f,c);
  1680. if (temp == EOP) goto done;
  1681. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1682. part_classdata[j][class_set] = r->classdata[temp];
  1683. #else
  1684. for (i=classwords-1; i >= 0; --i) {
  1685. classifications[j][i+pcount] = temp % r->classifications;
  1686. temp /= r->classifications;
  1687. }
  1688. #endif
  1689. }
  1690. }
  1691. }
  1692. for (i=0; i < classwords && pcount < part_read; ++i, ++pcount) {
  1693. for (j=0; j < ch; ++j) {
  1694. if (!do_not_decode[j]) {
  1695. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1696. int c = part_classdata[j][class_set][i];
  1697. #else
  1698. int c = classifications[j][pcount];
  1699. #endif
  1700. int b = r->residue_books[c][pass];
  1701. if (b >= 0) {
  1702. float *target = residue_buffers[j];
  1703. int offset = r->begin + pcount * r->part_size;
  1704. int n = r->part_size;
  1705. Codebook *book = f->codebooks + b;
  1706. if (!residue_decode(f, book, target, offset, n, rtype))
  1707. goto done;
  1708. }
  1709. }
  1710. }
  1711. }
  1712. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1713. ++class_set;
  1714. #endif
  1715. }
  1716. }
  1717. done:
  1718. CHECK(f);
  1719. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  1720. temp_free(f,part_classdata);
  1721. #else
  1722. temp_free(f,classifications);
  1723. #endif
  1724. temp_alloc_restore(f,temp_alloc_point);
  1725. }
  1726. #if 0
  1727. // slow way for debugging
  1728. void inverse_mdct_slow(float *buffer, int n)
  1729. {
  1730. int i,j;
  1731. int n2 = n >> 1;
  1732. float *x = (float *) malloc(sizeof(*x) * n2);
  1733. memcpy(x, buffer, sizeof(*x) * n2);
  1734. for (i=0; i < n; ++i) {
  1735. float acc = 0;
  1736. for (j=0; j < n2; ++j)
  1737. // formula from paper:
  1738. //acc += n/4.0f * x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
  1739. // formula from wikipedia
  1740. //acc += 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
  1741. // these are equivalent, except the formula from the paper inverts the multiplier!
  1742. // however, what actually works is NO MULTIPLIER!?!
  1743. //acc += 64 * 2.0f / n2 * x[j] * (float) cos(M_PI/n2 * (i + 0.5 + n2/2)*(j + 0.5));
  1744. acc += x[j] * (float) cos(M_PI / 2 / n * (2 * i + 1 + n/2.0)*(2*j+1));
  1745. buffer[i] = acc;
  1746. }
  1747. free(x);
  1748. }
  1749. #elif 0
  1750. // same as above, but just barely able to run in real time on modern machines
  1751. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  1752. {
  1753. float mcos[16384];
  1754. int i,j;
  1755. int n2 = n >> 1, nmask = (n << 2) -1;
  1756. float *x = (float *) malloc(sizeof(*x) * n2);
  1757. memcpy(x, buffer, sizeof(*x) * n2);
  1758. for (i=0; i < 4*n; ++i)
  1759. mcos[i] = (float) cos(M_PI / 2 * i / n);
  1760. for (i=0; i < n; ++i) {
  1761. float acc = 0;
  1762. for (j=0; j < n2; ++j)
  1763. acc += x[j] * mcos[(2 * i + 1 + n2)*(2*j+1) & nmask];
  1764. buffer[i] = acc;
  1765. }
  1766. free(x);
  1767. }
  1768. #elif 0
  1769. // transform to use a slow dct-iv; this is STILL basically trivial,
  1770. // but only requires half as many ops
  1771. void dct_iv_slow(float *buffer, int n)
  1772. {
  1773. float mcos[16384];
  1774. float x[2048];
  1775. int i,j;
  1776. int n2 = n >> 1, nmask = (n << 3) - 1;
  1777. memcpy(x, buffer, sizeof(*x) * n);
  1778. for (i=0; i < 8*n; ++i)
  1779. mcos[i] = (float) cos(M_PI / 4 * i / n);
  1780. for (i=0; i < n; ++i) {
  1781. float acc = 0;
  1782. for (j=0; j < n; ++j)
  1783. acc += x[j] * mcos[((2 * i + 1)*(2*j+1)) & nmask];
  1784. buffer[i] = acc;
  1785. }
  1786. }
  1787. void inverse_mdct_slow(float *buffer, int n, vorb *f, int blocktype)
  1788. {
  1789. int i, n4 = n >> 2, n2 = n >> 1, n3_4 = n - n4;
  1790. float temp[4096];
  1791. memcpy(temp, buffer, n2 * sizeof(float));
  1792. dct_iv_slow(temp, n2); // returns -c'-d, a-b'
  1793. for (i=0; i < n4 ; ++i) buffer[i] = temp[i+n4]; // a-b'
  1794. for ( ; i < n3_4; ++i) buffer[i] = -temp[n3_4 - i - 1]; // b-a', c+d'
  1795. for ( ; i < n ; ++i) buffer[i] = -temp[i - n3_4]; // c'+d
  1796. }
  1797. #endif
  1798. #ifndef LIBVORBIS_MDCT
  1799. #define LIBVORBIS_MDCT 0
  1800. #endif
  1801. #if LIBVORBIS_MDCT
  1802. // directly call the vorbis MDCT using an interface documented
  1803. // by Jeff Roberts... useful for performance comparison
  1804. typedef struct
  1805. {
  1806. int n;
  1807. int log2n;
  1808. float *trig;
  1809. int *bitrev;
  1810. float scale;
  1811. } mdct_lookup;
  1812. extern void mdct_init(mdct_lookup *lookup, int n);
  1813. extern void mdct_clear(mdct_lookup *l);
  1814. extern void mdct_backward(mdct_lookup *init, float *in, float *out);
  1815. mdct_lookup M1,M2;
  1816. void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  1817. {
  1818. mdct_lookup *M;
  1819. if (M1.n == n) M = &M1;
  1820. else if (M2.n == n) M = &M2;
  1821. else if (M1.n == 0) { mdct_init(&M1, n); M = &M1; }
  1822. else {
  1823. if (M2.n) __asm int 3;
  1824. mdct_init(&M2, n);
  1825. M = &M2;
  1826. }
  1827. mdct_backward(M, buffer, buffer);
  1828. }
  1829. #endif
  1830. // the following were split out into separate functions while optimizing;
  1831. // they could be pushed back up but eh. __forceinline showed no change;
  1832. // they're probably already being inlined.
  1833. static void imdct_step3_iter0_loop(int n, float *e, int i_off, int k_off, float *A)
  1834. {
  1835. float *ee0 = e + i_off;
  1836. float *ee2 = ee0 + k_off;
  1837. int i;
  1838. assert((n & 3) == 0);
  1839. for (i=(n>>2); i > 0; --i) {
  1840. float k00_20, k01_21;
  1841. k00_20 = ee0[ 0] - ee2[ 0];
  1842. k01_21 = ee0[-1] - ee2[-1];
  1843. ee0[ 0] += ee2[ 0];//ee0[ 0] = ee0[ 0] + ee2[ 0];
  1844. ee0[-1] += ee2[-1];//ee0[-1] = ee0[-1] + ee2[-1];
  1845. ee2[ 0] = k00_20 * A[0] - k01_21 * A[1];
  1846. ee2[-1] = k01_21 * A[0] + k00_20 * A[1];
  1847. A += 8;
  1848. k00_20 = ee0[-2] - ee2[-2];
  1849. k01_21 = ee0[-3] - ee2[-3];
  1850. ee0[-2] += ee2[-2];//ee0[-2] = ee0[-2] + ee2[-2];
  1851. ee0[-3] += ee2[-3];//ee0[-3] = ee0[-3] + ee2[-3];
  1852. ee2[-2] = k00_20 * A[0] - k01_21 * A[1];
  1853. ee2[-3] = k01_21 * A[0] + k00_20 * A[1];
  1854. A += 8;
  1855. k00_20 = ee0[-4] - ee2[-4];
  1856. k01_21 = ee0[-5] - ee2[-5];
  1857. ee0[-4] += ee2[-4];//ee0[-4] = ee0[-4] + ee2[-4];
  1858. ee0[-5] += ee2[-5];//ee0[-5] = ee0[-5] + ee2[-5];
  1859. ee2[-4] = k00_20 * A[0] - k01_21 * A[1];
  1860. ee2[-5] = k01_21 * A[0] + k00_20 * A[1];
  1861. A += 8;
  1862. k00_20 = ee0[-6] - ee2[-6];
  1863. k01_21 = ee0[-7] - ee2[-7];
  1864. ee0[-6] += ee2[-6];//ee0[-6] = ee0[-6] + ee2[-6];
  1865. ee0[-7] += ee2[-7];//ee0[-7] = ee0[-7] + ee2[-7];
  1866. ee2[-6] = k00_20 * A[0] - k01_21 * A[1];
  1867. ee2[-7] = k01_21 * A[0] + k00_20 * A[1];
  1868. A += 8;
  1869. ee0 -= 8;
  1870. ee2 -= 8;
  1871. }
  1872. }
  1873. static void imdct_step3_inner_r_loop(int lim, float *e, int d0, int k_off, float *A, int k1)
  1874. {
  1875. int i;
  1876. float k00_20, k01_21;
  1877. float *e0 = e + d0;
  1878. float *e2 = e0 + k_off;
  1879. for (i=lim >> 2; i > 0; --i) {
  1880. k00_20 = e0[-0] - e2[-0];
  1881. k01_21 = e0[-1] - e2[-1];
  1882. e0[-0] += e2[-0];//e0[-0] = e0[-0] + e2[-0];
  1883. e0[-1] += e2[-1];//e0[-1] = e0[-1] + e2[-1];
  1884. e2[-0] = (k00_20)*A[0] - (k01_21) * A[1];
  1885. e2[-1] = (k01_21)*A[0] + (k00_20) * A[1];
  1886. A += k1;
  1887. k00_20 = e0[-2] - e2[-2];
  1888. k01_21 = e0[-3] - e2[-3];
  1889. e0[-2] += e2[-2];//e0[-2] = e0[-2] + e2[-2];
  1890. e0[-3] += e2[-3];//e0[-3] = e0[-3] + e2[-3];
  1891. e2[-2] = (k00_20)*A[0] - (k01_21) * A[1];
  1892. e2[-3] = (k01_21)*A[0] + (k00_20) * A[1];
  1893. A += k1;
  1894. k00_20 = e0[-4] - e2[-4];
  1895. k01_21 = e0[-5] - e2[-5];
  1896. e0[-4] += e2[-4];//e0[-4] = e0[-4] + e2[-4];
  1897. e0[-5] += e2[-5];//e0[-5] = e0[-5] + e2[-5];
  1898. e2[-4] = (k00_20)*A[0] - (k01_21) * A[1];
  1899. e2[-5] = (k01_21)*A[0] + (k00_20) * A[1];
  1900. A += k1;
  1901. k00_20 = e0[-6] - e2[-6];
  1902. k01_21 = e0[-7] - e2[-7];
  1903. e0[-6] += e2[-6];//e0[-6] = e0[-6] + e2[-6];
  1904. e0[-7] += e2[-7];//e0[-7] = e0[-7] + e2[-7];
  1905. e2[-6] = (k00_20)*A[0] - (k01_21) * A[1];
  1906. e2[-7] = (k01_21)*A[0] + (k00_20) * A[1];
  1907. e0 -= 8;
  1908. e2 -= 8;
  1909. A += k1;
  1910. }
  1911. }
  1912. static void imdct_step3_inner_s_loop(int n, float *e, int i_off, int k_off, float *A, int a_off, int k0)
  1913. {
  1914. int i;
  1915. float A0 = A[0];
  1916. float A1 = A[0+1];
  1917. float A2 = A[0+a_off];
  1918. float A3 = A[0+a_off+1];
  1919. float A4 = A[0+a_off*2+0];
  1920. float A5 = A[0+a_off*2+1];
  1921. float A6 = A[0+a_off*3+0];
  1922. float A7 = A[0+a_off*3+1];
  1923. float k00,k11;
  1924. float *ee0 = e +i_off;
  1925. float *ee2 = ee0+k_off;
  1926. for (i=n; i > 0; --i) {
  1927. k00 = ee0[ 0] - ee2[ 0];
  1928. k11 = ee0[-1] - ee2[-1];
  1929. ee0[ 0] = ee0[ 0] + ee2[ 0];
  1930. ee0[-1] = ee0[-1] + ee2[-1];
  1931. ee2[ 0] = (k00) * A0 - (k11) * A1;
  1932. ee2[-1] = (k11) * A0 + (k00) * A1;
  1933. k00 = ee0[-2] - ee2[-2];
  1934. k11 = ee0[-3] - ee2[-3];
  1935. ee0[-2] = ee0[-2] + ee2[-2];
  1936. ee0[-3] = ee0[-3] + ee2[-3];
  1937. ee2[-2] = (k00) * A2 - (k11) * A3;
  1938. ee2[-3] = (k11) * A2 + (k00) * A3;
  1939. k00 = ee0[-4] - ee2[-4];
  1940. k11 = ee0[-5] - ee2[-5];
  1941. ee0[-4] = ee0[-4] + ee2[-4];
  1942. ee0[-5] = ee0[-5] + ee2[-5];
  1943. ee2[-4] = (k00) * A4 - (k11) * A5;
  1944. ee2[-5] = (k11) * A4 + (k00) * A5;
  1945. k00 = ee0[-6] - ee2[-6];
  1946. k11 = ee0[-7] - ee2[-7];
  1947. ee0[-6] = ee0[-6] + ee2[-6];
  1948. ee0[-7] = ee0[-7] + ee2[-7];
  1949. ee2[-6] = (k00) * A6 - (k11) * A7;
  1950. ee2[-7] = (k11) * A6 + (k00) * A7;
  1951. ee0 -= k0;
  1952. ee2 -= k0;
  1953. }
  1954. }
  1955. static __forceinline void iter_54(float *z)
  1956. {
  1957. float k00,k11,k22,k33;
  1958. float y0,y1,y2,y3;
  1959. k00 = z[ 0] - z[-4];
  1960. y0 = z[ 0] + z[-4];
  1961. y2 = z[-2] + z[-6];
  1962. k22 = z[-2] - z[-6];
  1963. z[-0] = y0 + y2; // z0 + z4 + z2 + z6
  1964. z[-2] = y0 - y2; // z0 + z4 - z2 - z6
  1965. // done with y0,y2
  1966. k33 = z[-3] - z[-7];
  1967. z[-4] = k00 + k33; // z0 - z4 + z3 - z7
  1968. z[-6] = k00 - k33; // z0 - z4 - z3 + z7
  1969. // done with k33
  1970. k11 = z[-1] - z[-5];
  1971. y1 = z[-1] + z[-5];
  1972. y3 = z[-3] + z[-7];
  1973. z[-1] = y1 + y3; // z1 + z5 + z3 + z7
  1974. z[-3] = y1 - y3; // z1 + z5 - z3 - z7
  1975. z[-5] = k11 - k22; // z1 - z5 + z2 - z6
  1976. z[-7] = k11 + k22; // z1 - z5 - z2 + z6
  1977. }
  1978. static void imdct_step3_inner_s_loop_ld654(int n, float *e, int i_off, float *A, int base_n)
  1979. {
  1980. int a_off = base_n >> 3;
  1981. float A2 = A[0+a_off];
  1982. float *z = e + i_off;
  1983. float *base = z - 16 * n;
  1984. while (z > base) {
  1985. float k00,k11;
  1986. k00 = z[-0] - z[-8];
  1987. k11 = z[-1] - z[-9];
  1988. z[-0] = z[-0] + z[-8];
  1989. z[-1] = z[-1] + z[-9];
  1990. z[-8] = k00;
  1991. z[-9] = k11 ;
  1992. k00 = z[ -2] - z[-10];
  1993. k11 = z[ -3] - z[-11];
  1994. z[ -2] = z[ -2] + z[-10];
  1995. z[ -3] = z[ -3] + z[-11];
  1996. z[-10] = (k00+k11) * A2;
  1997. z[-11] = (k11-k00) * A2;
  1998. k00 = z[-12] - z[ -4]; // reverse to avoid a unary negation
  1999. k11 = z[ -5] - z[-13];
  2000. z[ -4] = z[ -4] + z[-12];
  2001. z[ -5] = z[ -5] + z[-13];
  2002. z[-12] = k11;
  2003. z[-13] = k00;
  2004. k00 = z[-14] - z[ -6]; // reverse to avoid a unary negation
  2005. k11 = z[ -7] - z[-15];
  2006. z[ -6] = z[ -6] + z[-14];
  2007. z[ -7] = z[ -7] + z[-15];
  2008. z[-14] = (k00+k11) * A2;
  2009. z[-15] = (k00-k11) * A2;
  2010. iter_54(z);
  2011. iter_54(z-8);
  2012. z -= 16;
  2013. }
  2014. }
  2015. static void inverse_mdct(float *buffer, int n, vorb *f, int blocktype)
  2016. {
  2017. int n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  2018. int ld;
  2019. // @OPTIMIZE: reduce register pressure by using fewer variables?
  2020. int save_point = temp_alloc_save(f);
  2021. float *buf2 = (float *) temp_alloc(f, n2 * sizeof(*buf2));
  2022. float *u=NULL,*v=NULL;
  2023. // twiddle factors
  2024. float *A = f->A[blocktype];
  2025. // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
  2026. // See notes about bugs in that paper in less-optimal implementation 'inverse_mdct_old' after this function.
  2027. // kernel from paper
  2028. // merged:
  2029. // copy and reflect spectral data
  2030. // step 0
  2031. // note that it turns out that the items added together during
  2032. // this step are, in fact, being added to themselves (as reflected
  2033. // by step 0). inexplicable inefficiency! this became obvious
  2034. // once I combined the passes.
  2035. // so there's a missing 'times 2' here (for adding X to itself).
  2036. // this propogates through linearly to the end, where the numbers
  2037. // are 1/2 too small, and need to be compensated for.
  2038. {
  2039. float *d,*e, *AA, *e_stop;
  2040. d = &buf2[n2-2];
  2041. AA = A;
  2042. e = &buffer[0];
  2043. e_stop = &buffer[n2];
  2044. while (e != e_stop) {
  2045. d[1] = (e[0] * AA[0] - e[2]*AA[1]);
  2046. d[0] = (e[0] * AA[1] + e[2]*AA[0]);
  2047. d -= 2;
  2048. AA += 2;
  2049. e += 4;
  2050. }
  2051. e = &buffer[n2-3];
  2052. while (d >= buf2) {
  2053. d[1] = (-e[2] * AA[0] - -e[0]*AA[1]);
  2054. d[0] = (-e[2] * AA[1] + -e[0]*AA[0]);
  2055. d -= 2;
  2056. AA += 2;
  2057. e -= 4;
  2058. }
  2059. }
  2060. // now we use symbolic names for these, so that we can
  2061. // possibly swap their meaning as we change which operations
  2062. // are in place
  2063. u = buffer;
  2064. v = buf2;
  2065. // step 2 (paper output is w, now u)
  2066. // this could be in place, but the data ends up in the wrong
  2067. // place... _somebody_'s got to swap it, so this is nominated
  2068. {
  2069. float *AA = &A[n2-8];
  2070. float *d0,*d1, *e0, *e1;
  2071. e0 = &v[n4];
  2072. e1 = &v[0];
  2073. d0 = &u[n4];
  2074. d1 = &u[0];
  2075. while (AA >= A) {
  2076. float v40_20, v41_21;
  2077. v41_21 = e0[1] - e1[1];
  2078. v40_20 = e0[0] - e1[0];
  2079. d0[1] = e0[1] + e1[1];
  2080. d0[0] = e0[0] + e1[0];
  2081. d1[1] = v41_21*AA[4] - v40_20*AA[5];
  2082. d1[0] = v40_20*AA[4] + v41_21*AA[5];
  2083. v41_21 = e0[3] - e1[3];
  2084. v40_20 = e0[2] - e1[2];
  2085. d0[3] = e0[3] + e1[3];
  2086. d0[2] = e0[2] + e1[2];
  2087. d1[3] = v41_21*AA[0] - v40_20*AA[1];
  2088. d1[2] = v40_20*AA[0] + v41_21*AA[1];
  2089. AA -= 8;
  2090. d0 += 4;
  2091. d1 += 4;
  2092. e0 += 4;
  2093. e1 += 4;
  2094. }
  2095. }
  2096. // step 3
  2097. ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  2098. // optimized step 3:
  2099. // the original step3 loop can be nested r inside s or s inside r;
  2100. // it's written originally as s inside r, but this is dumb when r
  2101. // iterates many times, and s few. So I have two copies of it and
  2102. // switch between them halfway.
  2103. // this is iteration 0 of step 3
  2104. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*0, -(n >> 3), A);
  2105. imdct_step3_iter0_loop(n >> 4, u, n2-1-n4*1, -(n >> 3), A);
  2106. // this is iteration 1 of step 3
  2107. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*0, -(n >> 4), A, 16);
  2108. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*1, -(n >> 4), A, 16);
  2109. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*2, -(n >> 4), A, 16);
  2110. imdct_step3_inner_r_loop(n >> 5, u, n2-1 - n8*3, -(n >> 4), A, 16);
  2111. l=2;
  2112. for (; l < (ld-3)>>1; ++l) {
  2113. int k0 = n >> (l+2), k0_2 = k0>>1;
  2114. int lim = 1 << (l+1);
  2115. int i;
  2116. for (i=0; i < lim; ++i)
  2117. imdct_step3_inner_r_loop(n >> (l+4), u, n2-1 - k0*i, -k0_2, A, 1 << (l+3));
  2118. }
  2119. for (; l < ld-6; ++l) {
  2120. int k0 = n >> (l+2), k1 = 1 << (l+3), k0_2 = k0>>1;
  2121. int rlim = n >> (l+6), r;
  2122. int lim = 1 << (l+1);
  2123. int i_off;
  2124. float *A0 = A;
  2125. i_off = n2-1;
  2126. for (r=rlim; r > 0; --r) {
  2127. imdct_step3_inner_s_loop(lim, u, i_off, -k0_2, A0, k1, k0);
  2128. A0 += k1*4;
  2129. i_off -= 8;
  2130. }
  2131. }
  2132. // iterations with count:
  2133. // ld-6,-5,-4 all interleaved together
  2134. // the big win comes from getting rid of needless flops
  2135. // due to the constants on pass 5 & 4 being all 1 and 0;
  2136. // combining them to be simultaneous to improve cache made little difference
  2137. imdct_step3_inner_s_loop_ld654(n >> 5, u, n2-1, A, n);
  2138. // output is u
  2139. // step 4, 5, and 6
  2140. // cannot be in-place because of step 5
  2141. {
  2142. uint16 *bitrev = f->bit_reverse[blocktype];
  2143. // weirdly, I'd have thought reading sequentially and writing
  2144. // erratically would have been better than vice-versa, but in
  2145. // fact that's not what my testing showed. (That is, with
  2146. // j = bitreverse(i), do you read i and write j, or read j and write i.)
  2147. float *d0 = &v[n4-4];
  2148. float *d1 = &v[n2-4];
  2149. while (d0 >= v) {
  2150. int k4;
  2151. k4 = bitrev[0];
  2152. d1[3] = u[k4+0];
  2153. d1[2] = u[k4+1];
  2154. d0[3] = u[k4+2];
  2155. d0[2] = u[k4+3];
  2156. k4 = bitrev[1];
  2157. d1[1] = u[k4+0];
  2158. d1[0] = u[k4+1];
  2159. d0[1] = u[k4+2];
  2160. d0[0] = u[k4+3];
  2161. d0 -= 4;
  2162. d1 -= 4;
  2163. bitrev += 2;
  2164. }
  2165. }
  2166. // (paper output is u, now v)
  2167. // data must be in buf2
  2168. assert(v == buf2);
  2169. // step 7 (paper output is v, now v)
  2170. // this is now in place
  2171. {
  2172. float *C = f->C[blocktype];
  2173. float *d, *e;
  2174. d = v;
  2175. e = v + n2 - 4;
  2176. while (d < e) {
  2177. float a02,a11,b0,b1,b2,b3;
  2178. a02 = d[0] - e[2];
  2179. a11 = d[1] + e[3];
  2180. b0 = C[1]*a02 + C[0]*a11;
  2181. b1 = C[1]*a11 - C[0]*a02;
  2182. b2 = d[0] + e[ 2];
  2183. b3 = d[1] - e[ 3];
  2184. d[0] = b2 + b0;
  2185. d[1] = b3 + b1;
  2186. e[2] = b2 - b0;
  2187. e[3] = b1 - b3;
  2188. a02 = d[2] - e[0];
  2189. a11 = d[3] + e[1];
  2190. b0 = C[3]*a02 + C[2]*a11;
  2191. b1 = C[3]*a11 - C[2]*a02;
  2192. b2 = d[2] + e[ 0];
  2193. b3 = d[3] - e[ 1];
  2194. d[2] = b2 + b0;
  2195. d[3] = b3 + b1;
  2196. e[0] = b2 - b0;
  2197. e[1] = b1 - b3;
  2198. C += 4;
  2199. d += 4;
  2200. e -= 4;
  2201. }
  2202. }
  2203. // data must be in buf2
  2204. // step 8+decode (paper output is X, now buffer)
  2205. // this generates pairs of data a la 8 and pushes them directly through
  2206. // the decode kernel (pushing rather than pulling) to avoid having
  2207. // to make another pass later
  2208. // this cannot POSSIBLY be in place, so we refer to the buffers directly
  2209. {
  2210. float *d0,*d1,*d2,*d3;
  2211. float *B = f->B[blocktype] + n2 - 8;
  2212. float *e = buf2 + n2 - 8;
  2213. d0 = &buffer[0];
  2214. d1 = &buffer[n2-4];
  2215. d2 = &buffer[n2];
  2216. d3 = &buffer[n-4];
  2217. while (e >= v) {
  2218. float p0,p1,p2,p3;
  2219. p3 = e[6]*B[7] - e[7]*B[6];
  2220. p2 = -e[6]*B[6] - e[7]*B[7];
  2221. d0[0] = p3;
  2222. d1[3] = - p3;
  2223. d2[0] = p2;
  2224. d3[3] = p2;
  2225. p1 = e[4]*B[5] - e[5]*B[4];
  2226. p0 = -e[4]*B[4] - e[5]*B[5];
  2227. d0[1] = p1;
  2228. d1[2] = - p1;
  2229. d2[1] = p0;
  2230. d3[2] = p0;
  2231. p3 = e[2]*B[3] - e[3]*B[2];
  2232. p2 = -e[2]*B[2] - e[3]*B[3];
  2233. d0[2] = p3;
  2234. d1[1] = - p3;
  2235. d2[2] = p2;
  2236. d3[1] = p2;
  2237. p1 = e[0]*B[1] - e[1]*B[0];
  2238. p0 = -e[0]*B[0] - e[1]*B[1];
  2239. d0[3] = p1;
  2240. d1[0] = - p1;
  2241. d2[3] = p0;
  2242. d3[0] = p0;
  2243. B -= 8;
  2244. e -= 8;
  2245. d0 += 4;
  2246. d2 += 4;
  2247. d1 -= 4;
  2248. d3 -= 4;
  2249. }
  2250. }
  2251. temp_free(f,buf2);
  2252. temp_alloc_restore(f,save_point);
  2253. }
  2254. #if 0
  2255. // this is the original version of the above code, if you want to optimize it from scratch
  2256. void inverse_mdct_naive(float *buffer, int n)
  2257. {
  2258. float s;
  2259. float A[1 << 12], B[1 << 12], C[1 << 11];
  2260. int i,k,k2,k4, n2 = n >> 1, n4 = n >> 2, n8 = n >> 3, l;
  2261. int n3_4 = n - n4, ld;
  2262. // how can they claim this only uses N words?!
  2263. // oh, because they're only used sparsely, whoops
  2264. float u[1 << 13], X[1 << 13], v[1 << 13], w[1 << 13];
  2265. // set up twiddle factors
  2266. for (k=k2=0; k < n4; ++k,k2+=2) {
  2267. A[k2 ] = (float) cos(4*k*M_PI/n);
  2268. A[k2+1] = (float) -sin(4*k*M_PI/n);
  2269. B[k2 ] = (float) cos((k2+1)*M_PI/n/2);
  2270. B[k2+1] = (float) sin((k2+1)*M_PI/n/2);
  2271. }
  2272. for (k=k2=0; k < n8; ++k,k2+=2) {
  2273. C[k2 ] = (float) cos(2*(k2+1)*M_PI/n);
  2274. C[k2+1] = (float) -sin(2*(k2+1)*M_PI/n);
  2275. }
  2276. // IMDCT algorithm from "The use of multirate filter banks for coding of high quality digital audio"
  2277. // Note there are bugs in that pseudocode, presumably due to them attempting
  2278. // to rename the arrays nicely rather than representing the way their actual
  2279. // implementation bounces buffers back and forth. As a result, even in the
  2280. // "some formulars corrected" version, a direct implementation fails. These
  2281. // are noted below as "paper bug".
  2282. // copy and reflect spectral data
  2283. for (k=0; k < n2; ++k) u[k] = buffer[k];
  2284. for ( ; k < n ; ++k) u[k] = -buffer[n - k - 1];
  2285. // kernel from paper
  2286. // step 1
  2287. for (k=k2=k4=0; k < n4; k+=1, k2+=2, k4+=4) {
  2288. v[n-k4-1] = (u[k4] - u[n-k4-1]) * A[k2] - (u[k4+2] - u[n-k4-3])*A[k2+1];
  2289. v[n-k4-3] = (u[k4] - u[n-k4-1]) * A[k2+1] + (u[k4+2] - u[n-k4-3])*A[k2];
  2290. }
  2291. // step 2
  2292. for (k=k4=0; k < n8; k+=1, k4+=4) {
  2293. w[n2+3+k4] = v[n2+3+k4] + v[k4+3];
  2294. w[n2+1+k4] = v[n2+1+k4] + v[k4+1];
  2295. w[k4+3] = (v[n2+3+k4] - v[k4+3])*A[n2-4-k4] - (v[n2+1+k4]-v[k4+1])*A[n2-3-k4];
  2296. w[k4+1] = (v[n2+1+k4] - v[k4+1])*A[n2-4-k4] + (v[n2+3+k4]-v[k4+3])*A[n2-3-k4];
  2297. }
  2298. // step 3
  2299. ld = ilog(n) - 1; // ilog is off-by-one from normal definitions
  2300. for (l=0; l < ld-3; ++l) {
  2301. int k0 = n >> (l+2), k1 = 1 << (l+3);
  2302. int rlim = n >> (l+4), r4, r;
  2303. int s2lim = 1 << (l+2), s2;
  2304. for (r=r4=0; r < rlim; r4+=4,++r) {
  2305. for (s2=0; s2 < s2lim; s2+=2) {
  2306. u[n-1-k0*s2-r4] = w[n-1-k0*s2-r4] + w[n-1-k0*(s2+1)-r4];
  2307. u[n-3-k0*s2-r4] = w[n-3-k0*s2-r4] + w[n-3-k0*(s2+1)-r4];
  2308. u[n-1-k0*(s2+1)-r4] = (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1]
  2309. - (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1+1];
  2310. u[n-3-k0*(s2+1)-r4] = (w[n-3-k0*s2-r4] - w[n-3-k0*(s2+1)-r4]) * A[r*k1]
  2311. + (w[n-1-k0*s2-r4] - w[n-1-k0*(s2+1)-r4]) * A[r*k1+1];
  2312. }
  2313. }
  2314. if (l+1 < ld-3) {
  2315. // paper bug: ping-ponging of u&w here is omitted
  2316. memcpy(w, u, sizeof(u));
  2317. }
  2318. }
  2319. // step 4
  2320. for (i=0; i < n8; ++i) {
  2321. int j = bit_reverse(i) >> (32-ld+3);
  2322. assert(j < n8);
  2323. if (i == j) {
  2324. // paper bug: original code probably swapped in place; if copying,
  2325. // need to directly copy in this case
  2326. int i8 = i << 3;
  2327. v[i8+1] = u[i8+1];
  2328. v[i8+3] = u[i8+3];
  2329. v[i8+5] = u[i8+5];
  2330. v[i8+7] = u[i8+7];
  2331. } else if (i < j) {
  2332. int i8 = i << 3, j8 = j << 3;
  2333. v[j8+1] = u[i8+1], v[i8+1] = u[j8 + 1];
  2334. v[j8+3] = u[i8+3], v[i8+3] = u[j8 + 3];
  2335. v[j8+5] = u[i8+5], v[i8+5] = u[j8 + 5];
  2336. v[j8+7] = u[i8+7], v[i8+7] = u[j8 + 7];
  2337. }
  2338. }
  2339. // step 5
  2340. for (k=0; k < n2; ++k) {
  2341. w[k] = v[k*2+1];
  2342. }
  2343. // step 6
  2344. for (k=k2=k4=0; k < n8; ++k, k2 += 2, k4 += 4) {
  2345. u[n-1-k2] = w[k4];
  2346. u[n-2-k2] = w[k4+1];
  2347. u[n3_4 - 1 - k2] = w[k4+2];
  2348. u[n3_4 - 2 - k2] = w[k4+3];
  2349. }
  2350. // step 7
  2351. for (k=k2=0; k < n8; ++k, k2 += 2) {
  2352. v[n2 + k2 ] = ( u[n2 + k2] + u[n-2-k2] + C[k2+1]*(u[n2+k2]-u[n-2-k2]) + C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
  2353. v[n-2 - k2] = ( u[n2 + k2] + u[n-2-k2] - C[k2+1]*(u[n2+k2]-u[n-2-k2]) - C[k2]*(u[n2+k2+1]+u[n-2-k2+1]))/2;
  2354. v[n2+1+ k2] = ( u[n2+1+k2] - u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
  2355. v[n-1 - k2] = (-u[n2+1+k2] + u[n-1-k2] + C[k2+1]*(u[n2+1+k2]+u[n-1-k2]) - C[k2]*(u[n2+k2]-u[n-2-k2]))/2;
  2356. }
  2357. // step 8
  2358. for (k=k2=0; k < n4; ++k,k2 += 2) {
  2359. X[k] = v[k2+n2]*B[k2 ] + v[k2+1+n2]*B[k2+1];
  2360. X[n2-1-k] = v[k2+n2]*B[k2+1] - v[k2+1+n2]*B[k2 ];
  2361. }
  2362. // decode kernel to output
  2363. // determined the following value experimentally
  2364. // (by first figuring out what made inverse_mdct_slow work); then matching that here
  2365. // (probably vorbis encoder premultiplies by n or n/2, to save it on the decoder?)
  2366. s = 0.5; // theoretically would be n4
  2367. // [[[ note! the s value of 0.5 is compensated for by the B[] in the current code,
  2368. // so it needs to use the "old" B values to behave correctly, or else
  2369. // set s to 1.0 ]]]
  2370. for (i=0; i < n4 ; ++i) buffer[i] = s * X[i+n4];
  2371. for ( ; i < n3_4; ++i) buffer[i] = -s * X[n3_4 - i - 1];
  2372. for ( ; i < n ; ++i) buffer[i] = -s * X[i - n3_4];
  2373. }
  2374. #endif
  2375. static float *get_window(vorb *f, int len)
  2376. {
  2377. len <<= 1;
  2378. if (len == f->blocksize_0) return f->window[0];
  2379. if (len == f->blocksize_1) return f->window[1];
  2380. assert(0);
  2381. return NULL;
  2382. }
  2383. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2384. typedef int16 YTYPE;
  2385. #else
  2386. typedef int YTYPE;
  2387. #endif
  2388. static int do_floor(vorb *f, Mapping *map, int i, int n, float *target, YTYPE *finalY, uint8 *step2_flag)
  2389. {
  2390. int n2 = n >> 1;
  2391. int s = map->chan[i].mux, floor;
  2392. floor = map->submap_floor[s];
  2393. if (f->floor_types[floor] == 0) {
  2394. return error(f, VORBIS_invalid_stream);
  2395. } else {
  2396. Floor1 *g = &f->floor_config[floor].floor1;
  2397. int j,q;
  2398. int lx = 0, ly = finalY[0] * g->floor1_multiplier;
  2399. for (q=1; q < g->values; ++q) {
  2400. j = g->sorted_order[q];
  2401. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2402. if (finalY[j] >= 0)
  2403. #else
  2404. if (step2_flag[j])
  2405. #endif
  2406. {
  2407. int hy = finalY[j] * g->floor1_multiplier;
  2408. int hx = g->Xlist[j];
  2409. if (lx != hx)
  2410. draw_line(target, lx,ly, hx,hy, n2);
  2411. CHECK(f);
  2412. lx = hx, ly = hy;
  2413. }
  2414. }
  2415. if (lx < n2) {
  2416. // optimization of: draw_line(target, lx,ly, n,ly, n2);
  2417. for (j=lx; j < n2; ++j)
  2418. LINE_OP(target[j], inverse_db_table[ly]);
  2419. CHECK(f);
  2420. }
  2421. }
  2422. return TRUE;
  2423. }
  2424. // The meaning of "left" and "right"
  2425. //
  2426. // For a given frame:
  2427. // we compute samples from 0..n
  2428. // window_center is n/2
  2429. // we'll window and mix the samples from left_start to left_end with data from the previous frame
  2430. // all of the samples from left_end to right_start can be output without mixing; however,
  2431. // this interval is 0-length except when transitioning between short and long frames
  2432. // all of the samples from right_start to right_end need to be mixed with the next frame,
  2433. // which we don't have, so those get saved in a buffer
  2434. // frame N's right_end-right_start, the number of samples to mix with the next frame,
  2435. // has to be the same as frame N+1's left_end-left_start (which they are by
  2436. // construction)
  2437. static int vorbis_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
  2438. {
  2439. Mode *m;
  2440. int i, n, prev, next, window_center;
  2441. f->channel_buffer_start = f->channel_buffer_end = 0;
  2442. retry:
  2443. if (f->eof) return FALSE;
  2444. if (!maybe_start_packet(f))
  2445. return FALSE;
  2446. // check packet type
  2447. if (get_bits(f,1) != 0) {
  2448. if (IS_PUSH_MODE(f))
  2449. return error(f,VORBIS_bad_packet_type);
  2450. while (EOP != get8_packet(f));
  2451. goto retry;
  2452. }
  2453. if (f->alloc.alloc_buffer)
  2454. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2455. i = get_bits(f, ilog(f->mode_count-1));
  2456. if (i == EOP) return FALSE;
  2457. if (i >= f->mode_count) return FALSE;
  2458. *mode = i;
  2459. m = f->mode_config + i;
  2460. if (m->blockflag) {
  2461. n = f->blocksize_1;
  2462. prev = get_bits(f,1);
  2463. next = get_bits(f,1);
  2464. } else {
  2465. prev = next = 0;
  2466. n = f->blocksize_0;
  2467. }
  2468. // WINDOWING
  2469. window_center = n >> 1;
  2470. if (m->blockflag && !prev) {
  2471. *p_left_start = (n - f->blocksize_0) >> 2;
  2472. *p_left_end = (n + f->blocksize_0) >> 2;
  2473. } else {
  2474. *p_left_start = 0;
  2475. *p_left_end = window_center;
  2476. }
  2477. if (m->blockflag && !next) {
  2478. *p_right_start = (n*3 - f->blocksize_0) >> 2;
  2479. *p_right_end = (n*3 + f->blocksize_0) >> 2;
  2480. } else {
  2481. *p_right_start = window_center;
  2482. *p_right_end = n;
  2483. }
  2484. return TRUE;
  2485. }
  2486. static int vorbis_decode_packet_rest(vorb *f, int *len, Mode *m, int left_start, int left_end, int right_start, int right_end, int *p_left)
  2487. {
  2488. Mapping *map;
  2489. int i,j,k,n,n2;
  2490. int zero_channel[256];
  2491. int really_zero_channel[256];
  2492. // WINDOWING
  2493. n = f->blocksize[m->blockflag];
  2494. map = &f->mapping[m->mapping];
  2495. // FLOORS
  2496. n2 = n >> 1;
  2497. CHECK(f);
  2498. for (i=0; i < f->channels; ++i) {
  2499. int s = map->chan[i].mux, floor;
  2500. zero_channel[i] = FALSE;
  2501. floor = map->submap_floor[s];
  2502. if (f->floor_types[floor] == 0) {
  2503. return error(f, VORBIS_invalid_stream);
  2504. } else {
  2505. Floor1 *g = &f->floor_config[floor].floor1;
  2506. if (get_bits(f, 1)) {
  2507. short *finalY;
  2508. uint8 step2_flag[256];
  2509. static int range_list[4] = { 256, 128, 86, 64 };
  2510. int range = range_list[g->floor1_multiplier-1];
  2511. int offset = 2;
  2512. finalY = f->finalY[i];
  2513. finalY[0] = get_bits(f, ilog(range)-1);
  2514. finalY[1] = get_bits(f, ilog(range)-1);
  2515. for (j=0; j < g->partitions; ++j) {
  2516. int pclass = g->partition_class_list[j];
  2517. int cdim = g->class_dimensions[pclass];
  2518. int cbits = g->class_subclasses[pclass];
  2519. int csub = (1 << cbits)-1;
  2520. int cval = 0;
  2521. if (cbits) {
  2522. Codebook *c = f->codebooks + g->class_masterbooks[pclass];
  2523. DECODE(cval,f,c);
  2524. }
  2525. for (k=0; k < cdim; ++k) {
  2526. int book = g->subclass_books[pclass][cval & csub];
  2527. cval = cval >> cbits;
  2528. if (book >= 0) {
  2529. int temp;
  2530. Codebook *c = f->codebooks + book;
  2531. DECODE(temp,f,c);
  2532. finalY[offset++] = temp;
  2533. } else
  2534. finalY[offset++] = 0;
  2535. }
  2536. }
  2537. if (f->valid_bits == INVALID_BITS) goto error; // behavior according to spec
  2538. step2_flag[0] = step2_flag[1] = 1;
  2539. for (j=2; j < g->values; ++j) {
  2540. int low, high, pred, highroom, lowroom, room, val;
  2541. low = g->neighbors[j][0];
  2542. high = g->neighbors[j][1];
  2543. //neighbors(g->Xlist, j, &low, &high);
  2544. pred = predict_point(g->Xlist[j], g->Xlist[low], g->Xlist[high], finalY[low], finalY[high]);
  2545. val = finalY[j];
  2546. highroom = range - pred;
  2547. lowroom = pred;
  2548. if (highroom < lowroom)
  2549. room = highroom * 2;
  2550. else
  2551. room = lowroom * 2;
  2552. if (val) {
  2553. step2_flag[low] = step2_flag[high] = 1;
  2554. step2_flag[j] = 1;
  2555. if (val >= room)
  2556. if (highroom > lowroom)
  2557. finalY[j] = val - lowroom + pred;
  2558. else
  2559. finalY[j] = pred - val + highroom - 1;
  2560. else
  2561. if (val & 1)
  2562. finalY[j] = pred - ((val+1)>>1);
  2563. else
  2564. finalY[j] = pred + (val>>1);
  2565. } else {
  2566. step2_flag[j] = 0;
  2567. finalY[j] = pred;
  2568. }
  2569. }
  2570. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  2571. do_floor(f, map, i, n, f->floor_buffers[i], finalY, step2_flag);
  2572. #else
  2573. // defer final floor computation until _after_ residue
  2574. for (j=0; j < g->values; ++j) {
  2575. if (!step2_flag[j])
  2576. finalY[j] = -1;
  2577. }
  2578. #endif
  2579. } else {
  2580. error:
  2581. zero_channel[i] = TRUE;
  2582. }
  2583. // So we just defer everything else to later
  2584. // at this point we've decoded the floor into buffer
  2585. }
  2586. }
  2587. CHECK(f);
  2588. // at this point we've decoded all floors
  2589. if (f->alloc.alloc_buffer)
  2590. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2591. // re-enable coupled channels if necessary
  2592. memcpy(really_zero_channel, zero_channel, sizeof(really_zero_channel[0]) * f->channels);
  2593. for (i=0; i < map->coupling_steps; ++i)
  2594. if (!zero_channel[map->chan[i].magnitude] || !zero_channel[map->chan[i].angle]) {
  2595. zero_channel[map->chan[i].magnitude] = zero_channel[map->chan[i].angle] = FALSE;
  2596. }
  2597. CHECK(f);
  2598. // RESIDUE DECODE
  2599. for (i=0; i < map->submaps; ++i) {
  2600. float *residue_buffers[STB_VORBIS_MAX_CHANNELS];
  2601. int r;
  2602. uint8 do_not_decode[256];
  2603. int ch = 0;
  2604. for (j=0; j < f->channels; ++j) {
  2605. if (map->chan[j].mux == i) {
  2606. if (zero_channel[j]) {
  2607. do_not_decode[ch] = TRUE;
  2608. residue_buffers[ch] = NULL;
  2609. } else {
  2610. do_not_decode[ch] = FALSE;
  2611. residue_buffers[ch] = f->channel_buffers[j];
  2612. }
  2613. ++ch;
  2614. }
  2615. }
  2616. r = map->submap_residue[i];
  2617. decode_residue(f, residue_buffers, ch, n2, r, do_not_decode);
  2618. }
  2619. if (f->alloc.alloc_buffer)
  2620. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2621. CHECK(f);
  2622. // INVERSE COUPLING
  2623. for (i = map->coupling_steps-1; i >= 0; --i) {
  2624. int n2 = n >> 1;
  2625. float *m = f->channel_buffers[map->chan[i].magnitude];
  2626. float *a = f->channel_buffers[map->chan[i].angle ];
  2627. for (j=0; j < n2; ++j) {
  2628. float a2,m2;
  2629. if (m[j] > 0)
  2630. if (a[j] > 0)
  2631. m2 = m[j], a2 = m[j] - a[j];
  2632. else
  2633. a2 = m[j], m2 = m[j] + a[j];
  2634. else
  2635. if (a[j] > 0)
  2636. m2 = m[j], a2 = m[j] + a[j];
  2637. else
  2638. a2 = m[j], m2 = m[j] - a[j];
  2639. m[j] = m2;
  2640. a[j] = a2;
  2641. }
  2642. }
  2643. CHECK(f);
  2644. // finish decoding the floors
  2645. #ifndef STB_VORBIS_NO_DEFER_FLOOR
  2646. for (i=0; i < f->channels; ++i) {
  2647. if (really_zero_channel[i]) {
  2648. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  2649. } else {
  2650. do_floor(f, map, i, n, f->channel_buffers[i], f->finalY[i], NULL);
  2651. }
  2652. }
  2653. #else
  2654. for (i=0; i < f->channels; ++i) {
  2655. if (really_zero_channel[i]) {
  2656. memset(f->channel_buffers[i], 0, sizeof(*f->channel_buffers[i]) * n2);
  2657. } else {
  2658. for (j=0; j < n2; ++j)
  2659. f->channel_buffers[i][j] *= f->floor_buffers[i][j];
  2660. }
  2661. }
  2662. #endif
  2663. // INVERSE MDCT
  2664. CHECK(f);
  2665. for (i=0; i < f->channels; ++i)
  2666. inverse_mdct(f->channel_buffers[i], n, f, m->blockflag);
  2667. CHECK(f);
  2668. // this shouldn't be necessary, unless we exited on an error
  2669. // and want to flush to get to the next packet
  2670. flush_packet(f);
  2671. if (f->first_decode) {
  2672. // assume we start so first non-discarded sample is sample 0
  2673. // this isn't to spec, but spec would require us to read ahead
  2674. // and decode the size of all current frames--could be done,
  2675. // but presumably it's not a commonly used feature
  2676. f->current_loc = -n2; // start of first frame is positioned for discard
  2677. // we might have to discard samples "from" the next frame too,
  2678. // if we're lapping a large block then a small at the start?
  2679. f->discard_samples_deferred = n - right_end;
  2680. f->current_loc_valid = TRUE;
  2681. f->first_decode = FALSE;
  2682. } else if (f->discard_samples_deferred) {
  2683. if (f->discard_samples_deferred >= right_start - left_start) {
  2684. f->discard_samples_deferred -= (right_start - left_start);
  2685. left_start = right_start;
  2686. *p_left = left_start;
  2687. } else {
  2688. left_start += f->discard_samples_deferred;
  2689. *p_left = left_start;
  2690. f->discard_samples_deferred = 0;
  2691. }
  2692. } else if (f->previous_length == 0 && f->current_loc_valid) {
  2693. // we're recovering from a seek... that means we're going to discard
  2694. // the samples from this packet even though we know our position from
  2695. // the last page header, so we need to update the position based on
  2696. // the discarded samples here
  2697. // but wait, the code below is going to add this in itself even
  2698. // on a discard, so we don't need to do it here...
  2699. }
  2700. // check if we have ogg information about the sample # for this packet
  2701. if (f->last_seg_which == f->end_seg_with_known_loc) {
  2702. // if we have a valid current loc, and this is final:
  2703. if (f->current_loc_valid && (f->page_flag & PAGEFLAG_last_page)) {
  2704. uint32 current_end = f->known_loc_for_packet - (n-right_end);
  2705. // then let's infer the size of the (probably) short final frame
  2706. if (current_end < f->current_loc + (right_end-left_start)) {
  2707. if (current_end < f->current_loc) {
  2708. // negative truncation, that's impossible!
  2709. *len = 0;
  2710. } else {
  2711. *len = current_end - f->current_loc;
  2712. }
  2713. *len += left_start;
  2714. if (*len > right_end) *len = right_end; // this should never happen
  2715. f->current_loc += *len;
  2716. return TRUE;
  2717. }
  2718. }
  2719. // otherwise, just set our sample loc
  2720. // guess that the ogg granule pos refers to the _middle_ of the
  2721. // last frame?
  2722. // set f->current_loc to the position of left_start
  2723. f->current_loc = f->known_loc_for_packet - (n2-left_start);
  2724. f->current_loc_valid = TRUE;
  2725. }
  2726. if (f->current_loc_valid)
  2727. f->current_loc += (right_start - left_start);
  2728. if (f->alloc.alloc_buffer)
  2729. assert(f->alloc.alloc_buffer_length_in_bytes == f->temp_offset);
  2730. *len = right_end; // ignore samples after the window goes to 0
  2731. CHECK(f);
  2732. return TRUE;
  2733. }
  2734. static int vorbis_decode_packet(vorb *f, int *len, int *p_left, int *p_right)
  2735. {
  2736. int mode, left_end, right_end;
  2737. if (!vorbis_decode_initial(f, p_left, &left_end, p_right, &right_end, &mode)) return 0;
  2738. return vorbis_decode_packet_rest(f, len, f->mode_config + mode, *p_left, left_end, *p_right, right_end, p_left);
  2739. }
  2740. static int vorbis_finish_frame(stb_vorbis *f, int len, int left, int right)
  2741. {
  2742. int prev,i,j;
  2743. // we use right&left (the start of the right- and left-window sin()-regions)
  2744. // to determine how much to return, rather than inferring from the rules
  2745. // (same result, clearer code); 'left' indicates where our sin() window
  2746. // starts, therefore where the previous window's right edge starts, and
  2747. // therefore where to start mixing from the previous buffer. 'right'
  2748. // indicates where our sin() ending-window starts, therefore that's where
  2749. // we start saving, and where our returned-data ends.
  2750. // mixin from previous window
  2751. if (f->previous_length) {
  2752. int i,j, n = f->previous_length;
  2753. float *w = get_window(f, n);
  2754. for (i=0; i < f->channels; ++i) {
  2755. for (j=0; j < n; ++j)
  2756. f->channel_buffers[i][left+j] =
  2757. f->channel_buffers[i][left+j]*w[ j] +
  2758. f->previous_window[i][ j]*w[n-1-j];
  2759. }
  2760. }
  2761. prev = f->previous_length;
  2762. // last half of this data becomes previous window
  2763. f->previous_length = len - right;
  2764. // @OPTIMIZE: could avoid this copy by double-buffering the
  2765. // output (flipping previous_window with channel_buffers), but
  2766. // then previous_window would have to be 2x as large, and
  2767. // channel_buffers couldn't be temp mem (although they're NOT
  2768. // currently temp mem, they could be (unless we want to level
  2769. // performance by spreading out the computation))
  2770. for (i=0; i < f->channels; ++i)
  2771. for (j=0; right+j < len; ++j)
  2772. f->previous_window[i][j] = f->channel_buffers[i][right+j];
  2773. if (!prev)
  2774. // there was no previous packet, so this data isn't valid...
  2775. // this isn't entirely true, only the would-have-overlapped data
  2776. // isn't valid, but this seems to be what the spec requires
  2777. return 0;
  2778. // truncate a short frame
  2779. if (len < right) right = len;
  2780. f->samples_output += right-left;
  2781. return right - left;
  2782. }
  2783. static void vorbis_pump_first_frame(stb_vorbis *f)
  2784. {
  2785. int len, right, left;
  2786. if (vorbis_decode_packet(f, &len, &left, &right))
  2787. vorbis_finish_frame(f, len, left, right);
  2788. }
  2789. #ifndef STB_VORBIS_NO_PUSHDATA_API
  2790. static int is_whole_packet_present(stb_vorbis *f, int end_page)
  2791. {
  2792. // make sure that we have the packet available before continuing...
  2793. // this requires a full ogg parse, but we know we can fetch from f->stream
  2794. // instead of coding this out explicitly, we could save the current read state,
  2795. // read the next packet with get8() until end-of-packet, check f->eof, then
  2796. // reset the state? but that would be slower, esp. since we'd have over 256 bytes
  2797. // of state to restore (primarily the page segment table)
  2798. int s = f->next_seg, first = TRUE;
  2799. uint8 *p = f->stream;
  2800. if (s != -1) { // if we're not starting the packet with a 'continue on next page' flag
  2801. for (; s < f->segment_count; ++s) {
  2802. p += f->segments[s];
  2803. if (f->segments[s] < 255) // stop at first short segment
  2804. break;
  2805. }
  2806. // either this continues, or it ends it...
  2807. if (end_page)
  2808. if (s < f->segment_count-1) return error(f, VORBIS_invalid_stream);
  2809. if (s == f->segment_count)
  2810. s = -1; // set 'crosses page' flag
  2811. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  2812. first = FALSE;
  2813. }
  2814. for (; s == -1;) {
  2815. uint8 *q;
  2816. int n;
  2817. // check that we have the page header ready
  2818. if (p + 26 >= f->stream_end) return error(f, VORBIS_need_more_data);
  2819. // validate the page
  2820. if (memcmp(p, ogg_page_header, 4)) return error(f, VORBIS_invalid_stream);
  2821. if (p[4] != 0) return error(f, VORBIS_invalid_stream);
  2822. if (first) { // the first segment must NOT have 'continued_packet', later ones MUST
  2823. if (f->previous_length)
  2824. if ((p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
  2825. // if no previous length, we're resynching, so we can come in on a continued-packet,
  2826. // which we'll just drop
  2827. } else {
  2828. if (!(p[5] & PAGEFLAG_continued_packet)) return error(f, VORBIS_invalid_stream);
  2829. }
  2830. n = p[26]; // segment counts
  2831. q = p+27; // q points to segment table
  2832. p = q + n; // advance past header
  2833. // make sure we've read the segment table
  2834. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  2835. for (s=0; s < n; ++s) {
  2836. p += q[s];
  2837. if (q[s] < 255)
  2838. break;
  2839. }
  2840. if (end_page)
  2841. if (s < n-1) return error(f, VORBIS_invalid_stream);
  2842. if (s == n)
  2843. s = -1; // set 'crosses page' flag
  2844. if (p > f->stream_end) return error(f, VORBIS_need_more_data);
  2845. first = FALSE;
  2846. }
  2847. return TRUE;
  2848. }
  2849. #endif // !STB_VORBIS_NO_PUSHDATA_API
  2850. static int start_decoder(vorb *f)
  2851. {
  2852. uint8 header[6], x,y;
  2853. int len,i,j,k, max_submaps = 0;
  2854. int longest_floorlist=0;
  2855. // first page, first packet
  2856. if (!start_page(f)) return FALSE;
  2857. // validate page flag
  2858. if (!(f->page_flag & PAGEFLAG_first_page)) return error(f, VORBIS_invalid_first_page);
  2859. if (f->page_flag & PAGEFLAG_last_page) return error(f, VORBIS_invalid_first_page);
  2860. if (f->page_flag & PAGEFLAG_continued_packet) return error(f, VORBIS_invalid_first_page);
  2861. // check for expected packet length
  2862. if (f->segment_count != 1) return error(f, VORBIS_invalid_first_page);
  2863. if (f->segments[0] != 30) return error(f, VORBIS_invalid_first_page);
  2864. // read packet
  2865. // check packet header
  2866. if (get8(f) != VORBIS_packet_id) return error(f, VORBIS_invalid_first_page);
  2867. if (!getn(f, header, 6)) return error(f, VORBIS_unexpected_eof);
  2868. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_first_page);
  2869. // vorbis_version
  2870. if (get32(f) != 0) return error(f, VORBIS_invalid_first_page);
  2871. f->channels = get8(f); if (!f->channels) return error(f, VORBIS_invalid_first_page);
  2872. if (f->channels > STB_VORBIS_MAX_CHANNELS) return error(f, VORBIS_too_many_channels);
  2873. f->sample_rate = get32(f); if (!f->sample_rate) return error(f, VORBIS_invalid_first_page);
  2874. get32(f); // bitrate_maximum
  2875. get32(f); // bitrate_nominal
  2876. get32(f); // bitrate_minimum
  2877. x = get8(f);
  2878. {
  2879. int log0,log1;
  2880. log0 = x & 15;
  2881. log1 = x >> 4;
  2882. f->blocksize_0 = 1 << log0;
  2883. f->blocksize_1 = 1 << log1;
  2884. if (log0 < 6 || log0 > 13) return error(f, VORBIS_invalid_setup);
  2885. if (log1 < 6 || log1 > 13) return error(f, VORBIS_invalid_setup);
  2886. if (log0 > log1) return error(f, VORBIS_invalid_setup);
  2887. }
  2888. // framing_flag
  2889. x = get8(f);
  2890. if (!(x & 1)) return error(f, VORBIS_invalid_first_page);
  2891. // second packet!
  2892. if (!start_page(f)) return FALSE;
  2893. if (!start_packet(f)) return FALSE;
  2894. do {
  2895. len = next_segment(f);
  2896. skip(f, len);
  2897. f->bytes_in_seg = 0;
  2898. } while (len);
  2899. // third packet!
  2900. if (!start_packet(f)) return FALSE;
  2901. #ifndef STB_VORBIS_NO_PUSHDATA_API
  2902. if (IS_PUSH_MODE(f)) {
  2903. if (!is_whole_packet_present(f, TRUE)) {
  2904. // convert error in ogg header to write type
  2905. if (f->error == VORBIS_invalid_stream)
  2906. f->error = VORBIS_invalid_setup;
  2907. return FALSE;
  2908. }
  2909. }
  2910. #endif
  2911. crc32_init(); // always init it, to avoid multithread race conditions
  2912. if (get8_packet(f) != VORBIS_packet_setup) return error(f, VORBIS_invalid_setup);
  2913. for (i=0; i < 6; ++i) header[i] = get8_packet(f);
  2914. if (!vorbis_validate(header)) return error(f, VORBIS_invalid_setup);
  2915. // codebooks
  2916. f->codebook_count = get_bits(f,8) + 1;
  2917. f->codebooks = (Codebook *) setup_malloc(f, sizeof(*f->codebooks) * f->codebook_count);
  2918. if (f->codebooks == NULL) return error(f, VORBIS_outofmem);
  2919. memset(f->codebooks, 0, sizeof(*f->codebooks) * f->codebook_count);
  2920. for (i=0; i < f->codebook_count; ++i) {
  2921. uint32 *values;
  2922. int ordered, sorted_count;
  2923. int total=0;
  2924. uint8 *lengths;
  2925. Codebook *c = f->codebooks+i;
  2926. CHECK(f);
  2927. x = get_bits(f, 8); if (x != 0x42) return error(f, VORBIS_invalid_setup);
  2928. x = get_bits(f, 8); if (x != 0x43) return error(f, VORBIS_invalid_setup);
  2929. x = get_bits(f, 8); if (x != 0x56) return error(f, VORBIS_invalid_setup);
  2930. x = get_bits(f, 8);
  2931. c->dimensions = (get_bits(f, 8)<<8) + x;
  2932. x = get_bits(f, 8);
  2933. y = get_bits(f, 8);
  2934. c->entries = (get_bits(f, 8)<<16) + (y<<8) + x;
  2935. ordered = get_bits(f,1);
  2936. c->sparse = ordered ? 0 : get_bits(f,1);
  2937. if (c->dimensions == 0 && c->entries != 0) return error(f, VORBIS_invalid_setup);
  2938. if (c->sparse)
  2939. lengths = (uint8 *) setup_temp_malloc(f, c->entries);
  2940. else
  2941. lengths = c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  2942. if (!lengths) return error(f, VORBIS_outofmem);
  2943. if (ordered) {
  2944. int current_entry = 0;
  2945. int current_length = get_bits(f,5) + 1;
  2946. while (current_entry < c->entries) {
  2947. int limit = c->entries - current_entry;
  2948. int n = get_bits(f, ilog(limit));
  2949. if (current_entry + n > (int) c->entries) { return error(f, VORBIS_invalid_setup); }
  2950. memset(lengths + current_entry, current_length, n);
  2951. current_entry += n;
  2952. ++current_length;
  2953. }
  2954. } else {
  2955. for (j=0; j < c->entries; ++j) {
  2956. int present = c->sparse ? get_bits(f,1) : 1;
  2957. if (present) {
  2958. lengths[j] = get_bits(f, 5) + 1;
  2959. ++total;
  2960. if (lengths[j] == 32)
  2961. return error(f, VORBIS_invalid_setup);
  2962. } else {
  2963. lengths[j] = NO_CODE;
  2964. }
  2965. }
  2966. }
  2967. if (c->sparse && total >= c->entries >> 2) {
  2968. // convert sparse items to non-sparse!
  2969. if (c->entries > (int) f->setup_temp_memory_required)
  2970. f->setup_temp_memory_required = c->entries;
  2971. c->codeword_lengths = (uint8 *) setup_malloc(f, c->entries);
  2972. if (c->codeword_lengths == NULL) return error(f, VORBIS_outofmem);
  2973. memcpy(c->codeword_lengths, lengths, c->entries);
  2974. setup_temp_free(f, lengths, c->entries); // note this is only safe if there have been no intervening temp mallocs!
  2975. lengths = c->codeword_lengths;
  2976. c->sparse = 0;
  2977. }
  2978. // compute the size of the sorted tables
  2979. if (c->sparse) {
  2980. sorted_count = total;
  2981. } else {
  2982. sorted_count = 0;
  2983. #ifndef STB_VORBIS_NO_HUFFMAN_BINARY_SEARCH
  2984. for (j=0; j < c->entries; ++j)
  2985. if (lengths[j] > STB_VORBIS_FAST_HUFFMAN_LENGTH && lengths[j] != NO_CODE)
  2986. ++sorted_count;
  2987. #endif
  2988. }
  2989. c->sorted_entries = sorted_count;
  2990. values = NULL;
  2991. CHECK(f);
  2992. if (!c->sparse) {
  2993. c->codewords = (uint32 *) setup_malloc(f, sizeof(c->codewords[0]) * c->entries);
  2994. if (!c->codewords) return error(f, VORBIS_outofmem);
  2995. } else {
  2996. unsigned int size;
  2997. if (c->sorted_entries) {
  2998. c->codeword_lengths = (uint8 *) setup_malloc(f, c->sorted_entries);
  2999. if (!c->codeword_lengths) return error(f, VORBIS_outofmem);
  3000. c->codewords = (uint32 *) setup_temp_malloc(f, sizeof(*c->codewords) * c->sorted_entries);
  3001. if (!c->codewords) return error(f, VORBIS_outofmem);
  3002. values = (uint32 *) setup_temp_malloc(f, sizeof(*values) * c->sorted_entries);
  3003. if (!values) return error(f, VORBIS_outofmem);
  3004. }
  3005. size = c->entries + (sizeof(*c->codewords) + sizeof(*values)) * c->sorted_entries;
  3006. if (size > f->setup_temp_memory_required)
  3007. f->setup_temp_memory_required = size;
  3008. }
  3009. if (!compute_codewords(c, lengths, c->entries, values)) {
  3010. if (c->sparse) setup_temp_free(f, values, 0);
  3011. return error(f, VORBIS_invalid_setup);
  3012. }
  3013. if (c->sorted_entries) {
  3014. // allocate an extra slot for sentinels
  3015. c->sorted_codewords = (uint32 *) setup_malloc(f, sizeof(*c->sorted_codewords) * (c->sorted_entries+1));
  3016. if (c->sorted_codewords == NULL) return error(f, VORBIS_outofmem);
  3017. // allocate an extra slot at the front so that c->sorted_values[-1] is defined
  3018. // so that we can catch that case without an extra if
  3019. c->sorted_values = ( int *) setup_malloc(f, sizeof(*c->sorted_values ) * (c->sorted_entries+1));
  3020. if (c->sorted_values == NULL) return error(f, VORBIS_outofmem);
  3021. ++c->sorted_values;
  3022. c->sorted_values[-1] = -1;
  3023. compute_sorted_huffman(c, lengths, values);
  3024. }
  3025. if (c->sparse) {
  3026. setup_temp_free(f, values, sizeof(*values)*c->sorted_entries);
  3027. setup_temp_free(f, c->codewords, sizeof(*c->codewords)*c->sorted_entries);
  3028. setup_temp_free(f, lengths, c->entries);
  3029. c->codewords = NULL;
  3030. }
  3031. compute_accelerated_huffman(c);
  3032. CHECK(f);
  3033. c->lookup_type = get_bits(f, 4);
  3034. if (c->lookup_type > 2) return error(f, VORBIS_invalid_setup);
  3035. if (c->lookup_type > 0) {
  3036. uint16 *mults;
  3037. c->minimum_value = float32_unpack(get_bits(f, 32));
  3038. c->delta_value = float32_unpack(get_bits(f, 32));
  3039. c->value_bits = get_bits(f, 4)+1;
  3040. c->sequence_p = get_bits(f,1);
  3041. if (c->lookup_type == 1) {
  3042. c->lookup_values = lookup1_values(c->entries, c->dimensions);
  3043. } else {
  3044. c->lookup_values = c->entries * c->dimensions;
  3045. }
  3046. if (c->lookup_values == 0) return error(f, VORBIS_invalid_setup);
  3047. mults = (uint16 *) setup_temp_malloc(f, sizeof(mults[0]) * c->lookup_values);
  3048. if (mults == NULL) return error(f, VORBIS_outofmem);
  3049. for (j=0; j < (int) c->lookup_values; ++j) {
  3050. int q = get_bits(f, c->value_bits);
  3051. if (q == EOP) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_invalid_setup); }
  3052. mults[j] = q;
  3053. }
  3054. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3055. if (c->lookup_type == 1) {
  3056. int len, sparse = c->sparse;
  3057. float last=0;
  3058. // pre-expand the lookup1-style multiplicands, to avoid a divide in the inner loop
  3059. if (sparse) {
  3060. if (c->sorted_entries == 0) goto skip;
  3061. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->sorted_entries * c->dimensions);
  3062. } else
  3063. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->entries * c->dimensions);
  3064. if (c->multiplicands == NULL) { setup_temp_free(f,mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
  3065. len = sparse ? c->sorted_entries : c->entries;
  3066. for (j=0; j < len; ++j) {
  3067. unsigned int z = sparse ? c->sorted_values[j] : j;
  3068. unsigned int div=1;
  3069. for (k=0; k < c->dimensions; ++k) {
  3070. int off = (z / div) % c->lookup_values;
  3071. float val = mults[off];
  3072. val = mults[off]*c->delta_value + c->minimum_value + last;
  3073. c->multiplicands[j*c->dimensions + k] = val;
  3074. if (c->sequence_p)
  3075. last = val;
  3076. if (k+1 < c->dimensions) {
  3077. if (div > UINT_MAX / (unsigned int) c->lookup_values) {
  3078. setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values);
  3079. return error(f, VORBIS_invalid_setup);
  3080. }
  3081. div *= c->lookup_values;
  3082. }
  3083. }
  3084. }
  3085. c->lookup_type = 2;
  3086. }
  3087. else
  3088. #endif
  3089. {
  3090. float last=0;
  3091. CHECK(f);
  3092. c->multiplicands = (codetype *) setup_malloc(f, sizeof(c->multiplicands[0]) * c->lookup_values);
  3093. if (c->multiplicands == NULL) { setup_temp_free(f, mults,sizeof(mults[0])*c->lookup_values); return error(f, VORBIS_outofmem); }
  3094. for (j=0; j < (int) c->lookup_values; ++j) {
  3095. float val = mults[j] * c->delta_value + c->minimum_value + last;
  3096. c->multiplicands[j] = val;
  3097. if (c->sequence_p)
  3098. last = val;
  3099. }
  3100. }
  3101. #ifndef STB_VORBIS_DIVIDES_IN_CODEBOOK
  3102. skip:;
  3103. #endif
  3104. setup_temp_free(f, mults, sizeof(mults[0])*c->lookup_values);
  3105. CHECK(f);
  3106. }
  3107. CHECK(f);
  3108. }
  3109. // time domain transfers (notused)
  3110. x = get_bits(f, 6) + 1;
  3111. for (i=0; i < x; ++i) {
  3112. uint32 z = get_bits(f, 16);
  3113. if (z != 0) return error(f, VORBIS_invalid_setup);
  3114. }
  3115. // Floors
  3116. f->floor_count = get_bits(f, 6)+1;
  3117. f->floor_config = (Floor *) setup_malloc(f, f->floor_count * sizeof(*f->floor_config));
  3118. if (f->floor_config == NULL) return error(f, VORBIS_outofmem);
  3119. for (i=0; i < f->floor_count; ++i) {
  3120. f->floor_types[i] = get_bits(f, 16);
  3121. if (f->floor_types[i] > 1) return error(f, VORBIS_invalid_setup);
  3122. if (f->floor_types[i] == 0) {
  3123. Floor0 *g = &f->floor_config[i].floor0;
  3124. g->order = get_bits(f,8);
  3125. g->rate = get_bits(f,16);
  3126. g->bark_map_size = get_bits(f,16);
  3127. g->amplitude_bits = get_bits(f,6);
  3128. g->amplitude_offset = get_bits(f,8);
  3129. g->number_of_books = get_bits(f,4) + 1;
  3130. for (j=0; j < g->number_of_books; ++j)
  3131. g->book_list[j] = get_bits(f,8);
  3132. return error(f, VORBIS_feature_not_supported);
  3133. } else {
  3134. Point p[31*8+2];
  3135. Floor1 *g = &f->floor_config[i].floor1;
  3136. int max_class = -1;
  3137. g->partitions = get_bits(f, 5);
  3138. for (j=0; j < g->partitions; ++j) {
  3139. g->partition_class_list[j] = get_bits(f, 4);
  3140. if (g->partition_class_list[j] > max_class)
  3141. max_class = g->partition_class_list[j];
  3142. }
  3143. for (j=0; j <= max_class; ++j) {
  3144. g->class_dimensions[j] = get_bits(f, 3)+1;
  3145. g->class_subclasses[j] = get_bits(f, 2);
  3146. if (g->class_subclasses[j]) {
  3147. g->class_masterbooks[j] = get_bits(f, 8);
  3148. if (g->class_masterbooks[j] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3149. }
  3150. for (k=0; k < 1 << g->class_subclasses[j]; ++k) {
  3151. g->subclass_books[j][k] = get_bits(f,8)-1;
  3152. if (g->subclass_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3153. }
  3154. }
  3155. g->floor1_multiplier = get_bits(f,2)+1;
  3156. g->rangebits = get_bits(f,4);
  3157. g->Xlist[0] = 0;
  3158. g->Xlist[1] = 1 << g->rangebits;
  3159. g->values = 2;
  3160. for (j=0; j < g->partitions; ++j) {
  3161. int c = g->partition_class_list[j];
  3162. for (k=0; k < g->class_dimensions[c]; ++k) {
  3163. g->Xlist[g->values] = get_bits(f, g->rangebits);
  3164. ++g->values;
  3165. }
  3166. }
  3167. // precompute the sorting
  3168. for (j=0; j < g->values; ++j) {
  3169. p[j].x = g->Xlist[j];
  3170. p[j].y = j;
  3171. }
  3172. qsort(p, g->values, sizeof(p[0]), point_compare);
  3173. for (j=0; j < g->values; ++j)
  3174. g->sorted_order[j] = (uint8) p[j].y;
  3175. // precompute the neighbors
  3176. for (j=2; j < g->values; ++j) {
  3177. int low,hi;
  3178. neighbors(g->Xlist, j, &low,&hi);
  3179. g->neighbors[j][0] = low;
  3180. g->neighbors[j][1] = hi;
  3181. }
  3182. if (g->values > longest_floorlist)
  3183. longest_floorlist = g->values;
  3184. }
  3185. }
  3186. // Residue
  3187. f->residue_count = get_bits(f, 6)+1;
  3188. f->residue_config = (Residue *) setup_malloc(f, f->residue_count * sizeof(f->residue_config[0]));
  3189. if (f->residue_config == NULL) return error(f, VORBIS_outofmem);
  3190. memset(f->residue_config, 0, f->residue_count * sizeof(f->residue_config[0]));
  3191. for (i=0; i < f->residue_count; ++i) {
  3192. uint8 residue_cascade[64];
  3193. Residue *r = f->residue_config+i;
  3194. f->residue_types[i] = get_bits(f, 16);
  3195. if (f->residue_types[i] > 2) return error(f, VORBIS_invalid_setup);
  3196. r->begin = get_bits(f, 24);
  3197. r->end = get_bits(f, 24);
  3198. if (r->end < r->begin) return error(f, VORBIS_invalid_setup);
  3199. r->part_size = get_bits(f,24)+1;
  3200. r->classifications = get_bits(f,6)+1;
  3201. r->classbook = get_bits(f,8);
  3202. if (r->classbook >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3203. for (j=0; j < r->classifications; ++j) {
  3204. uint8 high_bits=0;
  3205. uint8 low_bits=get_bits(f,3);
  3206. if (get_bits(f,1))
  3207. high_bits = get_bits(f,5);
  3208. residue_cascade[j] = high_bits*8 + low_bits;
  3209. }
  3210. r->residue_books = (short (*)[8]) setup_malloc(f, sizeof(r->residue_books[0]) * r->classifications);
  3211. if (r->residue_books == NULL) return error(f, VORBIS_outofmem);
  3212. for (j=0; j < r->classifications; ++j) {
  3213. for (k=0; k < 8; ++k) {
  3214. if (residue_cascade[j] & (1 << k)) {
  3215. r->residue_books[j][k] = get_bits(f, 8);
  3216. if (r->residue_books[j][k] >= f->codebook_count) return error(f, VORBIS_invalid_setup);
  3217. } else {
  3218. r->residue_books[j][k] = -1;
  3219. }
  3220. }
  3221. }
  3222. // precompute the classifications[] array to avoid inner-loop mod/divide
  3223. // call it 'classdata' since we already have r->classifications
  3224. r->classdata = (uint8 **) setup_malloc(f, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  3225. if (!r->classdata) return error(f, VORBIS_outofmem);
  3226. memset(r->classdata, 0, sizeof(*r->classdata) * f->codebooks[r->classbook].entries);
  3227. for (j=0; j < f->codebooks[r->classbook].entries; ++j) {
  3228. int classwords = f->codebooks[r->classbook].dimensions;
  3229. int temp = j;
  3230. r->classdata[j] = (uint8 *) setup_malloc(f, sizeof(r->classdata[j][0]) * classwords);
  3231. if (r->classdata[j] == NULL) return error(f, VORBIS_outofmem);
  3232. for (k=classwords-1; k >= 0; --k) {
  3233. r->classdata[j][k] = temp % r->classifications;
  3234. temp /= r->classifications;
  3235. }
  3236. }
  3237. }
  3238. f->mapping_count = get_bits(f,6)+1;
  3239. f->mapping = (Mapping *) setup_malloc(f, f->mapping_count * sizeof(*f->mapping));
  3240. if (f->mapping == NULL) return error(f, VORBIS_outofmem);
  3241. memset(f->mapping, 0, f->mapping_count * sizeof(*f->mapping));
  3242. for (i=0; i < f->mapping_count; ++i) {
  3243. Mapping *m = f->mapping + i;
  3244. int mapping_type = get_bits(f,16);
  3245. if (mapping_type != 0) return error(f, VORBIS_invalid_setup);
  3246. m->chan = (MappingChannel *) setup_malloc(f, f->channels * sizeof(*m->chan));
  3247. if (m->chan == NULL) return error(f, VORBIS_outofmem);
  3248. if (get_bits(f,1))
  3249. m->submaps = get_bits(f,4)+1;
  3250. else
  3251. m->submaps = 1;
  3252. if (m->submaps > max_submaps)
  3253. max_submaps = m->submaps;
  3254. if (get_bits(f,1)) {
  3255. m->coupling_steps = get_bits(f,8)+1;
  3256. for (k=0; k < m->coupling_steps; ++k) {
  3257. m->chan[k].magnitude = get_bits(f, ilog(f->channels-1));
  3258. m->chan[k].angle = get_bits(f, ilog(f->channels-1));
  3259. if (m->chan[k].magnitude >= f->channels) return error(f, VORBIS_invalid_setup);
  3260. if (m->chan[k].angle >= f->channels) return error(f, VORBIS_invalid_setup);
  3261. if (m->chan[k].magnitude == m->chan[k].angle) return error(f, VORBIS_invalid_setup);
  3262. }
  3263. } else
  3264. m->coupling_steps = 0;
  3265. // reserved field
  3266. if (get_bits(f,2)) return error(f, VORBIS_invalid_setup);
  3267. if (m->submaps > 1) {
  3268. for (j=0; j < f->channels; ++j) {
  3269. m->chan[j].mux = get_bits(f, 4);
  3270. if (m->chan[j].mux >= m->submaps) return error(f, VORBIS_invalid_setup);
  3271. }
  3272. } else
  3273. // @SPECIFICATION: this case is missing from the spec
  3274. for (j=0; j < f->channels; ++j)
  3275. m->chan[j].mux = 0;
  3276. for (j=0; j < m->submaps; ++j) {
  3277. get_bits(f,8); // discard
  3278. m->submap_floor[j] = get_bits(f,8);
  3279. m->submap_residue[j] = get_bits(f,8);
  3280. if (m->submap_floor[j] >= f->floor_count) return error(f, VORBIS_invalid_setup);
  3281. if (m->submap_residue[j] >= f->residue_count) return error(f, VORBIS_invalid_setup);
  3282. }
  3283. }
  3284. // Modes
  3285. f->mode_count = get_bits(f, 6)+1;
  3286. for (i=0; i < f->mode_count; ++i) {
  3287. Mode *m = f->mode_config+i;
  3288. m->blockflag = get_bits(f,1);
  3289. m->windowtype = get_bits(f,16);
  3290. m->transformtype = get_bits(f,16);
  3291. m->mapping = get_bits(f,8);
  3292. if (m->windowtype != 0) return error(f, VORBIS_invalid_setup);
  3293. if (m->transformtype != 0) return error(f, VORBIS_invalid_setup);
  3294. if (m->mapping >= f->mapping_count) return error(f, VORBIS_invalid_setup);
  3295. }
  3296. flush_packet(f);
  3297. f->previous_length = 0;
  3298. for (i=0; i < f->channels; ++i) {
  3299. f->channel_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1);
  3300. f->previous_window[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  3301. f->finalY[i] = (int16 *) setup_malloc(f, sizeof(int16) * longest_floorlist);
  3302. if (f->channel_buffers[i] == NULL || f->previous_window[i] == NULL || f->finalY[i] == NULL) return error(f, VORBIS_outofmem);
  3303. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  3304. f->floor_buffers[i] = (float *) setup_malloc(f, sizeof(float) * f->blocksize_1/2);
  3305. if (f->floor_buffers[i] == NULL) return error(f, VORBIS_outofmem);
  3306. #endif
  3307. }
  3308. if (!init_blocksize(f, 0, f->blocksize_0)) return FALSE;
  3309. if (!init_blocksize(f, 1, f->blocksize_1)) return FALSE;
  3310. f->blocksize[0] = f->blocksize_0;
  3311. f->blocksize[1] = f->blocksize_1;
  3312. #ifdef STB_VORBIS_DIVIDE_TABLE
  3313. if (integer_divide_table[1][1]==0)
  3314. for (i=0; i < DIVTAB_NUMER; ++i)
  3315. for (j=1; j < DIVTAB_DENOM; ++j)
  3316. integer_divide_table[i][j] = i / j;
  3317. #endif
  3318. // compute how much temporary memory is needed
  3319. // 1.
  3320. {
  3321. uint32 imdct_mem = (f->blocksize_1 * sizeof(float) >> 1);
  3322. uint32 classify_mem;
  3323. int i,max_part_read=0;
  3324. for (i=0; i < f->residue_count; ++i) {
  3325. Residue *r = f->residue_config + i;
  3326. int n_read = r->end - r->begin;
  3327. int part_read = n_read / r->part_size;
  3328. if (part_read > max_part_read)
  3329. max_part_read = part_read;
  3330. }
  3331. #ifndef STB_VORBIS_DIVIDES_IN_RESIDUE
  3332. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(uint8 *));
  3333. #else
  3334. classify_mem = f->channels * (sizeof(void*) + max_part_read * sizeof(int *));
  3335. #endif
  3336. f->temp_memory_required = classify_mem;
  3337. if (imdct_mem > f->temp_memory_required)
  3338. f->temp_memory_required = imdct_mem;
  3339. }
  3340. f->first_decode = TRUE;
  3341. if (f->alloc.alloc_buffer) {
  3342. assert(f->temp_offset == f->alloc.alloc_buffer_length_in_bytes);
  3343. // check if there's enough temp memory so we don't error later
  3344. if (f->setup_offset + sizeof(*f) + f->temp_memory_required > (unsigned) f->temp_offset)
  3345. return error(f, VORBIS_outofmem);
  3346. }
  3347. f->first_audio_page_offset = stb_vorbis_get_file_offset(f);
  3348. return TRUE;
  3349. }
  3350. static void vorbis_deinit(stb_vorbis *p)
  3351. {
  3352. int i,j;
  3353. if (p->residue_config) {
  3354. for (i=0; i < p->residue_count; ++i) {
  3355. Residue *r = p->residue_config+i;
  3356. if (r->classdata) {
  3357. for (j=0; j < p->codebooks[r->classbook].entries; ++j)
  3358. setup_free(p, r->classdata[j]);
  3359. setup_free(p, r->classdata);
  3360. }
  3361. setup_free(p, r->residue_books);
  3362. }
  3363. }
  3364. if (p->codebooks) {
  3365. CHECK(p);
  3366. for (i=0; i < p->codebook_count; ++i) {
  3367. Codebook *c = p->codebooks + i;
  3368. setup_free(p, c->codeword_lengths);
  3369. setup_free(p, c->multiplicands);
  3370. setup_free(p, c->codewords);
  3371. setup_free(p, c->sorted_codewords);
  3372. // c->sorted_values[-1] is the first entry in the array
  3373. setup_free(p, c->sorted_values ? c->sorted_values-1 : NULL);
  3374. }
  3375. setup_free(p, p->codebooks);
  3376. }
  3377. setup_free(p, p->floor_config);
  3378. setup_free(p, p->residue_config);
  3379. if (p->mapping) {
  3380. for (i=0; i < p->mapping_count; ++i)
  3381. setup_free(p, p->mapping[i].chan);
  3382. setup_free(p, p->mapping);
  3383. }
  3384. CHECK(p);
  3385. for (i=0; i < p->channels && i < STB_VORBIS_MAX_CHANNELS; ++i) {
  3386. setup_free(p, p->channel_buffers[i]);
  3387. setup_free(p, p->previous_window[i]);
  3388. #ifdef STB_VORBIS_NO_DEFER_FLOOR
  3389. setup_free(p, p->floor_buffers[i]);
  3390. #endif
  3391. setup_free(p, p->finalY[i]);
  3392. }
  3393. for (i=0; i < 2; ++i) {
  3394. setup_free(p, p->A[i]);
  3395. setup_free(p, p->B[i]);
  3396. setup_free(p, p->C[i]);
  3397. setup_free(p, p->window[i]);
  3398. setup_free(p, p->bit_reverse[i]);
  3399. }
  3400. #ifndef STB_VORBIS_NO_STDIO
  3401. if (p->close_on_free) fclose(p->f);
  3402. #endif
  3403. }
  3404. void stb_vorbis_close(stb_vorbis *p)
  3405. {
  3406. if (p == NULL) return;
  3407. vorbis_deinit(p);
  3408. setup_free(p,p);
  3409. }
  3410. static void vorbis_init(stb_vorbis *p, const stb_vorbis_alloc *z)
  3411. {
  3412. memset(p, 0, sizeof(*p)); // NULL out all malloc'd pointers to start
  3413. if (z) {
  3414. p->alloc = *z;
  3415. p->alloc.alloc_buffer_length_in_bytes = (p->alloc.alloc_buffer_length_in_bytes+3) & ~3;
  3416. p->temp_offset = p->alloc.alloc_buffer_length_in_bytes;
  3417. }
  3418. p->eof = 0;
  3419. p->error = VORBIS__no_error;
  3420. p->stream = NULL;
  3421. p->codebooks = NULL;
  3422. p->page_crc_tests = -1;
  3423. #ifndef STB_VORBIS_NO_STDIO
  3424. p->close_on_free = FALSE;
  3425. p->f = NULL;
  3426. #endif
  3427. }
  3428. int stb_vorbis_get_sample_offset(stb_vorbis *f)
  3429. {
  3430. if (f->current_loc_valid)
  3431. return f->current_loc;
  3432. else
  3433. return -1;
  3434. }
  3435. stb_vorbis_info stb_vorbis_get_info(stb_vorbis *f)
  3436. {
  3437. stb_vorbis_info d;
  3438. d.channels = f->channels;
  3439. d.sample_rate = f->sample_rate;
  3440. d.setup_memory_required = f->setup_memory_required;
  3441. d.setup_temp_memory_required = f->setup_temp_memory_required;
  3442. d.temp_memory_required = f->temp_memory_required;
  3443. d.max_frame_size = f->blocksize_1 >> 1;
  3444. return d;
  3445. }
  3446. int stb_vorbis_get_error(stb_vorbis *f)
  3447. {
  3448. int e = f->error;
  3449. f->error = VORBIS__no_error;
  3450. return e;
  3451. }
  3452. static stb_vorbis * vorbis_alloc(stb_vorbis *f)
  3453. {
  3454. stb_vorbis *p = (stb_vorbis *) setup_malloc(f, sizeof(*p));
  3455. return p;
  3456. }
  3457. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3458. void stb_vorbis_flush_pushdata(stb_vorbis *f)
  3459. {
  3460. f->previous_length = 0;
  3461. f->page_crc_tests = 0;
  3462. f->discard_samples_deferred = 0;
  3463. f->current_loc_valid = FALSE;
  3464. f->first_decode = FALSE;
  3465. f->samples_output = 0;
  3466. f->channel_buffer_start = 0;
  3467. f->channel_buffer_end = 0;
  3468. }
  3469. static int vorbis_search_for_page_pushdata(vorb *f, uint8 *data, int data_len)
  3470. {
  3471. int i,n;
  3472. for (i=0; i < f->page_crc_tests; ++i)
  3473. f->scan[i].bytes_done = 0;
  3474. // if we have room for more scans, search for them first, because
  3475. // they may cause us to stop early if their header is incomplete
  3476. if (f->page_crc_tests < STB_VORBIS_PUSHDATA_CRC_COUNT) {
  3477. if (data_len < 4) return 0;
  3478. data_len -= 3; // need to look for 4-byte sequence, so don't miss
  3479. // one that straddles a boundary
  3480. for (i=0; i < data_len; ++i) {
  3481. if (data[i] == 0x4f) {
  3482. if (0==memcmp(data+i, ogg_page_header, 4)) {
  3483. int j,len;
  3484. uint32 crc;
  3485. // make sure we have the whole page header
  3486. if (i+26 >= data_len || i+27+data[i+26] >= data_len) {
  3487. // only read up to this page start, so hopefully we'll
  3488. // have the whole page header start next time
  3489. data_len = i;
  3490. break;
  3491. }
  3492. // ok, we have it all; compute the length of the page
  3493. len = 27 + data[i+26];
  3494. for (j=0; j < data[i+26]; ++j)
  3495. len += data[i+27+j];
  3496. // scan everything up to the embedded crc (which we must 0)
  3497. crc = 0;
  3498. for (j=0; j < 22; ++j)
  3499. crc = crc32_update(crc, data[i+j]);
  3500. // now process 4 0-bytes
  3501. for ( ; j < 26; ++j)
  3502. crc = crc32_update(crc, 0);
  3503. // len is the total number of bytes we need to scan
  3504. n = f->page_crc_tests++;
  3505. f->scan[n].bytes_left = len-j;
  3506. f->scan[n].crc_so_far = crc;
  3507. f->scan[n].goal_crc = data[i+22] + (data[i+23] << 8) + (data[i+24]<<16) + (data[i+25]<<24);
  3508. // if the last frame on a page is continued to the next, then
  3509. // we can't recover the sample_loc immediately
  3510. if (data[i+27+data[i+26]-1] == 255)
  3511. f->scan[n].sample_loc = ~0;
  3512. else
  3513. f->scan[n].sample_loc = data[i+6] + (data[i+7] << 8) + (data[i+ 8]<<16) + (data[i+ 9]<<24);
  3514. f->scan[n].bytes_done = i+j;
  3515. if (f->page_crc_tests == STB_VORBIS_PUSHDATA_CRC_COUNT)
  3516. break;
  3517. // keep going if we still have room for more
  3518. }
  3519. }
  3520. }
  3521. }
  3522. for (i=0; i < f->page_crc_tests;) {
  3523. uint32 crc;
  3524. int j;
  3525. int n = f->scan[i].bytes_done;
  3526. int m = f->scan[i].bytes_left;
  3527. if (m > data_len - n) m = data_len - n;
  3528. // m is the bytes to scan in the current chunk
  3529. crc = f->scan[i].crc_so_far;
  3530. for (j=0; j < m; ++j)
  3531. crc = crc32_update(crc, data[n+j]);
  3532. f->scan[i].bytes_left -= m;
  3533. f->scan[i].crc_so_far = crc;
  3534. if (f->scan[i].bytes_left == 0) {
  3535. // does it match?
  3536. if (f->scan[i].crc_so_far == f->scan[i].goal_crc) {
  3537. // Houston, we have page
  3538. data_len = n+m; // consumption amount is wherever that scan ended
  3539. f->page_crc_tests = -1; // drop out of page scan mode
  3540. f->previous_length = 0; // decode-but-don't-output one frame
  3541. f->next_seg = -1; // start a new page
  3542. f->current_loc = f->scan[i].sample_loc; // set the current sample location
  3543. // to the amount we'd have decoded had we decoded this page
  3544. f->current_loc_valid = f->current_loc != ~0U;
  3545. return data_len;
  3546. }
  3547. // delete entry
  3548. f->scan[i] = f->scan[--f->page_crc_tests];
  3549. } else {
  3550. ++i;
  3551. }
  3552. }
  3553. return data_len;
  3554. }
  3555. // return value: number of bytes we used
  3556. int stb_vorbis_decode_frame_pushdata(
  3557. stb_vorbis *f, // the file we're decoding
  3558. const uint8 *data, int data_len, // the memory available for decoding
  3559. int *channels, // place to write number of float * buffers
  3560. float ***output, // place to write float ** array of float * buffers
  3561. int *samples // place to write number of output samples
  3562. )
  3563. {
  3564. int i;
  3565. int len,right,left;
  3566. if (!IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  3567. if (f->page_crc_tests >= 0) {
  3568. *samples = 0;
  3569. return vorbis_search_for_page_pushdata(f, (uint8 *) data, data_len);
  3570. }
  3571. f->stream = (uint8 *) data;
  3572. f->stream_end = (uint8 *) data + data_len;
  3573. f->error = VORBIS__no_error;
  3574. // check that we have the entire packet in memory
  3575. if (!is_whole_packet_present(f, FALSE)) {
  3576. *samples = 0;
  3577. return 0;
  3578. }
  3579. if (!vorbis_decode_packet(f, &len, &left, &right)) {
  3580. // save the actual error we encountered
  3581. enum STBVorbisError error = f->error;
  3582. if (error == VORBIS_bad_packet_type) {
  3583. // flush and resynch
  3584. f->error = VORBIS__no_error;
  3585. while (get8_packet(f) != EOP)
  3586. if (f->eof) break;
  3587. *samples = 0;
  3588. return (int) (f->stream - data);
  3589. }
  3590. if (error == VORBIS_continued_packet_flag_invalid) {
  3591. if (f->previous_length == 0) {
  3592. // we may be resynching, in which case it's ok to hit one
  3593. // of these; just discard the packet
  3594. f->error = VORBIS__no_error;
  3595. while (get8_packet(f) != EOP)
  3596. if (f->eof) break;
  3597. *samples = 0;
  3598. return (int) (f->stream - data);
  3599. }
  3600. }
  3601. // if we get an error while parsing, what to do?
  3602. // well, it DEFINITELY won't work to continue from where we are!
  3603. stb_vorbis_flush_pushdata(f);
  3604. // restore the error that actually made us bail
  3605. f->error = error;
  3606. *samples = 0;
  3607. return 1;
  3608. }
  3609. // success!
  3610. len = vorbis_finish_frame(f, len, left, right);
  3611. for (i=0; i < f->channels; ++i)
  3612. f->outputs[i] = f->channel_buffers[i] + left;
  3613. if (channels) *channels = f->channels;
  3614. *samples = len;
  3615. *output = f->outputs;
  3616. return (int) (f->stream - data);
  3617. }
  3618. stb_vorbis *stb_vorbis_open_pushdata(
  3619. const unsigned char *data, int data_len, // the memory available for decoding
  3620. int *data_used, // only defined if result is not NULL
  3621. int *error, const stb_vorbis_alloc *alloc)
  3622. {
  3623. stb_vorbis *f, p;
  3624. vorbis_init(&p, alloc);
  3625. p.stream = (uint8 *) data;
  3626. p.stream_end = (uint8 *) data + data_len;
  3627. p.push_mode = TRUE;
  3628. if (!start_decoder(&p)) {
  3629. if (p.eof)
  3630. *error = VORBIS_need_more_data;
  3631. else
  3632. *error = p.error;
  3633. return NULL;
  3634. }
  3635. f = vorbis_alloc(&p);
  3636. if (f) {
  3637. *f = p;
  3638. *data_used = (int) (f->stream - data);
  3639. *error = 0;
  3640. return f;
  3641. } else {
  3642. vorbis_deinit(&p);
  3643. return NULL;
  3644. }
  3645. }
  3646. #endif // STB_VORBIS_NO_PUSHDATA_API
  3647. unsigned int stb_vorbis_get_file_offset(stb_vorbis *f)
  3648. {
  3649. #ifndef STB_VORBIS_NO_PUSHDATA_API
  3650. if (f->push_mode) return 0;
  3651. #endif
  3652. if (USE_MEMORY(f)) return (unsigned int) (f->stream - f->stream_start);
  3653. #ifndef STB_VORBIS_NO_STDIO
  3654. return (unsigned int) (ftell(f->f) - f->f_start);
  3655. #endif
  3656. }
  3657. #ifndef STB_VORBIS_NO_PULLDATA_API
  3658. //
  3659. // DATA-PULLING API
  3660. //
  3661. static uint32 vorbis_find_page(stb_vorbis *f, uint32 *end, uint32 *last)
  3662. {
  3663. for(;;) {
  3664. int n;
  3665. if (f->eof) return 0;
  3666. n = get8(f);
  3667. if (n == 0x4f) { // page header candidate
  3668. unsigned int retry_loc = stb_vorbis_get_file_offset(f);
  3669. int i;
  3670. // check if we're off the end of a file_section stream
  3671. if (retry_loc - 25 > f->stream_len)
  3672. return 0;
  3673. // check the rest of the header
  3674. for (i=1; i < 4; ++i)
  3675. if (get8(f) != ogg_page_header[i])
  3676. break;
  3677. if (f->eof) return 0;
  3678. if (i == 4) {
  3679. uint8 header[27];
  3680. uint32 i, crc, goal, len;
  3681. for (i=0; i < 4; ++i)
  3682. header[i] = ogg_page_header[i];
  3683. for (; i < 27; ++i)
  3684. header[i] = get8(f);
  3685. if (f->eof) return 0;
  3686. if (header[4] != 0) goto invalid;
  3687. goal = header[22] + (header[23] << 8) + (header[24]<<16) + (header[25]<<24);
  3688. for (i=22; i < 26; ++i)
  3689. header[i] = 0;
  3690. crc = 0;
  3691. for (i=0; i < 27; ++i)
  3692. crc = crc32_update(crc, header[i]);
  3693. len = 0;
  3694. for (i=0; i < header[26]; ++i) {
  3695. int s = get8(f);
  3696. crc = crc32_update(crc, s);
  3697. len += s;
  3698. }
  3699. if (len && f->eof) return 0;
  3700. for (i=0; i < len; ++i)
  3701. crc = crc32_update(crc, get8(f));
  3702. // finished parsing probable page
  3703. if (crc == goal) {
  3704. // we could now check that it's either got the last
  3705. // page flag set, OR it's followed by the capture
  3706. // pattern, but I guess TECHNICALLY you could have
  3707. // a file with garbage between each ogg page and recover
  3708. // from it automatically? So even though that paranoia
  3709. // might decrease the chance of an invalid decode by
  3710. // another 2^32, not worth it since it would hose those
  3711. // invalid-but-useful files?
  3712. if (end)
  3713. *end = stb_vorbis_get_file_offset(f);
  3714. if (last) {
  3715. if (header[5] & 0x04)
  3716. *last = 1;
  3717. else
  3718. *last = 0;
  3719. }
  3720. set_file_offset(f, retry_loc-1);
  3721. return 1;
  3722. }
  3723. }
  3724. invalid:
  3725. // not a valid page, so rewind and look for next one
  3726. set_file_offset(f, retry_loc);
  3727. }
  3728. }
  3729. }
  3730. #define SAMPLE_unknown 0xffffffff
  3731. // seeking is implemented with a binary search, which narrows down the range to
  3732. // 64K, before using a linear search (because finding the synchronization
  3733. // pattern can be expensive, and the chance we'd find the end page again is
  3734. // relatively high for small ranges)
  3735. //
  3736. // two initial interpolation-style probes are used at the start of the search
  3737. // to try to bound either side of the binary search sensibly, while still
  3738. // working in O(log n) time if they fail.
  3739. static int get_seek_page_info(stb_vorbis *f, ProbedPage *z)
  3740. {
  3741. uint8 header[27], lacing[255];
  3742. int i,len;
  3743. // record where the page starts
  3744. z->page_start = stb_vorbis_get_file_offset(f);
  3745. // parse the header
  3746. getn(f, header, 27);
  3747. if (header[0] != 'O' || header[1] != 'g' || header[2] != 'g' || header[3] != 'S')
  3748. return 0;
  3749. getn(f, lacing, header[26]);
  3750. // determine the length of the payload
  3751. len = 0;
  3752. for (i=0; i < header[26]; ++i)
  3753. len += lacing[i];
  3754. // this implies where the page ends
  3755. z->page_end = z->page_start + 27 + header[26] + len;
  3756. // read the last-decoded sample out of the data
  3757. z->last_decoded_sample = header[6] + (header[7] << 8) + (header[8] << 16) + (header[9] << 24);
  3758. // restore file state to where we were
  3759. set_file_offset(f, z->page_start);
  3760. return 1;
  3761. }
  3762. // rarely used function to seek back to the preceeding page while finding the
  3763. // start of a packet
  3764. static int go_to_page_before(stb_vorbis *f, unsigned int limit_offset)
  3765. {
  3766. unsigned int previous_safe, end;
  3767. // now we want to seek back 64K from the limit
  3768. if (limit_offset >= 65536 && limit_offset-65536 >= f->first_audio_page_offset)
  3769. previous_safe = limit_offset - 65536;
  3770. else
  3771. previous_safe = f->first_audio_page_offset;
  3772. set_file_offset(f, previous_safe);
  3773. while (vorbis_find_page(f, &end, NULL)) {
  3774. if (end >= limit_offset && stb_vorbis_get_file_offset(f) < limit_offset)
  3775. return 1;
  3776. set_file_offset(f, end);
  3777. }
  3778. return 0;
  3779. }
  3780. // implements the search logic for finding a page and starting decoding. if
  3781. // the function succeeds, current_loc_valid will be true and current_loc will
  3782. // be less than or equal to the provided sample number (the closer the
  3783. // better).
  3784. static int seek_to_sample_coarse(stb_vorbis *f, uint32 sample_number)
  3785. {
  3786. ProbedPage left, right, mid;
  3787. int i, start_seg_with_known_loc, end_pos, page_start;
  3788. uint32 delta, stream_length, padding;
  3789. double offset, bytes_per_sample;
  3790. int probe = 0;
  3791. // find the last page and validate the target sample
  3792. stream_length = stb_vorbis_stream_length_in_samples(f);
  3793. if (stream_length == 0) return error(f, VORBIS_seek_without_length);
  3794. if (sample_number > stream_length) return error(f, VORBIS_seek_invalid);
  3795. // this is the maximum difference between the window-center (which is the
  3796. // actual granule position value), and the right-start (which the spec
  3797. // indicates should be the granule position (give or take one)).
  3798. padding = ((f->blocksize_1 - f->blocksize_0) >> 2);
  3799. if (sample_number < padding)
  3800. sample_number = 0;
  3801. else
  3802. sample_number -= padding;
  3803. left = f->p_first;
  3804. while (left.last_decoded_sample == ~0U) {
  3805. // (untested) the first page does not have a 'last_decoded_sample'
  3806. set_file_offset(f, left.page_end);
  3807. if (!get_seek_page_info(f, &left)) goto error;
  3808. }
  3809. right = f->p_last;
  3810. assert(right.last_decoded_sample != ~0U);
  3811. // starting from the start is handled differently
  3812. if (sample_number <= left.last_decoded_sample) {
  3813. stb_vorbis_seek_start(f);
  3814. return 1;
  3815. }
  3816. while (left.page_end != right.page_start) {
  3817. assert(left.page_end < right.page_start);
  3818. // search range in bytes
  3819. delta = right.page_start - left.page_end;
  3820. if (delta <= 65536) {
  3821. // there's only 64K left to search - handle it linearly
  3822. set_file_offset(f, left.page_end);
  3823. } else {
  3824. if (probe < 2) {
  3825. if (probe == 0) {
  3826. // first probe (interpolate)
  3827. double data_bytes = right.page_end - left.page_start;
  3828. bytes_per_sample = data_bytes / right.last_decoded_sample;
  3829. offset = left.page_start + bytes_per_sample * (sample_number - left.last_decoded_sample);
  3830. } else {
  3831. // second probe (try to bound the other side)
  3832. double error = ((double) sample_number - mid.last_decoded_sample) * bytes_per_sample;
  3833. if (error >= 0 && error < 8000) error = 8000;
  3834. if (error < 0 && error > -8000) error = -8000;
  3835. offset += error * 2;
  3836. }
  3837. // ensure the offset is valid
  3838. if (offset < left.page_end)
  3839. offset = left.page_end;
  3840. if (offset > right.page_start - 65536)
  3841. offset = right.page_start - 65536;
  3842. set_file_offset(f, (unsigned int) offset);
  3843. } else {
  3844. // binary search for large ranges (offset by 32K to ensure
  3845. // we don't hit the right page)
  3846. set_file_offset(f, left.page_end + (delta / 2) - 32768);
  3847. }
  3848. if (!vorbis_find_page(f, NULL, NULL)) goto error;
  3849. }
  3850. for (;;) {
  3851. if (!get_seek_page_info(f, &mid)) goto error;
  3852. if (mid.last_decoded_sample != ~0U) break;
  3853. // (untested) no frames end on this page
  3854. set_file_offset(f, mid.page_end);
  3855. assert(mid.page_start < right.page_start);
  3856. }
  3857. // if we've just found the last page again then we're in a tricky file,
  3858. // and we're close enough.
  3859. if (mid.page_start == right.page_start)
  3860. break;
  3861. if (sample_number < mid.last_decoded_sample)
  3862. right = mid;
  3863. else
  3864. left = mid;
  3865. ++probe;
  3866. }
  3867. // seek back to start of the last packet
  3868. page_start = left.page_start;
  3869. set_file_offset(f, page_start);
  3870. if (!start_page(f)) return error(f, VORBIS_seek_failed);
  3871. end_pos = f->end_seg_with_known_loc;
  3872. assert(end_pos >= 0);
  3873. for (;;) {
  3874. for (i = end_pos; i > 0; --i)
  3875. if (f->segments[i-1] != 255)
  3876. break;
  3877. start_seg_with_known_loc = i;
  3878. if (start_seg_with_known_loc > 0 || !(f->page_flag & PAGEFLAG_continued_packet))
  3879. break;
  3880. // (untested) the final packet begins on an earlier page
  3881. if (!go_to_page_before(f, page_start))
  3882. goto error;
  3883. page_start = stb_vorbis_get_file_offset(f);
  3884. if (!start_page(f)) goto error;
  3885. end_pos = f->segment_count - 1;
  3886. }
  3887. // prepare to start decoding
  3888. f->current_loc_valid = FALSE;
  3889. f->last_seg = FALSE;
  3890. f->valid_bits = 0;
  3891. f->packet_bytes = 0;
  3892. f->bytes_in_seg = 0;
  3893. f->previous_length = 0;
  3894. f->next_seg = start_seg_with_known_loc;
  3895. for (i = 0; i < start_seg_with_known_loc; i++)
  3896. skip(f, f->segments[i]);
  3897. // start decoding (optimizable - this frame is generally discarded)
  3898. vorbis_pump_first_frame(f);
  3899. return 1;
  3900. error:
  3901. // try to restore the file to a valid state
  3902. stb_vorbis_seek_start(f);
  3903. return error(f, VORBIS_seek_failed);
  3904. }
  3905. // the same as vorbis_decode_initial, but without advancing
  3906. static int peek_decode_initial(vorb *f, int *p_left_start, int *p_left_end, int *p_right_start, int *p_right_end, int *mode)
  3907. {
  3908. int bits_read, bytes_read;
  3909. if (!vorbis_decode_initial(f, p_left_start, p_left_end, p_right_start, p_right_end, mode))
  3910. return 0;
  3911. // either 1 or 2 bytes were read, figure out which so we can rewind
  3912. bits_read = 1 + ilog(f->mode_count-1);
  3913. if (f->mode_config[*mode].blockflag)
  3914. bits_read += 2;
  3915. bytes_read = (bits_read + 7) / 8;
  3916. f->bytes_in_seg += bytes_read;
  3917. f->packet_bytes -= bytes_read;
  3918. skip(f, -bytes_read);
  3919. if (f->next_seg == -1)
  3920. f->next_seg = f->segment_count - 1;
  3921. else
  3922. f->next_seg--;
  3923. f->valid_bits = 0;
  3924. return 1;
  3925. }
  3926. int stb_vorbis_seek_frame(stb_vorbis *f, unsigned int sample_number)
  3927. {
  3928. uint32 max_frame_samples;
  3929. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  3930. // fast page-level search
  3931. if (!seek_to_sample_coarse(f, sample_number))
  3932. return 0;
  3933. assert(f->current_loc_valid);
  3934. assert(f->current_loc <= sample_number);
  3935. // linear search for the relevant packet
  3936. max_frame_samples = (f->blocksize_1*3 - f->blocksize_0) >> 2;
  3937. while (f->current_loc < sample_number) {
  3938. int left_start, left_end, right_start, right_end, mode, frame_samples;
  3939. if (!peek_decode_initial(f, &left_start, &left_end, &right_start, &right_end, &mode))
  3940. return error(f, VORBIS_seek_failed);
  3941. // calculate the number of samples returned by the next frame
  3942. frame_samples = right_start - left_start;
  3943. if (f->current_loc + frame_samples > sample_number) {
  3944. return 1; // the next frame will contain the sample
  3945. } else if (f->current_loc + frame_samples + max_frame_samples > sample_number) {
  3946. // there's a chance the frame after this could contain the sample
  3947. vorbis_pump_first_frame(f);
  3948. } else {
  3949. // this frame is too early to be relevant
  3950. f->current_loc += frame_samples;
  3951. f->previous_length = 0;
  3952. maybe_start_packet(f);
  3953. flush_packet(f);
  3954. }
  3955. }
  3956. // the next frame will start with the sample
  3957. assert(f->current_loc == sample_number);
  3958. return 1;
  3959. }
  3960. int stb_vorbis_seek(stb_vorbis *f, unsigned int sample_number)
  3961. {
  3962. if (!stb_vorbis_seek_frame(f, sample_number))
  3963. return 0;
  3964. if (sample_number != f->current_loc) {
  3965. int n;
  3966. uint32 frame_start = f->current_loc;
  3967. stb_vorbis_get_frame_float(f, &n, NULL);
  3968. assert(sample_number > frame_start);
  3969. assert(f->channel_buffer_start + (int) (sample_number-frame_start) <= f->channel_buffer_end);
  3970. f->channel_buffer_start += (sample_number - frame_start);
  3971. }
  3972. return 1;
  3973. }
  3974. void stb_vorbis_seek_start(stb_vorbis *f)
  3975. {
  3976. if (IS_PUSH_MODE(f)) { error(f, VORBIS_invalid_api_mixing); return; }
  3977. set_file_offset(f, f->first_audio_page_offset);
  3978. f->previous_length = 0;
  3979. f->first_decode = TRUE;
  3980. f->next_seg = -1;
  3981. vorbis_pump_first_frame(f);
  3982. }
  3983. unsigned int stb_vorbis_stream_length_in_samples(stb_vorbis *f)
  3984. {
  3985. unsigned int restore_offset, previous_safe;
  3986. unsigned int end, last_page_loc;
  3987. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  3988. if (!f->total_samples) {
  3989. unsigned int last;
  3990. uint32 lo,hi;
  3991. char header[6];
  3992. // first, store the current decode position so we can restore it
  3993. restore_offset = stb_vorbis_get_file_offset(f);
  3994. // now we want to seek back 64K from the end (the last page must
  3995. // be at most a little less than 64K, but let's allow a little slop)
  3996. if (f->stream_len >= 65536 && f->stream_len-65536 >= f->first_audio_page_offset)
  3997. previous_safe = f->stream_len - 65536;
  3998. else
  3999. previous_safe = f->first_audio_page_offset;
  4000. set_file_offset(f, previous_safe);
  4001. // previous_safe is now our candidate 'earliest known place that seeking
  4002. // to will lead to the final page'
  4003. if (!vorbis_find_page(f, &end, &last)) {
  4004. // if we can't find a page, we're hosed!
  4005. f->error = VORBIS_cant_find_last_page;
  4006. f->total_samples = 0xffffffff;
  4007. goto done;
  4008. }
  4009. // check if there are more pages
  4010. last_page_loc = stb_vorbis_get_file_offset(f);
  4011. // stop when the last_page flag is set, not when we reach eof;
  4012. // this allows us to stop short of a 'file_section' end without
  4013. // explicitly checking the length of the section
  4014. while (!last) {
  4015. set_file_offset(f, end);
  4016. if (!vorbis_find_page(f, &end, &last)) {
  4017. // the last page we found didn't have the 'last page' flag
  4018. // set. whoops!
  4019. break;
  4020. }
  4021. previous_safe = last_page_loc+1;
  4022. last_page_loc = stb_vorbis_get_file_offset(f);
  4023. }
  4024. set_file_offset(f, last_page_loc);
  4025. // parse the header
  4026. getn(f, (unsigned char *)header, 6);
  4027. // extract the absolute granule position
  4028. lo = get32(f);
  4029. hi = get32(f);
  4030. if (lo == 0xffffffff && hi == 0xffffffff) {
  4031. f->error = VORBIS_cant_find_last_page;
  4032. f->total_samples = SAMPLE_unknown;
  4033. goto done;
  4034. }
  4035. if (hi)
  4036. lo = 0xfffffffe; // saturate
  4037. f->total_samples = lo;
  4038. f->p_last.page_start = last_page_loc;
  4039. f->p_last.page_end = end;
  4040. f->p_last.last_decoded_sample = lo;
  4041. done:
  4042. set_file_offset(f, restore_offset);
  4043. }
  4044. return f->total_samples == SAMPLE_unknown ? 0 : f->total_samples;
  4045. }
  4046. float stb_vorbis_stream_length_in_seconds(stb_vorbis *f)
  4047. {
  4048. return stb_vorbis_stream_length_in_samples(f) / (float) f->sample_rate;
  4049. }
  4050. int stb_vorbis_get_frame_float(stb_vorbis *f, int *channels, float ***output)
  4051. {
  4052. int len, right,left,i;
  4053. if (IS_PUSH_MODE(f)) return error(f, VORBIS_invalid_api_mixing);
  4054. if (!vorbis_decode_packet(f, &len, &left, &right)) {
  4055. f->channel_buffer_start = f->channel_buffer_end = 0;
  4056. return 0;
  4057. }
  4058. len = vorbis_finish_frame(f, len, left, right);
  4059. for (i=0; i < f->channels; ++i)
  4060. f->outputs[i] = f->channel_buffers[i] + left;
  4061. f->channel_buffer_start = left;
  4062. f->channel_buffer_end = left+len;
  4063. if (channels) *channels = f->channels;
  4064. if (output) *output = f->outputs;
  4065. return len;
  4066. }
  4067. #ifndef STB_VORBIS_NO_STDIO
  4068. stb_vorbis * stb_vorbis_open_file_section(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc, unsigned int length)
  4069. {
  4070. stb_vorbis *f, p;
  4071. vorbis_init(&p, alloc);
  4072. p.f = file;
  4073. p.f_start = (uint32) ftell(file);
  4074. p.stream_len = length;
  4075. p.close_on_free = close_on_free;
  4076. if (start_decoder(&p)) {
  4077. f = vorbis_alloc(&p);
  4078. if (f) {
  4079. *f = p;
  4080. vorbis_pump_first_frame(f);
  4081. return f;
  4082. }
  4083. }
  4084. if (error) *error = p.error;
  4085. vorbis_deinit(&p);
  4086. return NULL;
  4087. }
  4088. stb_vorbis * stb_vorbis_open_file(FILE *file, int close_on_free, int *error, const stb_vorbis_alloc *alloc)
  4089. {
  4090. unsigned int len, start;
  4091. start = (unsigned int) ftell(file);
  4092. fseek(file, 0, SEEK_END);
  4093. len = (unsigned int) (ftell(file) - start);
  4094. fseek(file, start, SEEK_SET);
  4095. return stb_vorbis_open_file_section(file, close_on_free, error, alloc, len);
  4096. }
  4097. stb_vorbis * stb_vorbis_open_filename(const char *filename, int *error, const stb_vorbis_alloc *alloc)
  4098. {
  4099. FILE *f = fopen(filename, "rb");
  4100. if (f)
  4101. return stb_vorbis_open_file(f, TRUE, error, alloc);
  4102. if (error) *error = VORBIS_file_open_failure;
  4103. return NULL;
  4104. }
  4105. #endif // STB_VORBIS_NO_STDIO
  4106. stb_vorbis * stb_vorbis_open_memory(const unsigned char *data, int len, int *error, const stb_vorbis_alloc *alloc)
  4107. {
  4108. stb_vorbis *f, p;
  4109. if (data == NULL) return NULL;
  4110. vorbis_init(&p, alloc);
  4111. p.stream = (uint8 *) data;
  4112. p.stream_end = (uint8 *) data + len;
  4113. p.stream_start = (uint8 *) p.stream;
  4114. p.stream_len = len;
  4115. p.push_mode = FALSE;
  4116. if (start_decoder(&p)) {
  4117. f = vorbis_alloc(&p);
  4118. if (f) {
  4119. *f = p;
  4120. vorbis_pump_first_frame(f);
  4121. return f;
  4122. }
  4123. }
  4124. if (error) *error = p.error;
  4125. vorbis_deinit(&p);
  4126. return NULL;
  4127. }
  4128. #ifndef STB_VORBIS_NO_INTEGER_CONVERSION
  4129. #define PLAYBACK_MONO 1
  4130. #define PLAYBACK_LEFT 2
  4131. #define PLAYBACK_RIGHT 4
  4132. #define L (PLAYBACK_LEFT | PLAYBACK_MONO)
  4133. #define C (PLAYBACK_LEFT | PLAYBACK_RIGHT | PLAYBACK_MONO)
  4134. #define R (PLAYBACK_RIGHT | PLAYBACK_MONO)
  4135. static int8 channel_position[7][6] =
  4136. {
  4137. { 0 },
  4138. { C },
  4139. { L, R },
  4140. { L, C, R },
  4141. { L, R, L, R },
  4142. { L, C, R, L, R },
  4143. { L, C, R, L, R, C },
  4144. };
  4145. #ifndef STB_VORBIS_NO_FAST_SCALED_FLOAT
  4146. typedef union {
  4147. float f;
  4148. int i;
  4149. } float_conv;
  4150. typedef char stb_vorbis_float_size_test[sizeof(float)==4 && sizeof(int) == 4];
  4151. #define FASTDEF(x) float_conv x
  4152. // add (1<<23) to convert to int, then divide by 2^SHIFT, then add 0.5/2^SHIFT to round
  4153. #define MAGIC(SHIFT) (1.5f * (1 << (23-SHIFT)) + 0.5f/(1 << SHIFT))
  4154. #define ADDEND(SHIFT) (((150-SHIFT) << 23) + (1 << 22))
  4155. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) (temp.f = (x) + MAGIC(s), temp.i - ADDEND(s))
  4156. #define check_endianness()
  4157. #else
  4158. #define FAST_SCALED_FLOAT_TO_INT(temp,x,s) ((int) ((x) * (1 << (s))))
  4159. #define check_endianness()
  4160. #define FASTDEF(x)
  4161. #endif
  4162. static void copy_samples(short *dest, float *src, int len)
  4163. {
  4164. int i;
  4165. check_endianness();
  4166. for (i=0; i < len; ++i) {
  4167. FASTDEF(temp);
  4168. int v = FAST_SCALED_FLOAT_TO_INT(temp, src[i],15);
  4169. if ((unsigned int) (v + 32768) > 65535)
  4170. v = v < 0 ? -32768 : 32767;
  4171. dest[i] = v;
  4172. }
  4173. }
  4174. static void compute_samples(int mask, short *output, int num_c, float **data, int d_offset, int len)
  4175. {
  4176. #define BUFFER_SIZE 32
  4177. float buffer[BUFFER_SIZE];
  4178. int i,j,o,n = BUFFER_SIZE;
  4179. check_endianness();
  4180. for (o = 0; o < len; o += BUFFER_SIZE) {
  4181. memset(buffer, 0, sizeof(buffer));
  4182. if (o + n > len) n = len - o;
  4183. for (j=0; j < num_c; ++j) {
  4184. if (channel_position[num_c][j] & mask) {
  4185. for (i=0; i < n; ++i)
  4186. buffer[i] += data[j][d_offset+o+i];
  4187. }
  4188. }
  4189. for (i=0; i < n; ++i) {
  4190. FASTDEF(temp);
  4191. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  4192. if ((unsigned int) (v + 32768) > 65535)
  4193. v = v < 0 ? -32768 : 32767;
  4194. output[o+i] = v;
  4195. }
  4196. }
  4197. }
  4198. static void compute_stereo_samples(short *output, int num_c, float **data, int d_offset, int len)
  4199. {
  4200. #define BUFFER_SIZE 32
  4201. float buffer[BUFFER_SIZE];
  4202. int i,j,o,n = BUFFER_SIZE >> 1;
  4203. // o is the offset in the source data
  4204. check_endianness();
  4205. for (o = 0; o < len; o += BUFFER_SIZE >> 1) {
  4206. // o2 is the offset in the output data
  4207. int o2 = o << 1;
  4208. memset(buffer, 0, sizeof(buffer));
  4209. if (o + n > len) n = len - o;
  4210. for (j=0; j < num_c; ++j) {
  4211. int m = channel_position[num_c][j] & (PLAYBACK_LEFT | PLAYBACK_RIGHT);
  4212. if (m == (PLAYBACK_LEFT | PLAYBACK_RIGHT)) {
  4213. for (i=0; i < n; ++i) {
  4214. buffer[i*2+0] += data[j][d_offset+o+i];
  4215. buffer[i*2+1] += data[j][d_offset+o+i];
  4216. }
  4217. } else if (m == PLAYBACK_LEFT) {
  4218. for (i=0; i < n; ++i) {
  4219. buffer[i*2+0] += data[j][d_offset+o+i];
  4220. }
  4221. } else if (m == PLAYBACK_RIGHT) {
  4222. for (i=0; i < n; ++i) {
  4223. buffer[i*2+1] += data[j][d_offset+o+i];
  4224. }
  4225. }
  4226. }
  4227. for (i=0; i < (n<<1); ++i) {
  4228. FASTDEF(temp);
  4229. int v = FAST_SCALED_FLOAT_TO_INT(temp,buffer[i],15);
  4230. if ((unsigned int) (v + 32768) > 65535)
  4231. v = v < 0 ? -32768 : 32767;
  4232. output[o2+i] = v;
  4233. }
  4234. }
  4235. }
  4236. static void convert_samples_short(int buf_c, short **buffer, int b_offset, int data_c, float **data, int d_offset, int samples)
  4237. {
  4238. int i;
  4239. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  4240. static int channel_selector[3][2] = { {0}, {PLAYBACK_MONO}, {PLAYBACK_LEFT, PLAYBACK_RIGHT} };
  4241. for (i=0; i < buf_c; ++i)
  4242. compute_samples(channel_selector[buf_c][i], buffer[i]+b_offset, data_c, data, d_offset, samples);
  4243. } else {
  4244. int limit = buf_c < data_c ? buf_c : data_c;
  4245. for (i=0; i < limit; ++i)
  4246. copy_samples(buffer[i]+b_offset, data[i]+d_offset, samples);
  4247. for ( ; i < buf_c; ++i)
  4248. memset(buffer[i]+b_offset, 0, sizeof(short) * samples);
  4249. }
  4250. }
  4251. int stb_vorbis_get_frame_short(stb_vorbis *f, int num_c, short **buffer, int num_samples)
  4252. {
  4253. float **output;
  4254. int len = stb_vorbis_get_frame_float(f, NULL, &output);
  4255. if (len > num_samples) len = num_samples;
  4256. if (len)
  4257. convert_samples_short(num_c, buffer, 0, f->channels, output, 0, len);
  4258. return len;
  4259. }
  4260. static void convert_channels_short_interleaved(int buf_c, short *buffer, int data_c, float **data, int d_offset, int len)
  4261. {
  4262. int i;
  4263. check_endianness();
  4264. if (buf_c != data_c && buf_c <= 2 && data_c <= 6) {
  4265. assert(buf_c == 2);
  4266. for (i=0; i < buf_c; ++i)
  4267. compute_stereo_samples(buffer, data_c, data, d_offset, len);
  4268. } else {
  4269. int limit = buf_c < data_c ? buf_c : data_c;
  4270. int j;
  4271. for (j=0; j < len; ++j) {
  4272. for (i=0; i < limit; ++i) {
  4273. FASTDEF(temp);
  4274. float f = data[i][d_offset+j];
  4275. int v = FAST_SCALED_FLOAT_TO_INT(temp, f,15);//data[i][d_offset+j],15);
  4276. if ((unsigned int) (v + 32768) > 65535)
  4277. v = v < 0 ? -32768 : 32767;
  4278. *buffer++ = v;
  4279. }
  4280. for ( ; i < buf_c; ++i)
  4281. *buffer++ = 0;
  4282. }
  4283. }
  4284. }
  4285. int stb_vorbis_get_frame_short_interleaved(stb_vorbis *f, int num_c, short *buffer, int num_shorts)
  4286. {
  4287. float **output;
  4288. int len;
  4289. if (num_c == 1) return stb_vorbis_get_frame_short(f,num_c,&buffer, num_shorts);
  4290. len = stb_vorbis_get_frame_float(f, NULL, &output);
  4291. if (len) {
  4292. if (len*num_c > num_shorts) len = num_shorts / num_c;
  4293. convert_channels_short_interleaved(num_c, buffer, f->channels, output, 0, len);
  4294. }
  4295. return len;
  4296. }
  4297. int stb_vorbis_get_samples_short_interleaved(stb_vorbis *f, int channels, short *buffer, int num_shorts)
  4298. {
  4299. float **outputs;
  4300. int len = num_shorts / channels;
  4301. int n=0;
  4302. int z = f->channels;
  4303. if (z > channels) z = channels;
  4304. while (n < len) {
  4305. int k = f->channel_buffer_end - f->channel_buffer_start;
  4306. if (n+k >= len) k = len - n;
  4307. if (k)
  4308. convert_channels_short_interleaved(channels, buffer, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  4309. buffer += k*channels;
  4310. n += k;
  4311. f->channel_buffer_start += k;
  4312. if (n == len) break;
  4313. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4314. }
  4315. return n;
  4316. }
  4317. int stb_vorbis_get_samples_short(stb_vorbis *f, int channels, short **buffer, int len)
  4318. {
  4319. float **outputs;
  4320. int n=0;
  4321. int z = f->channels;
  4322. if (z > channels) z = channels;
  4323. while (n < len) {
  4324. int k = f->channel_buffer_end - f->channel_buffer_start;
  4325. if (n+k >= len) k = len - n;
  4326. if (k)
  4327. convert_samples_short(channels, buffer, n, f->channels, f->channel_buffers, f->channel_buffer_start, k);
  4328. n += k;
  4329. f->channel_buffer_start += k;
  4330. if (n == len) break;
  4331. if (!stb_vorbis_get_frame_float(f, NULL, &outputs)) break;
  4332. }
  4333. return n;
  4334. }
  4335. #ifndef STB_VORBIS_NO_STDIO
  4336. int stb_vorbis_decode_filename(const char *filename, int *channels, int *sample_rate, short **output)
  4337. {
  4338. int data_len, offset, total, limit, error;
  4339. short *data;
  4340. stb_vorbis *v = stb_vorbis_open_filename(filename, &error, NULL);
  4341. if (v == NULL) return -1;
  4342. limit = v->channels * 4096;
  4343. *channels = v->channels;
  4344. if (sample_rate)
  4345. *sample_rate = v->sample_rate;
  4346. offset = data_len = 0;
  4347. total = limit;
  4348. data = (short *) malloc(total * sizeof(*data));
  4349. if (data == NULL) {
  4350. stb_vorbis_close(v);
  4351. return -2;
  4352. }
  4353. for (;;) {
  4354. int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
  4355. if (n == 0) break;
  4356. data_len += n;
  4357. offset += n * v->channels;
  4358. if (offset + limit > total) {
  4359. short *data2;
  4360. total *= 2;
  4361. data2 = (short *) realloc(data, total * sizeof(*data));
  4362. if (data2 == NULL) {
  4363. free(data);
  4364. stb_vorbis_close(v);
  4365. return -2;
  4366. }
  4367. data = data2;
  4368. }
  4369. }
  4370. *output = data;
  4371. stb_vorbis_close(v);
  4372. return data_len;
  4373. }
  4374. #endif // NO_STDIO
  4375. int stb_vorbis_decode_memory(const uint8 *mem, int len, int *channels, int *sample_rate, short **output)
  4376. {
  4377. int data_len, offset, total, limit, error;
  4378. short *data;
  4379. stb_vorbis *v = stb_vorbis_open_memory(mem, len, &error, NULL);
  4380. if (v == NULL) return -1;
  4381. limit = v->channels * 4096;
  4382. *channels = v->channels;
  4383. if (sample_rate)
  4384. *sample_rate = v->sample_rate;
  4385. offset = data_len = 0;
  4386. total = limit;
  4387. data = (short *) malloc(total * sizeof(*data));
  4388. if (data == NULL) {
  4389. stb_vorbis_close(v);
  4390. return -2;
  4391. }
  4392. for (;;) {
  4393. int n = stb_vorbis_get_frame_short_interleaved(v, v->channels, data+offset, total-offset);
  4394. if (n == 0) break;
  4395. data_len += n;
  4396. offset += n * v->channels;
  4397. if (offset + limit > total) {
  4398. short *data2;
  4399. total *= 2;
  4400. data2 = (short *) realloc(data, total * sizeof(*data));
  4401. if (data2 == NULL) {
  4402. free(data);
  4403. stb_vorbis_close(v);
  4404. return -2;
  4405. }
  4406. data = data2;
  4407. }
  4408. }
  4409. *output = data;
  4410. stb_vorbis_close(v);
  4411. return data_len;
  4412. }
  4413. #endif // STB_VORBIS_NO_INTEGER_CONVERSION
  4414. int stb_vorbis_get_samples_float_interleaved(stb_vorbis *f, int channels, float *buffer, int num_floats)
  4415. {
  4416. float **outputs;
  4417. int len = num_floats / channels;
  4418. int n=0;
  4419. int z = f->channels;
  4420. if (z > channels) z = channels;
  4421. while (n < len) {
  4422. int i,j;
  4423. int k = f->channel_buffer_end - f->channel_buffer_start;
  4424. if (n+k >= len) k = len - n;
  4425. for (j=0; j < k; ++j) {
  4426. for (i=0; i < z; ++i)
  4427. *buffer++ = f->channel_buffers[i][f->channel_buffer_start+j];
  4428. for ( ; i < channels; ++i)
  4429. *buffer++ = 0;
  4430. }
  4431. n += k;
  4432. f->channel_buffer_start += k;
  4433. if (n == len)
  4434. break;
  4435. if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
  4436. break;
  4437. }
  4438. return n;
  4439. }
  4440. int stb_vorbis_get_samples_float(stb_vorbis *f, int channels, float **buffer, int num_samples)
  4441. {
  4442. float **outputs;
  4443. int n=0;
  4444. int z = f->channels;
  4445. if (z > channels) z = channels;
  4446. while (n < num_samples) {
  4447. int i;
  4448. int k = f->channel_buffer_end - f->channel_buffer_start;
  4449. if (n+k >= num_samples) k = num_samples - n;
  4450. if (k) {
  4451. for (i=0; i < z; ++i)
  4452. memcpy(buffer[i]+n, f->channel_buffers[i]+f->channel_buffer_start, sizeof(float)*k);
  4453. for ( ; i < channels; ++i)
  4454. memset(buffer[i]+n, 0, sizeof(float) * k);
  4455. }
  4456. n += k;
  4457. f->channel_buffer_start += k;
  4458. if (n == num_samples)
  4459. break;
  4460. if (!stb_vorbis_get_frame_float(f, NULL, &outputs))
  4461. break;
  4462. }
  4463. return n;
  4464. }
  4465. #endif // STB_VORBIS_NO_PULLDATA_API
  4466. /* Version history
  4467. 1.09 - 2016/04/04 - back out 'avoid discarding last frame' fix from previous version
  4468. 1.08 - 2016/04/02 - fixed multiple warnings; fix setup memory leaks;
  4469. avoid discarding last frame of audio data
  4470. 1.07 - 2015/01/16 - fixed some warnings, fix mingw, const-correct API
  4471. some more crash fixes when out of memory or with corrupt files
  4472. 1.06 - 2015/08/31 - full, correct support for seeking API (Dougall Johnson)
  4473. some crash fixes when out of memory or with corrupt files
  4474. 1.05 - 2015/04/19 - don't define __forceinline if it's redundant
  4475. 1.04 - 2014/08/27 - fix missing const-correct case in API
  4476. 1.03 - 2014/08/07 - Warning fixes
  4477. 1.02 - 2014/07/09 - Declare qsort compare function _cdecl on windows
  4478. 1.01 - 2014/06/18 - fix stb_vorbis_get_samples_float
  4479. 1.0 - 2014/05/26 - fix memory leaks; fix warnings; fix bugs in multichannel
  4480. (API change) report sample rate for decode-full-file funcs
  4481. 0.99996 - bracket #include <malloc.h> for macintosh compilation by Laurent Gomila
  4482. 0.99995 - use union instead of pointer-cast for fast-float-to-int to avoid alias-optimization problem
  4483. 0.99994 - change fast-float-to-int to work in single-precision FPU mode, remove endian-dependence
  4484. 0.99993 - remove assert that fired on legal files with empty tables
  4485. 0.99992 - rewind-to-start
  4486. 0.99991 - bugfix to stb_vorbis_get_samples_short by Bernhard Wodo
  4487. 0.9999 - (should have been 0.99990) fix no-CRT support, compiling as C++
  4488. 0.9998 - add a full-decode function with a memory source
  4489. 0.9997 - fix a bug in the read-from-FILE case in 0.9996 addition
  4490. 0.9996 - query length of vorbis stream in samples/seconds
  4491. 0.9995 - bugfix to another optimization that only happened in certain files
  4492. 0.9994 - bugfix to one of the optimizations that caused significant (but inaudible?) errors
  4493. 0.9993 - performance improvements; runs in 99% to 104% of time of reference implementation
  4494. 0.9992 - performance improvement of IMDCT; now performs close to reference implementation
  4495. 0.9991 - performance improvement of IMDCT
  4496. 0.999 - (should have been 0.9990) performance improvement of IMDCT
  4497. 0.998 - no-CRT support from Casey Muratori
  4498. 0.997 - bugfixes for bugs found by Terje Mathisen
  4499. 0.996 - bugfix: fast-huffman decode initialized incorrectly for sparse codebooks; fixing gives 10% speedup - found by Terje Mathisen
  4500. 0.995 - bugfix: fix to 'effective' overrun detection - found by Terje Mathisen
  4501. 0.994 - bugfix: garbage decode on final VQ symbol of a non-multiple - found by Terje Mathisen
  4502. 0.993 - bugfix: pushdata API required 1 extra byte for empty page (failed to consume final page if empty) - found by Terje Mathisen
  4503. 0.992 - fixes for MinGW warning
  4504. 0.991 - turn fast-float-conversion on by default
  4505. 0.990 - fix push-mode seek recovery if you seek into the headers
  4506. 0.98b - fix to bad release of 0.98
  4507. 0.98 - fix push-mode seek recovery; robustify float-to-int and support non-fast mode
  4508. 0.97 - builds under c++ (typecasting, don't use 'class' keyword)
  4509. 0.96 - somehow MY 0.95 was right, but the web one was wrong, so here's my 0.95 rereleased as 0.96, fixes a typo in the clamping code
  4510. 0.95 - clamping code for 16-bit functions
  4511. 0.94 - not publically released
  4512. 0.93 - fixed all-zero-floor case (was decoding garbage)
  4513. 0.92 - fixed a memory leak
  4514. 0.91 - conditional compiles to omit parts of the API and the infrastructure to support them: STB_VORBIS_NO_PULLDATA_API, STB_VORBIS_NO_PUSHDATA_API, STB_VORBIS_NO_STDIO, STB_VORBIS_NO_INTEGER_CONVERSION
  4515. 0.90 - first public release
  4516. */
  4517. #endif // STB_VORBIS_HEADER_ONLY