stb_vorbis.c 184 KB

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