stb_vorbis.c 187 KB

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