stb_vorbis.c 187 KB

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