stb_vorbis.c 163 KB

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