stb_vorbis.c 186 KB

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