stb_image.h 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435
  1. /* stb_image - v2.05 - public domain image loader - http://nothings.org/stb_image.h
  2. no warranty implied; use at your own risk
  3. Do this:
  4. #define STB_IMAGE_IMPLEMENTATION
  5. before you include this file in *one* C or C++ file to create the implementation.
  6. // i.e. it should look like this:
  7. #include ...
  8. #include ...
  9. #include ...
  10. #define STB_IMAGE_IMPLEMENTATION
  11. #include "stb_image.h"
  12. You can #define STBI_ASSERT(x) before the #include to avoid using assert.h.
  13. And #define STBI_MALLOC, STBI_REALLOC, and STBI_FREE to avoid using malloc,realloc,free
  14. QUICK NOTES:
  15. Primarily of interest to game developers and other people who can
  16. avoid problematic images and only need the trivial interface
  17. JPEG baseline & progressive (12 bpc/arithmetic not supported, same as stock IJG lib)
  18. PNG 1/2/4/8-bit-per-channel (16 bpc not supported)
  19. TGA (not sure what subset, if a subset)
  20. BMP non-1bpp, non-RLE
  21. PSD (composited view only, no extra channels)
  22. GIF (*comp always reports as 4-channel)
  23. HDR (radiance rgbE format)
  24. PIC (Softimage PIC)
  25. PNM (PPM and PGM binary only)
  26. - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
  27. - decode from arbitrary I/O callbacks
  28. - SIMD acceleration on x86/x64 (SSE2) and ARM (NEON)
  29. Full documentation under "DOCUMENTATION" below.
  30. Revision 2.00 release notes:
  31. - Progressive JPEG is now supported.
  32. - PPM and PGM binary formats are now supported, thanks to Ken Miller.
  33. - x86 platforms now make use of SSE2 SIMD instructions for
  34. JPEG decoding, and ARM platforms can use NEON SIMD if requested.
  35. This work was done by Fabian "ryg" Giesen. SSE2 is used by
  36. default, but NEON must be enabled explicitly; see docs.
  37. With other JPEG optimizations included in this version, we see
  38. 2x speedup on a JPEG on an x86 machine, and a 1.5x speedup
  39. on a JPEG on an ARM machine, relative to previous versions of this
  40. library. The same results will not obtain for all JPGs and for all
  41. x86/ARM machines. (Note that progressive JPEGs are significantly
  42. slower to decode than regular JPEGs.) This doesn't mean that this
  43. is the fastest JPEG decoder in the land; rather, it brings it
  44. closer to parity with standard libraries. If you want the fastest
  45. decode, look elsewhere. (See "Philosophy" section of docs below.)
  46. See final bullet items below for more info on SIMD.
  47. - Added STBI_MALLOC, STBI_REALLOC, and STBI_FREE macros for replacing
  48. the memory allocator. Unlike other STBI libraries, these macros don't
  49. support a context parameter, so if you need to pass a context in to
  50. the allocator, you'll have to store it in a global or a thread-local
  51. variable.
  52. - Split existing STBI_NO_HDR flag into two flags, STBI_NO_HDR and
  53. STBI_NO_LINEAR.
  54. STBI_NO_HDR: suppress implementation of .hdr reader format
  55. STBI_NO_LINEAR: suppress high-dynamic-range light-linear float API
  56. - You can suppress implementation of any of the decoders to reduce
  57. your code footprint by #defining one or more of the following
  58. symbols before creating the implementation.
  59. STBI_NO_JPEG
  60. STBI_NO_PNG
  61. STBI_NO_BMP
  62. STBI_NO_PSD
  63. STBI_NO_TGA
  64. STBI_NO_GIF
  65. STBI_NO_HDR
  66. STBI_NO_PIC
  67. STBI_NO_PNM (.ppm and .pgm)
  68. - You can request *only* certain decoders and suppress all other ones
  69. (this will be more forward-compatible, as addition of new decoders
  70. doesn't require you to disable them explicitly):
  71. STBI_ONLY_JPEG
  72. STBI_ONLY_PNG
  73. STBI_ONLY_BMP
  74. STBI_ONLY_PSD
  75. STBI_ONLY_TGA
  76. STBI_ONLY_GIF
  77. STBI_ONLY_HDR
  78. STBI_ONLY_PIC
  79. STBI_ONLY_PNM (.ppm and .pgm)
  80. Note that you can define multiples of these, and you will get all
  81. of them ("only x" and "only y" is interpreted to mean "only x&y").
  82. - If you use STBI_NO_PNG (or _ONLY_ without PNG), and you still
  83. want the zlib decoder to be available, #define STBI_SUPPORT_ZLIB
  84. - Compilation of all SIMD code can be suppressed with
  85. #define STBI_NO_SIMD
  86. It should not be necessary to disable SIMD unless you have issues
  87. compiling (e.g. using an x86 compiler which doesn't support SSE
  88. intrinsics or that doesn't support the method used to detect
  89. SSE2 support at run-time), and even those can be reported as
  90. bugs so I can refine the built-in compile-time checking to be
  91. smarter.
  92. - The old STBI_SIMD system which allowed installing a user-defined
  93. IDCT etc. has been removed. If you need this, don't upgrade. My
  94. assumption is that almost nobody was doing this, and those who
  95. were will find the built-in SIMD more satisfactory anyway.
  96. - RGB values computed for JPEG images are slightly different from
  97. previous versions of stb_image. (This is due to using less
  98. integer precision in SIMD.) The C code has been adjusted so
  99. that the same RGB values will be computed regardless of whether
  100. SIMD support is available, so your app should always produce
  101. consistent results. But these results are slightly different from
  102. previous versions. (Specifically, about 3% of available YCbCr values
  103. will compute different RGB results from pre-1.49 versions by +-1;
  104. most of the deviating values are one smaller in the G channel.)
  105. - If you must produce consistent results with previous versions of
  106. stb_image, #define STBI_JPEG_OLD and you will get the same results
  107. you used to; however, you will not get the SIMD speedups for
  108. the YCbCr-to-RGB conversion step (although you should still see
  109. significant JPEG speedup from the other changes).
  110. Please note that STBI_JPEG_OLD is a temporary feature; it will be
  111. removed in future versions of the library. It is only intended for
  112. near-term back-compatibility use.
  113. Latest revision history:
  114. 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
  115. 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
  116. 2.03 (2015-04-12) additional corruption checking
  117. stbi_set_flip_vertically_on_load
  118. fix NEON support; fix mingw support
  119. 2.02 (2015-01-19) fix incorrect assert, fix warning
  120. 2.01 (2015-01-17) fix various warnings
  121. 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
  122. 2.00 (2014-12-25) optimize JPEG, including x86 SSE2 & ARM NEON SIMD
  123. progressive JPEG
  124. PGM/PPM support
  125. STBI_MALLOC,STBI_REALLOC,STBI_FREE
  126. STBI_NO_*, STBI_ONLY_*
  127. GIF bugfix
  128. 1.48 (2014-12-14) fix incorrectly-named assert()
  129. 1.47 (2014-12-14) 1/2/4-bit PNG support (both grayscale and paletted)
  130. optimize PNG
  131. fix bug in interlaced PNG with user-specified channel count
  132. See end of file for full revision history.
  133. ============================ Contributors =========================
  134. Image formats Bug fixes & warning fixes
  135. Sean Barrett (jpeg, png, bmp) Marc LeBlanc
  136. Nicolas Schulz (hdr, psd) Christpher Lloyd
  137. Jonathan Dummer (tga) Dave Moore
  138. Jean-Marc Lienher (gif) Won Chun
  139. Tom Seddon (pic) the Horde3D community
  140. Thatcher Ulrich (psd) Janez Zemva
  141. Ken Miller (pgm, ppm) Jonathan Blow
  142. Laurent Gomila
  143. Aruelien Pocheville
  144. Extensions, features Ryamond Barbiero
  145. Jetro Lauha (stbi_info) David Woo
  146. Martin "SpartanJ" Golini (stbi_info) Martin Golini
  147. James "moose2000" Brown (iPhone PNG) Roy Eltham
  148. Ben "Disch" Wenger (io callbacks) Luke Graham
  149. Omar Cornut (1/2/4-bit PNG) Thomas Ruf
  150. Nicolas Guillemot (vertical flip) John Bartholomew
  151. Ken Hamada
  152. Optimizations & bugfixes Cort Stratton
  153. Fabian "ryg" Giesen Blazej Dariusz Roszkowski
  154. Arseny Kapoulkine Thibault Reuille
  155. Paul Du Bois
  156. Guillaume George
  157. If your name should be here but Jerry Jansson
  158. isn't, let Sean know. Hayaki Saito
  159. Johan Duparc
  160. Ronny Chevalier
  161. Michal Cichon
  162. Tero Hanninen
  163. Sergio Gonzalez
  164. Cass Everitt
  165. Engin Manap
  166. Martins Mozeiko
  167. Joseph Thomson
  168. Phil Jordan
  169. License:
  170. This software is in the public domain. Where that dedication is not
  171. recognized, you are granted a perpetual, irrevocable license to copy
  172. and modify this file however you want.
  173. */
  174. #ifndef STBI_INCLUDE_STB_IMAGE_H
  175. #define STBI_INCLUDE_STB_IMAGE_H
  176. // DOCUMENTATION
  177. //
  178. // Limitations:
  179. // - no 16-bit-per-channel PNG
  180. // - no 12-bit-per-channel JPEG
  181. // - no JPEGs with arithmetic coding
  182. // - no 1-bit BMP
  183. // - GIF always returns *comp=4
  184. //
  185. // Basic usage (see HDR discussion below for HDR usage):
  186. // int x,y,n;
  187. // unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
  188. // // ... process data if not NULL ...
  189. // // ... x = width, y = height, n = # 8-bit components per pixel ...
  190. // // ... replace '0' with '1'..'4' to force that many components per pixel
  191. // // ... but 'n' will always be the number that it would have been if you said 0
  192. // stbi_image_free(data)
  193. //
  194. // Standard parameters:
  195. // int *x -- outputs image width in pixels
  196. // int *y -- outputs image height in pixels
  197. // int *comp -- outputs # of image components in image file
  198. // int req_comp -- if non-zero, # of image components requested in result
  199. //
  200. // The return value from an image loader is an 'unsigned char *' which points
  201. // to the pixel data, or NULL on an allocation failure or if the image is
  202. // corrupt or invalid. The pixel data consists of *y scanlines of *x pixels,
  203. // with each pixel consisting of N interleaved 8-bit components; the first
  204. // pixel pointed to is top-left-most in the image. There is no padding between
  205. // image scanlines or between pixels, regardless of format. The number of
  206. // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
  207. // If req_comp is non-zero, *comp has the number of components that _would_
  208. // have been output otherwise. E.g. if you set req_comp to 4, you will always
  209. // get RGBA output, but you can check *comp to see if it's trivially opaque
  210. // because e.g. there were only 3 channels in the source image.
  211. //
  212. // An output image with N components has the following components interleaved
  213. // in this order in each pixel:
  214. //
  215. // N=#comp components
  216. // 1 grey
  217. // 2 grey, alpha
  218. // 3 red, green, blue
  219. // 4 red, green, blue, alpha
  220. //
  221. // If image loading fails for any reason, the return value will be NULL,
  222. // and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
  223. // can be queried for an extremely brief, end-user unfriendly explanation
  224. // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
  225. // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
  226. // more user-friendly ones.
  227. //
  228. // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
  229. //
  230. // ===========================================================================
  231. //
  232. // Philosophy
  233. //
  234. // stb libraries are designed with the following priorities:
  235. //
  236. // 1. easy to use
  237. // 2. easy to maintain
  238. // 3. good performance
  239. //
  240. // Sometimes I let "good performance" creep up in priority over "easy to maintain",
  241. // and for best performance I may provide less-easy-to-use APIs that give higher
  242. // performance, in addition to the easy to use ones. Nevertheless, it's important
  243. // to keep in mind that from the standpoint of you, a client of this library,
  244. // all you care about is #1 and #3, and stb libraries do not emphasize #3 above all.
  245. //
  246. // Some secondary priorities arise directly from the first two, some of which
  247. // make more explicit reasons why performance can't be emphasized.
  248. //
  249. // - Portable ("ease of use")
  250. // - Small footprint ("easy to maintain")
  251. // - No dependencies ("ease of use")
  252. //
  253. // ===========================================================================
  254. //
  255. // I/O callbacks
  256. //
  257. // I/O callbacks allow you to read from arbitrary sources, like packaged
  258. // files or some other source. Data read from callbacks are processed
  259. // through a small internal buffer (currently 128 bytes) to try to reduce
  260. // overhead.
  261. //
  262. // The three functions you must define are "read" (reads some bytes of data),
  263. // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
  264. //
  265. // ===========================================================================
  266. //
  267. // SIMD support
  268. //
  269. // The JPEG decoder will try to automatically use SIMD kernels on x86 when
  270. // supported by the compiler. For ARM Neon support, you must explicitly
  271. // request it.
  272. //
  273. // (The old do-it-yourself SIMD API is no longer supported in the current
  274. // code.)
  275. //
  276. // On x86, SSE2 will automatically be used when available based on a run-time
  277. // test; if not, the generic C versions are used as a fall-back. On ARM targets,
  278. // the typical path is to have separate builds for NEON and non-NEON devices
  279. // (at least this is true for iOS and Android). Therefore, the NEON support is
  280. // toggled by a build flag: define STBI_NEON to get NEON loops.
  281. //
  282. // The output of the JPEG decoder is slightly different from versions where
  283. // SIMD support was introduced (that is, for versions before 1.49). The
  284. // difference is only +-1 in the 8-bit RGB channels, and only on a small
  285. // fraction of pixels. You can force the pre-1.49 behavior by defining
  286. // STBI_JPEG_OLD, but this will disable some of the SIMD decoding path
  287. // and hence cost some performance.
  288. //
  289. // If for some reason you do not want to use any of SIMD code, or if
  290. // you have issues compiling it, you can disable it entirely by
  291. // defining STBI_NO_SIMD.
  292. //
  293. // ===========================================================================
  294. //
  295. // HDR image support (disable by defining STBI_NO_HDR)
  296. //
  297. // stb_image now supports loading HDR images in general, and currently
  298. // the Radiance .HDR file format, although the support is provided
  299. // generically. You can still load any file through the existing interface;
  300. // if you attempt to load an HDR file, it will be automatically remapped to
  301. // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
  302. // both of these constants can be reconfigured through this interface:
  303. //
  304. // stbi_hdr_to_ldr_gamma(2.2f);
  305. // stbi_hdr_to_ldr_scale(1.0f);
  306. //
  307. // (note, do not use _inverse_ constants; stbi_image will invert them
  308. // appropriately).
  309. //
  310. // Additionally, there is a new, parallel interface for loading files as
  311. // (linear) floats to preserve the full dynamic range:
  312. //
  313. // float *data = stbi_loadf(filename, &x, &y, &n, 0);
  314. //
  315. // If you load LDR images through this interface, those images will
  316. // be promoted to floating point values, run through the inverse of
  317. // constants corresponding to the above:
  318. //
  319. // stbi_ldr_to_hdr_scale(1.0f);
  320. // stbi_ldr_to_hdr_gamma(2.2f);
  321. //
  322. // Finally, given a filename (or an open file or memory block--see header
  323. // file for details) containing image data, you can query for the "most
  324. // appropriate" interface to use (that is, whether the image is HDR or
  325. // not), using:
  326. //
  327. // stbi_is_hdr(char *filename);
  328. //
  329. // ===========================================================================
  330. //
  331. // iPhone PNG support:
  332. //
  333. // By default we convert iphone-formatted PNGs back to RGB, even though
  334. // they are internally encoded differently. You can disable this conversion
  335. // by by calling stbi_convert_iphone_png_to_rgb(0), in which case
  336. // you will always just get the native iphone "format" through (which
  337. // is BGR stored in RGB).
  338. //
  339. // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
  340. // pixel to remove any premultiplied alpha *only* if the image file explicitly
  341. // says there's premultiplied data (currently only happens in iPhone images,
  342. // and only if iPhone convert-to-rgb processing is on).
  343. //
  344. #define STBI_NO_STDIO
  345. #ifndef STBI_NO_STDIO
  346. #include <stdio.h>
  347. #endif // STBI_NO_STDIO
  348. #define STBI_VERSION 1
  349. enum
  350. {
  351. STBI_default = 0, // only used for req_comp
  352. STBI_grey = 1,
  353. STBI_grey_alpha = 2,
  354. STBI_rgb = 3,
  355. STBI_rgb_alpha = 4
  356. };
  357. typedef unsigned char stbi_uc;
  358. #ifdef __cplusplus
  359. extern "C" {
  360. #endif
  361. #ifdef STB_IMAGE_STATIC
  362. #define STBIDEF static
  363. #else
  364. #define STBIDEF extern
  365. #endif
  366. //////////////////////////////////////////////////////////////////////////////
  367. //
  368. // PRIMARY API - works on images of any type
  369. //
  370. //
  371. // load image by filename, open file, or memory buffer
  372. //
  373. typedef struct
  374. {
  375. int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
  376. void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
  377. int (*eof) (void *user); // returns nonzero if we are at end of file/data
  378. } stbi_io_callbacks;
  379. STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
  380. STBIDEF stbi_uc *stbi_load_from_memory (stbi_uc const *buffer, int len , int *x, int *y, int *comp, int req_comp);
  381. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk , void *user, int *x, int *y, int *comp, int req_comp);
  382. #ifndef STBI_NO_STDIO
  383. STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  384. // for stbi_load_from_file, file pointer is left pointing immediately after image
  385. #endif
  386. #ifndef STBI_NO_LINEAR
  387. STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
  388. STBIDEF float *stbi_loadf_from_memory (stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  389. STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  390. #ifndef STBI_NO_STDIO
  391. STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  392. #endif
  393. #endif
  394. #ifndef STBI_NO_HDR
  395. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
  396. STBIDEF void stbi_hdr_to_ldr_scale(float scale);
  397. #endif
  398. #ifndef STBI_NO_LINEAR
  399. STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
  400. STBIDEF void stbi_ldr_to_hdr_scale(float scale);
  401. #endif // STBI_NO_HDR
  402. // stbi_is_hdr is always defined, but always returns false if STBI_NO_HDR
  403. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  404. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
  405. #ifndef STBI_NO_STDIO
  406. STBIDEF int stbi_is_hdr (char const *filename);
  407. STBIDEF int stbi_is_hdr_from_file(FILE *f);
  408. #endif // STBI_NO_STDIO
  409. // get a VERY brief reason for failure
  410. // NOT THREADSAFE
  411. STBIDEF const char *stbi_failure_reason (void);
  412. // free the loaded image -- this is just free()
  413. STBIDEF void stbi_image_free (void *retval_from_stbi_load);
  414. // get image dimensions & components without fully decoding
  415. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
  416. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
  417. #ifndef STBI_NO_STDIO
  418. STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
  419. STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
  420. #endif
  421. // for image formats that explicitly notate that they have premultiplied alpha,
  422. // we just return the colors as stored in the file. set this flag to force
  423. // unpremultiplication. results are undefined if the unpremultiply overflow.
  424. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
  425. // indicate whether we should process iphone images back to canonical format,
  426. // or just pass them through "as-is"
  427. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
  428. // flip the image vertically, so the first pixel in the output array is the bottom left
  429. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip);
  430. // ZLIB client - used by PNG, available for other purposes
  431. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
  432. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
  433. STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
  434. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  435. STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
  436. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  437. #ifdef __cplusplus
  438. }
  439. #endif
  440. //
  441. //
  442. //// end header file /////////////////////////////////////////////////////
  443. #endif // STBI_INCLUDE_STB_IMAGE_H
  444. #ifdef STB_IMAGE_IMPLEMENTATION
  445. #if defined(STBI_ONLY_JPEG) || defined(STBI_ONLY_PNG) || defined(STBI_ONLY_BMP) \
  446. || defined(STBI_ONLY_TGA) || defined(STBI_ONLY_GIF) || defined(STBI_ONLY_PSD) \
  447. || defined(STBI_ONLY_HDR) || defined(STBI_ONLY_PIC) || defined(STBI_ONLY_PNM) \
  448. || defined(STBI_ONLY_ZLIB)
  449. #ifndef STBI_ONLY_JPEG
  450. #define STBI_NO_JPEG
  451. #endif
  452. #ifndef STBI_ONLY_PNG
  453. #define STBI_NO_PNG
  454. #endif
  455. #ifndef STBI_ONLY_BMP
  456. #define STBI_NO_BMP
  457. #endif
  458. #ifndef STBI_ONLY_PSD
  459. #define STBI_NO_PSD
  460. #endif
  461. #ifndef STBI_ONLY_TGA
  462. #define STBI_NO_TGA
  463. #endif
  464. #ifndef STBI_ONLY_GIF
  465. #define STBI_NO_GIF
  466. #endif
  467. #ifndef STBI_ONLY_HDR
  468. #define STBI_NO_HDR
  469. #endif
  470. #ifndef STBI_ONLY_PIC
  471. #define STBI_NO_PIC
  472. #endif
  473. #ifndef STBI_ONLY_PNM
  474. #define STBI_NO_PNM
  475. #endif
  476. #endif
  477. #if defined(STBI_NO_PNG) && !defined(STBI_SUPPORT_ZLIB) && !defined(STBI_NO_ZLIB)
  478. #define STBI_NO_ZLIB
  479. #endif
  480. #include <stdarg.h>
  481. #include <stddef.h> // ptrdiff_t on osx
  482. #include <stdlib.h>
  483. #include <string.h>
  484. #if !defined(STBI_NO_LINEAR) || !defined(STBI_NO_HDR)
  485. #include <math.h> // ldexp
  486. #endif
  487. #ifndef STBI_NO_STDIO
  488. #include <stdio.h>
  489. #endif
  490. #ifndef STBI_ASSERT
  491. #include <assert.h>
  492. #define STBI_ASSERT(x) assert(x)
  493. #endif
  494. #ifndef _MSC_VER
  495. #ifdef __cplusplus
  496. #define stbi_inline inline
  497. #else
  498. #define stbi_inline
  499. #endif
  500. #else
  501. #define stbi_inline __forceinline
  502. #endif
  503. #ifdef _MSC_VER
  504. typedef unsigned short stbi__uint16;
  505. typedef signed short stbi__int16;
  506. typedef unsigned int stbi__uint32;
  507. typedef signed int stbi__int32;
  508. #else
  509. #include <stdint.h>
  510. typedef uint16_t stbi__uint16;
  511. typedef int16_t stbi__int16;
  512. typedef uint32_t stbi__uint32;
  513. typedef int32_t stbi__int32;
  514. #endif
  515. // should produce compiler error if size is wrong
  516. typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
  517. #ifdef _MSC_VER
  518. #define STBI_NOTUSED(v) (void)(v)
  519. #else
  520. #define STBI_NOTUSED(v) (void)sizeof(v)
  521. #endif
  522. #ifdef _MSC_VER
  523. #define STBI_HAS_LROTL
  524. #endif
  525. #ifdef STBI_HAS_LROTL
  526. #define stbi_lrot(x,y) _lrotl(x,y)
  527. #else
  528. #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
  529. #endif
  530. #if defined(STBI_MALLOC) && defined(STBI_FREE) && defined(STBI_REALLOC)
  531. // ok
  532. #elif !defined(STBI_MALLOC) && !defined(STBI_FREE) && !defined(STBI_REALLOC)
  533. // ok
  534. #else
  535. #error "Must define all or none of STBI_MALLOC, STBI_FREE, and STBI_REALLOC."
  536. #endif
  537. #ifndef STBI_MALLOC
  538. #define STBI_MALLOC(sz) malloc(sz)
  539. #define STBI_REALLOC(p,sz) realloc(p,sz)
  540. #define STBI_FREE(p) free(p)
  541. #endif
  542. // x86/x64 detection
  543. #if defined(__x86_64__) || defined(_M_X64)
  544. #define STBI__X64_TARGET
  545. #elif defined(__i386) || defined(_M_IX86)
  546. #define STBI__X86_TARGET
  547. #endif
  548. #if defined(__GNUC__) && (defined(STBI__X86_TARGET) || defined(STBI__X64_TARGET)) && !defined(__SSE2__) && !defined(STBI_NO_SIMD)
  549. // NOTE: not clear do we actually need this for the 64-bit path?
  550. // gcc doesn't support sse2 intrinsics unless you compile with -msse2,
  551. // (but compiling with -msse2 allows the compiler to use SSE2 everywhere;
  552. // this is just broken and gcc are jerks for not fixing it properly
  553. // http://www.virtualdub.org/blog/pivot/entry.php?id=363 )
  554. #define STBI_NO_SIMD
  555. #endif
  556. #if defined(__MINGW32__) && defined(STBI__X86_TARGET) && !defined(STBI_MINGW_ENABLE_SSE2) && !defined(STBI_NO_SIMD)
  557. // Note that __MINGW32__ doesn't actually mean 32-bit, so we have to avoid STBI__X64_TARGET
  558. //
  559. // 32-bit MinGW wants ESP to be 16-byte aligned, but this is not in the
  560. // Windows ABI and VC++ as well as Windows DLLs don't maintain that invariant.
  561. // As a result, enabling SSE2 on 32-bit MinGW is dangerous when not
  562. // simultaneously enabling "-mstackrealign".
  563. //
  564. // See https://github.com/nothings/stb/issues/81 for more information.
  565. //
  566. // So default to no SSE2 on 32-bit MinGW. If you've read this far and added
  567. // -mstackrealign to your build settings, feel free to #define STBI_MINGW_ENABLE_SSE2.
  568. #define STBI_NO_SIMD
  569. #endif
  570. #if !defined(STBI_NO_SIMD) && defined(STBI__X86_TARGET)
  571. #define STBI_SSE2
  572. #include <emmintrin.h>
  573. #ifdef _MSC_VER
  574. #if _MSC_VER >= 1400 // not VC6
  575. #include <intrin.h> // __cpuid
  576. static int stbi__cpuid3(void)
  577. {
  578. int info[4];
  579. __cpuid(info,1);
  580. return info[3];
  581. }
  582. #else
  583. static int stbi__cpuid3(void)
  584. {
  585. int res;
  586. __asm {
  587. mov eax,1
  588. cpuid
  589. mov res,edx
  590. }
  591. return res;
  592. }
  593. #endif
  594. #define STBI_SIMD_ALIGN(type, name) __declspec(align(16)) type name
  595. static int stbi__sse2_available()
  596. {
  597. int info3 = stbi__cpuid3();
  598. return ((info3 >> 26) & 1) != 0;
  599. }
  600. #else // assume GCC-style if not VC++
  601. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  602. static int stbi__sse2_available()
  603. {
  604. #if defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 408 // GCC 4.8 or later
  605. // GCC 4.8+ has a nice way to do this
  606. return __builtin_cpu_supports("sse2");
  607. #else
  608. // portable way to do this, preferably without using GCC inline ASM?
  609. // just bail for now.
  610. return 0;
  611. #endif
  612. }
  613. #endif
  614. #endif
  615. // ARM NEON
  616. #if defined(STBI_NO_SIMD) && defined(STBI_NEON)
  617. #undef STBI_NEON
  618. #endif
  619. #ifdef STBI_NEON
  620. #include <arm_neon.h>
  621. // assume GCC or Clang on ARM targets
  622. #define STBI_SIMD_ALIGN(type, name) type name __attribute__((aligned(16)))
  623. #endif
  624. #ifndef STBI_SIMD_ALIGN
  625. #define STBI_SIMD_ALIGN(type, name) type name
  626. #endif
  627. ///////////////////////////////////////////////
  628. //
  629. // stbi__context struct and start_xxx functions
  630. // stbi__context structure is our basic context used by all images, so it
  631. // contains all the IO context, plus some basic image information
  632. typedef struct
  633. {
  634. stbi__uint32 img_x, img_y;
  635. int img_n, img_out_n;
  636. stbi_io_callbacks io;
  637. void *io_user_data;
  638. int read_from_callbacks;
  639. int buflen;
  640. stbi_uc buffer_start[128];
  641. stbi_uc *img_buffer, *img_buffer_end;
  642. stbi_uc *img_buffer_original;
  643. } stbi__context;
  644. static void stbi__refill_buffer(stbi__context *s);
  645. // initialize a memory-decode context
  646. static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
  647. {
  648. s->io.read = NULL;
  649. s->read_from_callbacks = 0;
  650. s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
  651. s->img_buffer_end = (stbi_uc *) buffer+len;
  652. }
  653. // initialize a callback-based context
  654. static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
  655. {
  656. s->io = *c;
  657. s->io_user_data = user;
  658. s->buflen = sizeof(s->buffer_start);
  659. s->read_from_callbacks = 1;
  660. s->img_buffer_original = s->buffer_start;
  661. stbi__refill_buffer(s);
  662. }
  663. #ifndef STBI_NO_STDIO
  664. static int stbi__stdio_read(void *user, char *data, int size)
  665. {
  666. return (int) fread(data,1,size,(FILE*) user);
  667. }
  668. static void stbi__stdio_skip(void *user, int n)
  669. {
  670. fseek((FILE*) user, n, SEEK_CUR);
  671. }
  672. static int stbi__stdio_eof(void *user)
  673. {
  674. return feof((FILE*) user);
  675. }
  676. static stbi_io_callbacks stbi__stdio_callbacks =
  677. {
  678. stbi__stdio_read,
  679. stbi__stdio_skip,
  680. stbi__stdio_eof,
  681. };
  682. static void stbi__start_file(stbi__context *s, FILE *f)
  683. {
  684. stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
  685. }
  686. //static void stop_file(stbi__context *s) { }
  687. #endif // !STBI_NO_STDIO
  688. static void stbi__rewind(stbi__context *s)
  689. {
  690. // conceptually rewind SHOULD rewind to the beginning of the stream,
  691. // but we just rewind to the beginning of the initial buffer, because
  692. // we only use it after doing 'test', which only ever looks at at most 92 bytes
  693. s->img_buffer = s->img_buffer_original;
  694. }
  695. #ifndef STBI_NO_JPEG
  696. static int stbi__jpeg_test(stbi__context *s);
  697. static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  698. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
  699. #endif
  700. #ifndef STBI_NO_PNG
  701. static int stbi__png_test(stbi__context *s);
  702. static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  703. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
  704. #endif
  705. #ifndef STBI_NO_BMP
  706. static int stbi__bmp_test(stbi__context *s);
  707. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  708. static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp);
  709. #endif
  710. #ifndef STBI_NO_TGA
  711. static int stbi__tga_test(stbi__context *s);
  712. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  713. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
  714. #endif
  715. #ifndef STBI_NO_PSD
  716. static int stbi__psd_test(stbi__context *s);
  717. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  718. static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp);
  719. #endif
  720. #ifndef STBI_NO_HDR
  721. static int stbi__hdr_test(stbi__context *s);
  722. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  723. static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp);
  724. #endif
  725. #ifndef STBI_NO_PIC
  726. static int stbi__pic_test(stbi__context *s);
  727. static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  728. static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp);
  729. #endif
  730. #ifndef STBI_NO_GIF
  731. static int stbi__gif_test(stbi__context *s);
  732. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  733. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
  734. #endif
  735. #ifndef STBI_NO_PNM
  736. static int stbi__pnm_test(stbi__context *s);
  737. static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  738. static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp);
  739. #endif
  740. // this is not threadsafe
  741. static const char *stbi__g_failure_reason;
  742. STBIDEF const char *stbi_failure_reason(void)
  743. {
  744. return stbi__g_failure_reason;
  745. }
  746. static int stbi__err(const char *str)
  747. {
  748. stbi__g_failure_reason = str;
  749. return 0;
  750. }
  751. static void *stbi__malloc(size_t size)
  752. {
  753. return STBI_MALLOC(size);
  754. }
  755. // stbi__err - error
  756. // stbi__errpf - error returning pointer to float
  757. // stbi__errpuc - error returning pointer to unsigned char
  758. #ifdef STBI_NO_FAILURE_STRINGS
  759. #define stbi__err(x,y) 0
  760. #elif defined(STBI_FAILURE_USERMSG)
  761. #define stbi__err(x,y) stbi__err(y)
  762. #else
  763. #define stbi__err(x,y) stbi__err(x)
  764. #endif
  765. #define stbi__errpf(x,y) ((float *) (stbi__err(x,y)?NULL:NULL))
  766. #define stbi__errpuc(x,y) ((unsigned char *) (stbi__err(x,y)?NULL:NULL))
  767. STBIDEF void stbi_image_free(void *retval_from_stbi_load)
  768. {
  769. STBI_FREE(retval_from_stbi_load);
  770. }
  771. #ifndef STBI_NO_LINEAR
  772. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
  773. #endif
  774. #ifndef STBI_NO_HDR
  775. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
  776. #endif
  777. static int stbi__vertically_flip_on_load = 1;
  778. STBIDEF void stbi_set_flip_vertically_on_load(int flag_true_if_should_flip)
  779. {
  780. stbi__vertically_flip_on_load = flag_true_if_should_flip;
  781. }
  782. static unsigned char *stbi__load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  783. {
  784. #ifndef STBI_NO_JPEG
  785. if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);
  786. #endif
  787. #ifndef STBI_NO_PNG
  788. if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);
  789. #endif
  790. #ifndef STBI_NO_BMP
  791. if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);
  792. #endif
  793. #ifndef STBI_NO_GIF
  794. if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);
  795. #endif
  796. #ifndef STBI_NO_PSD
  797. if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);
  798. #endif
  799. #ifndef STBI_NO_PIC
  800. if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);
  801. #endif
  802. #ifndef STBI_NO_PNM
  803. if (stbi__pnm_test(s)) return stbi__pnm_load(s,x,y,comp,req_comp);
  804. #endif
  805. #ifndef STBI_NO_HDR
  806. if (stbi__hdr_test(s)) {
  807. float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);
  808. return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
  809. }
  810. #endif
  811. #ifndef STBI_NO_TGA
  812. // test tga last because it's a crappy test!
  813. if (stbi__tga_test(s))
  814. return stbi__tga_load(s,x,y,comp,req_comp);
  815. #endif
  816. return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
  817. }
  818. static unsigned char *stbi__load_flip(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  819. {
  820. unsigned char *result = stbi__load_main(s, x, y, comp, req_comp);
  821. if (stbi__vertically_flip_on_load && result != NULL) {
  822. int w = *x, h = *y;
  823. int depth = req_comp ? req_comp : *comp;
  824. int row,col,z;
  825. stbi_uc temp;
  826. // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once
  827. for (row = 0; row < (h>>1); row++) {
  828. for (col = 0; col < w; col++) {
  829. for (z = 0; z < depth; z++) {
  830. temp = result[(row * w + col) * depth + z];
  831. result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];
  832. result[((h - row - 1) * w + col) * depth + z] = temp;
  833. }
  834. }
  835. }
  836. }
  837. return result;
  838. }
  839. static void stbi__float_postprocess(float *result, int *x, int *y, int *comp, int req_comp)
  840. {
  841. if (stbi__vertically_flip_on_load && result != NULL) {
  842. int w = *x, h = *y;
  843. int depth = req_comp ? req_comp : *comp;
  844. int row,col,z;
  845. float temp;
  846. // @OPTIMIZE: use a bigger temp buffer and memcpy multiple pixels at once
  847. for (row = 0; row < (h>>1); row++) {
  848. for (col = 0; col < w; col++) {
  849. for (z = 0; z < depth; z++) {
  850. temp = result[(row * w + col) * depth + z];
  851. result[(row * w + col) * depth + z] = result[((h - row - 1) * w + col) * depth + z];
  852. result[((h - row - 1) * w + col) * depth + z] = temp;
  853. }
  854. }
  855. }
  856. }
  857. }
  858. #ifndef STBI_NO_STDIO
  859. static FILE *stbi__fopen(char const *filename, char const *mode)
  860. {
  861. FILE *f;
  862. #if defined(_MSC_VER) && _MSC_VER >= 1400
  863. if (0 != fopen_s(&f, filename, mode))
  864. f=0;
  865. #else
  866. f = fopen(filename, mode);
  867. #endif
  868. return f;
  869. }
  870. STBIDEF stbi_uc *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
  871. {
  872. FILE *f = stbi__fopen(filename, "rb");
  873. unsigned char *result;
  874. if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
  875. result = stbi_load_from_file(f,x,y,comp,req_comp);
  876. fclose(f);
  877. return result;
  878. }
  879. STBIDEF stbi_uc *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  880. {
  881. unsigned char *result;
  882. stbi__context s;
  883. stbi__start_file(&s,f);
  884. result = stbi__load_flip(&s,x,y,comp,req_comp);
  885. if (result) {
  886. // need to 'unget' all the characters in the IO buffer
  887. fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
  888. }
  889. return result;
  890. }
  891. #endif //!STBI_NO_STDIO
  892. STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  893. {
  894. stbi__context s;
  895. stbi__start_mem(&s,buffer,len);
  896. return stbi__load_flip(&s,x,y,comp,req_comp);
  897. }
  898. STBIDEF stbi_uc *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  899. {
  900. stbi__context s;
  901. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  902. return stbi__load_flip(&s,x,y,comp,req_comp);
  903. }
  904. #ifndef STBI_NO_LINEAR
  905. static float *stbi__loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  906. {
  907. unsigned char *data;
  908. #ifndef STBI_NO_HDR
  909. if (stbi__hdr_test(s)) {
  910. float *hdr_data = stbi__hdr_load(s,x,y,comp,req_comp);
  911. if (hdr_data)
  912. stbi__float_postprocess(hdr_data,x,y,comp,req_comp);
  913. return hdr_data;
  914. }
  915. #endif
  916. data = stbi__load_flip(s, x, y, comp, req_comp);
  917. if (data)
  918. return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
  919. return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
  920. }
  921. STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  922. {
  923. stbi__context s;
  924. stbi__start_mem(&s,buffer,len);
  925. return stbi__loadf_main(&s,x,y,comp,req_comp);
  926. }
  927. STBIDEF float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  928. {
  929. stbi__context s;
  930. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  931. return stbi__loadf_main(&s,x,y,comp,req_comp);
  932. }
  933. #ifndef STBI_NO_STDIO
  934. STBIDEF float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
  935. {
  936. float *result;
  937. FILE *f = stbi__fopen(filename, "rb");
  938. if (!f) return stbi__errpf("can't fopen", "Unable to open file");
  939. result = stbi_loadf_from_file(f,x,y,comp,req_comp);
  940. fclose(f);
  941. return result;
  942. }
  943. STBIDEF float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  944. {
  945. stbi__context s;
  946. stbi__start_file(&s,f);
  947. return stbi__loadf_main(&s,x,y,comp,req_comp);
  948. }
  949. #endif // !STBI_NO_STDIO
  950. #endif // !STBI_NO_LINEAR
  951. // these is-hdr-or-not is defined independent of whether STBI_NO_LINEAR is
  952. // defined, for API simplicity; if STBI_NO_LINEAR is defined, it always
  953. // reports false!
  954. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
  955. {
  956. #ifndef STBI_NO_HDR
  957. stbi__context s;
  958. stbi__start_mem(&s,buffer,len);
  959. return stbi__hdr_test(&s);
  960. #else
  961. STBI_NOTUSED(buffer);
  962. STBI_NOTUSED(len);
  963. return 0;
  964. #endif
  965. }
  966. #ifndef STBI_NO_STDIO
  967. STBIDEF int stbi_is_hdr (char const *filename)
  968. {
  969. FILE *f = stbi__fopen(filename, "rb");
  970. int result=0;
  971. if (f) {
  972. result = stbi_is_hdr_from_file(f);
  973. fclose(f);
  974. }
  975. return result;
  976. }
  977. STBIDEF int stbi_is_hdr_from_file(FILE *f)
  978. {
  979. #ifndef STBI_NO_HDR
  980. stbi__context s;
  981. stbi__start_file(&s,f);
  982. return stbi__hdr_test(&s);
  983. #else
  984. return 0;
  985. #endif
  986. }
  987. #endif // !STBI_NO_STDIO
  988. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
  989. {
  990. #ifndef STBI_NO_HDR
  991. stbi__context s;
  992. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  993. return stbi__hdr_test(&s);
  994. #else
  995. return 0;
  996. #endif
  997. }
  998. static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
  999. static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
  1000. #ifndef STBI_NO_LINEAR
  1001. STBIDEF void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
  1002. STBIDEF void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
  1003. #endif
  1004. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
  1005. STBIDEF void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
  1006. //////////////////////////////////////////////////////////////////////////////
  1007. //
  1008. // Common code used by all image loaders
  1009. //
  1010. enum
  1011. {
  1012. STBI__SCAN_load=0,
  1013. STBI__SCAN_type,
  1014. STBI__SCAN_header
  1015. };
  1016. static void stbi__refill_buffer(stbi__context *s)
  1017. {
  1018. int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
  1019. if (n == 0) {
  1020. // at end of file, treat same as if from memory, but need to handle case
  1021. // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
  1022. s->read_from_callbacks = 0;
  1023. s->img_buffer = s->buffer_start;
  1024. s->img_buffer_end = s->buffer_start+1;
  1025. *s->img_buffer = 0;
  1026. } else {
  1027. s->img_buffer = s->buffer_start;
  1028. s->img_buffer_end = s->buffer_start + n;
  1029. }
  1030. }
  1031. stbi_inline static stbi_uc stbi__get8(stbi__context *s)
  1032. {
  1033. if (s->img_buffer < s->img_buffer_end)
  1034. return *s->img_buffer++;
  1035. if (s->read_from_callbacks) {
  1036. stbi__refill_buffer(s);
  1037. return *s->img_buffer++;
  1038. }
  1039. return 0;
  1040. }
  1041. stbi_inline static int stbi__at_eof(stbi__context *s)
  1042. {
  1043. if (s->io.read) {
  1044. if (!(s->io.eof)(s->io_user_data)) return 0;
  1045. // if feof() is true, check if buffer = end
  1046. // special case: we've only got the special 0 character at the end
  1047. if (s->read_from_callbacks == 0) return 1;
  1048. }
  1049. return s->img_buffer >= s->img_buffer_end;
  1050. }
  1051. static void stbi__skip(stbi__context *s, int n)
  1052. {
  1053. if (n < 0) {
  1054. s->img_buffer = s->img_buffer_end;
  1055. return;
  1056. }
  1057. if (s->io.read) {
  1058. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1059. if (blen < n) {
  1060. s->img_buffer = s->img_buffer_end;
  1061. (s->io.skip)(s->io_user_data, n - blen);
  1062. return;
  1063. }
  1064. }
  1065. s->img_buffer += n;
  1066. }
  1067. static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
  1068. {
  1069. if (s->io.read) {
  1070. int blen = (int) (s->img_buffer_end - s->img_buffer);
  1071. if (blen < n) {
  1072. int res, count;
  1073. memcpy(buffer, s->img_buffer, blen);
  1074. count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
  1075. res = (count == (n-blen));
  1076. s->img_buffer = s->img_buffer_end;
  1077. return res;
  1078. }
  1079. }
  1080. if (s->img_buffer+n <= s->img_buffer_end) {
  1081. memcpy(buffer, s->img_buffer, n);
  1082. s->img_buffer += n;
  1083. return 1;
  1084. } else
  1085. return 0;
  1086. }
  1087. static int stbi__get16be(stbi__context *s)
  1088. {
  1089. int z = stbi__get8(s);
  1090. return (z << 8) + stbi__get8(s);
  1091. }
  1092. static stbi__uint32 stbi__get32be(stbi__context *s)
  1093. {
  1094. stbi__uint32 z = stbi__get16be(s);
  1095. return (z << 16) + stbi__get16be(s);
  1096. }
  1097. static int stbi__get16le(stbi__context *s)
  1098. {
  1099. int z = stbi__get8(s);
  1100. return z + (stbi__get8(s) << 8);
  1101. }
  1102. static stbi__uint32 stbi__get32le(stbi__context *s)
  1103. {
  1104. stbi__uint32 z = stbi__get16le(s);
  1105. return z + (stbi__get16le(s) << 16);
  1106. }
  1107. #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
  1108. //////////////////////////////////////////////////////////////////////////////
  1109. //
  1110. // generic converter from built-in img_n to req_comp
  1111. // individual types do this automatically as much as possible (e.g. jpeg
  1112. // does all cases internally since it needs to colorspace convert anyway,
  1113. // and it never has alpha, so very few cases ). png can automatically
  1114. // interleave an alpha=255 channel, but falls back to this for other cases
  1115. //
  1116. // assume data buffer is malloced, so malloc a new one and free that one
  1117. // only failure mode is malloc failing
  1118. static stbi_uc stbi__compute_y(int r, int g, int b)
  1119. {
  1120. return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
  1121. }
  1122. static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
  1123. {
  1124. int i,j;
  1125. unsigned char *good;
  1126. if (req_comp == img_n) return data;
  1127. STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
  1128. good = (unsigned char *) stbi__malloc(req_comp * x * y);
  1129. if (good == NULL) {
  1130. STBI_FREE(data);
  1131. return stbi__errpuc("outofmem", "Out of memory");
  1132. }
  1133. for (j=0; j < (int) y; ++j) {
  1134. unsigned char *src = data + j * x * img_n ;
  1135. unsigned char *dest = good + j * x * req_comp;
  1136. #define COMBO(a,b) ((a)*8+(b))
  1137. #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  1138. // convert source image with img_n components to one with req_comp components;
  1139. // avoid switch per pixel, so use switch per scanline and massive macros
  1140. switch (COMBO(img_n, req_comp)) {
  1141. CASE(1,2) dest[0]=src[0], dest[1]=255; break;
  1142. CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  1143. CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
  1144. CASE(2,1) dest[0]=src[0]; break;
  1145. CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  1146. CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
  1147. CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
  1148. CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  1149. CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
  1150. CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  1151. CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
  1152. CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
  1153. default: STBI_ASSERT(0);
  1154. }
  1155. #undef CASE
  1156. }
  1157. STBI_FREE(data);
  1158. return good;
  1159. }
  1160. #ifndef STBI_NO_LINEAR
  1161. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
  1162. {
  1163. int i,k,n;
  1164. float *output = (float *) stbi__malloc(x * y * comp * sizeof(float));
  1165. if (output == NULL) { STBI_FREE(data); return stbi__errpf("outofmem", "Out of memory"); }
  1166. // compute number of non-alpha components
  1167. if (comp & 1) n = comp; else n = comp-1;
  1168. for (i=0; i < x*y; ++i) {
  1169. for (k=0; k < n; ++k) {
  1170. output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
  1171. }
  1172. if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
  1173. }
  1174. STBI_FREE(data);
  1175. return output;
  1176. }
  1177. #endif
  1178. #ifndef STBI_NO_HDR
  1179. #define stbi__float2int(x) ((int) (x))
  1180. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
  1181. {
  1182. int i,k,n;
  1183. stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp);
  1184. if (output == NULL) { STBI_FREE(data); return stbi__errpuc("outofmem", "Out of memory"); }
  1185. // compute number of non-alpha components
  1186. if (comp & 1) n = comp; else n = comp-1;
  1187. for (i=0; i < x*y; ++i) {
  1188. for (k=0; k < n; ++k) {
  1189. float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
  1190. if (z < 0) z = 0;
  1191. if (z > 255) z = 255;
  1192. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  1193. }
  1194. if (k < comp) {
  1195. float z = data[i*comp+k] * 255 + 0.5f;
  1196. if (z < 0) z = 0;
  1197. if (z > 255) z = 255;
  1198. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  1199. }
  1200. }
  1201. STBI_FREE(data);
  1202. return output;
  1203. }
  1204. #endif
  1205. //////////////////////////////////////////////////////////////////////////////
  1206. //
  1207. // "baseline" JPEG/JFIF decoder
  1208. //
  1209. // simple implementation
  1210. // - doesn't support delayed output of y-dimension
  1211. // - simple interface (only one output format: 8-bit interleaved RGB)
  1212. // - doesn't try to recover corrupt jpegs
  1213. // - doesn't allow partial loading, loading multiple at once
  1214. // - still fast on x86 (copying globals into locals doesn't help x86)
  1215. // - allocates lots of intermediate memory (full size of all components)
  1216. // - non-interleaved case requires this anyway
  1217. // - allows good upsampling (see next)
  1218. // high-quality
  1219. // - upsampled channels are bilinearly interpolated, even across blocks
  1220. // - quality integer IDCT derived from IJG's 'slow'
  1221. // performance
  1222. // - fast huffman; reasonable integer IDCT
  1223. // - some SIMD kernels for common paths on targets with SSE2/NEON
  1224. // - uses a lot of intermediate memory, could cache poorly
  1225. #ifndef STBI_NO_JPEG
  1226. // huffman decoding acceleration
  1227. #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
  1228. typedef struct
  1229. {
  1230. stbi_uc fast[1 << FAST_BITS];
  1231. // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
  1232. stbi__uint16 code[256];
  1233. stbi_uc values[256];
  1234. stbi_uc size[257];
  1235. unsigned int maxcode[18];
  1236. int delta[17]; // old 'firstsymbol' - old 'firstcode'
  1237. } stbi__huffman;
  1238. typedef struct
  1239. {
  1240. stbi__context *s;
  1241. stbi__huffman huff_dc[4];
  1242. stbi__huffman huff_ac[4];
  1243. stbi_uc dequant[4][64];
  1244. stbi__int16 fast_ac[4][1 << FAST_BITS];
  1245. // sizes for components, interleaved MCUs
  1246. int img_h_max, img_v_max;
  1247. int img_mcu_x, img_mcu_y;
  1248. int img_mcu_w, img_mcu_h;
  1249. // definition of jpeg image component
  1250. struct
  1251. {
  1252. int id;
  1253. int h,v;
  1254. int tq;
  1255. int hd,ha;
  1256. int dc_pred;
  1257. int x,y,w2,h2;
  1258. stbi_uc *data;
  1259. void *raw_data, *raw_coeff;
  1260. stbi_uc *linebuf;
  1261. short *coeff; // progressive only
  1262. int coeff_w, coeff_h; // number of 8x8 coefficient blocks
  1263. } img_comp[4];
  1264. stbi__uint32 code_buffer; // jpeg entropy-coded buffer
  1265. int code_bits; // number of valid bits
  1266. unsigned char marker; // marker seen while filling entropy buffer
  1267. int nomore; // flag if we saw a marker so must stop
  1268. int progressive;
  1269. int spec_start;
  1270. int spec_end;
  1271. int succ_high;
  1272. int succ_low;
  1273. int eob_run;
  1274. int scan_n, order[4];
  1275. int restart_interval, todo;
  1276. // kernels
  1277. void (*idct_block_kernel)(stbi_uc *out, int out_stride, short data[64]);
  1278. void (*YCbCr_to_RGB_kernel)(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step);
  1279. stbi_uc *(*resample_row_hv_2_kernel)(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs);
  1280. } stbi__jpeg;
  1281. static int stbi__build_huffman(stbi__huffman *h, int *count)
  1282. {
  1283. int i,j,k=0,code;
  1284. // build size list for each symbol (from JPEG spec)
  1285. for (i=0; i < 16; ++i)
  1286. for (j=0; j < count[i]; ++j)
  1287. h->size[k++] = (stbi_uc) (i+1);
  1288. h->size[k] = 0;
  1289. // compute actual symbols (from jpeg spec)
  1290. code = 0;
  1291. k = 0;
  1292. for(j=1; j <= 16; ++j) {
  1293. // compute delta to add to code to compute symbol id
  1294. h->delta[j] = k - code;
  1295. if (h->size[k] == j) {
  1296. while (h->size[k] == j)
  1297. h->code[k++] = (stbi__uint16) (code++);
  1298. if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG");
  1299. }
  1300. // compute largest code + 1 for this size, preshifted as needed later
  1301. h->maxcode[j] = code << (16-j);
  1302. code <<= 1;
  1303. }
  1304. h->maxcode[j] = 0xffffffff;
  1305. // build non-spec acceleration table; 255 is flag for not-accelerated
  1306. memset(h->fast, 255, 1 << FAST_BITS);
  1307. for (i=0; i < k; ++i) {
  1308. int s = h->size[i];
  1309. if (s <= FAST_BITS) {
  1310. int c = h->code[i] << (FAST_BITS-s);
  1311. int m = 1 << (FAST_BITS-s);
  1312. for (j=0; j < m; ++j) {
  1313. h->fast[c+j] = (stbi_uc) i;
  1314. }
  1315. }
  1316. }
  1317. return 1;
  1318. }
  1319. // build a table that decodes both magnitude and value of small ACs in
  1320. // one go.
  1321. static void stbi__build_fast_ac(stbi__int16 *fast_ac, stbi__huffman *h)
  1322. {
  1323. int i;
  1324. for (i=0; i < (1 << FAST_BITS); ++i) {
  1325. stbi_uc fast = h->fast[i];
  1326. fast_ac[i] = 0;
  1327. if (fast < 255) {
  1328. int rs = h->values[fast];
  1329. int run = (rs >> 4) & 15;
  1330. int magbits = rs & 15;
  1331. int len = h->size[fast];
  1332. if (magbits && len + magbits <= FAST_BITS) {
  1333. // magnitude code followed by receive_extend code
  1334. int k = ((i << len) & ((1 << FAST_BITS) - 1)) >> (FAST_BITS - magbits);
  1335. int m = 1 << (magbits - 1);
  1336. if (k < m) k += (-1 << magbits) + 1;
  1337. // if the result is small enough, we can fit it in fast_ac table
  1338. if (k >= -128 && k <= 127)
  1339. fast_ac[i] = (stbi__int16) ((k << 8) + (run << 4) + (len + magbits));
  1340. }
  1341. }
  1342. }
  1343. }
  1344. static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
  1345. {
  1346. do {
  1347. int b = j->nomore ? 0 : stbi__get8(j->s);
  1348. if (b == 0xff) {
  1349. int c = stbi__get8(j->s);
  1350. if (c != 0) {
  1351. j->marker = (unsigned char) c;
  1352. j->nomore = 1;
  1353. return;
  1354. }
  1355. }
  1356. j->code_buffer |= b << (24 - j->code_bits);
  1357. j->code_bits += 8;
  1358. } while (j->code_bits <= 24);
  1359. }
  1360. // (1 << n) - 1
  1361. static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
  1362. // decode a jpeg huffman value from the bitstream
  1363. stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
  1364. {
  1365. unsigned int temp;
  1366. int c,k;
  1367. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1368. // look at the top FAST_BITS and determine what symbol ID it is,
  1369. // if the code is <= FAST_BITS
  1370. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1371. k = h->fast[c];
  1372. if (k < 255) {
  1373. int s = h->size[k];
  1374. if (s > j->code_bits)
  1375. return -1;
  1376. j->code_buffer <<= s;
  1377. j->code_bits -= s;
  1378. return h->values[k];
  1379. }
  1380. // naive test is to shift the code_buffer down so k bits are
  1381. // valid, then test against maxcode. To speed this up, we've
  1382. // preshifted maxcode left so that it has (16-k) 0s at the
  1383. // end; in other words, regardless of the number of bits, it
  1384. // wants to be compared against something shifted to have 16;
  1385. // that way we don't need to shift inside the loop.
  1386. temp = j->code_buffer >> 16;
  1387. for (k=FAST_BITS+1 ; ; ++k)
  1388. if (temp < h->maxcode[k])
  1389. break;
  1390. if (k == 17) {
  1391. // error! code not found
  1392. j->code_bits -= 16;
  1393. return -1;
  1394. }
  1395. if (k > j->code_bits)
  1396. return -1;
  1397. // convert the huffman code to the symbol id
  1398. c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
  1399. STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
  1400. // convert the id to a symbol
  1401. j->code_bits -= k;
  1402. j->code_buffer <<= k;
  1403. return h->values[c];
  1404. }
  1405. // bias[n] = (-1<<n) + 1
  1406. static int const stbi__jbias[16] = {0,-1,-3,-7,-15,-31,-63,-127,-255,-511,-1023,-2047,-4095,-8191,-16383,-32767};
  1407. // combined JPEG 'receive' and JPEG 'extend', since baseline
  1408. // always extends everything it receives.
  1409. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
  1410. {
  1411. unsigned int k;
  1412. int sgn;
  1413. if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
  1414. sgn = (stbi__int32)j->code_buffer >> 31; // sign bit is always in MSB
  1415. k = stbi_lrot(j->code_buffer, n);
  1416. STBI_ASSERT(n >= 0 && n < (int) (sizeof(stbi__bmask)/sizeof(*stbi__bmask)));
  1417. j->code_buffer = k & ~stbi__bmask[n];
  1418. k &= stbi__bmask[n];
  1419. j->code_bits -= n;
  1420. return k + (stbi__jbias[n] & ~sgn);
  1421. }
  1422. // get some unsigned bits
  1423. stbi_inline static int stbi__jpeg_get_bits(stbi__jpeg *j, int n)
  1424. {
  1425. unsigned int k;
  1426. if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
  1427. k = stbi_lrot(j->code_buffer, n);
  1428. j->code_buffer = k & ~stbi__bmask[n];
  1429. k &= stbi__bmask[n];
  1430. j->code_bits -= n;
  1431. return k;
  1432. }
  1433. stbi_inline static int stbi__jpeg_get_bit(stbi__jpeg *j)
  1434. {
  1435. unsigned int k;
  1436. if (j->code_bits < 1) stbi__grow_buffer_unsafe(j);
  1437. k = j->code_buffer;
  1438. j->code_buffer <<= 1;
  1439. --j->code_bits;
  1440. return k & 0x80000000;
  1441. }
  1442. // given a value that's at position X in the zigzag stream,
  1443. // where does it appear in the 8x8 matrix coded as row-major?
  1444. static stbi_uc stbi__jpeg_dezigzag[64+15] =
  1445. {
  1446. 0, 1, 8, 16, 9, 2, 3, 10,
  1447. 17, 24, 32, 25, 18, 11, 4, 5,
  1448. 12, 19, 26, 33, 40, 48, 41, 34,
  1449. 27, 20, 13, 6, 7, 14, 21, 28,
  1450. 35, 42, 49, 56, 57, 50, 43, 36,
  1451. 29, 22, 15, 23, 30, 37, 44, 51,
  1452. 58, 59, 52, 45, 38, 31, 39, 46,
  1453. 53, 60, 61, 54, 47, 55, 62, 63,
  1454. // let corrupt input sample past end
  1455. 63, 63, 63, 63, 63, 63, 63, 63,
  1456. 63, 63, 63, 63, 63, 63, 63
  1457. };
  1458. // decode one 64-entry block--
  1459. static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, stbi__int16 *fac, int b, stbi_uc *dequant)
  1460. {
  1461. int diff,dc,k;
  1462. int t;
  1463. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1464. t = stbi__jpeg_huff_decode(j, hdc);
  1465. if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1466. // 0 all the ac values now so we can do it 32-bits at a time
  1467. memset(data,0,64*sizeof(data[0]));
  1468. diff = t ? stbi__extend_receive(j, t) : 0;
  1469. dc = j->img_comp[b].dc_pred + diff;
  1470. j->img_comp[b].dc_pred = dc;
  1471. data[0] = (short) (dc * dequant[0]);
  1472. // decode AC components, see JPEG spec
  1473. k = 1;
  1474. do {
  1475. unsigned int zig;
  1476. int c,r,s;
  1477. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1478. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1479. r = fac[c];
  1480. if (r) { // fast-AC path
  1481. k += (r >> 4) & 15; // run
  1482. s = r & 15; // combined length
  1483. j->code_buffer <<= s;
  1484. j->code_bits -= s;
  1485. // decode into unzigzag'd location
  1486. zig = stbi__jpeg_dezigzag[k++];
  1487. data[zig] = (short) ((r >> 8) * dequant[zig]);
  1488. } else {
  1489. int rs = stbi__jpeg_huff_decode(j, hac);
  1490. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1491. s = rs & 15;
  1492. r = rs >> 4;
  1493. if (s == 0) {
  1494. if (rs != 0xf0) break; // end block
  1495. k += 16;
  1496. } else {
  1497. k += r;
  1498. // decode into unzigzag'd location
  1499. zig = stbi__jpeg_dezigzag[k++];
  1500. data[zig] = (short) (stbi__extend_receive(j,s) * dequant[zig]);
  1501. }
  1502. }
  1503. } while (k < 64);
  1504. return 1;
  1505. }
  1506. static int stbi__jpeg_decode_block_prog_dc(stbi__jpeg *j, short data[64], stbi__huffman *hdc, int b)
  1507. {
  1508. int diff,dc;
  1509. int t;
  1510. if (j->spec_end != 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
  1511. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1512. if (j->succ_high == 0) {
  1513. // first scan for DC coefficient, must be first
  1514. memset(data,0,64*sizeof(data[0])); // 0 all the ac values now
  1515. t = stbi__jpeg_huff_decode(j, hdc);
  1516. diff = t ? stbi__extend_receive(j, t) : 0;
  1517. dc = j->img_comp[b].dc_pred + diff;
  1518. j->img_comp[b].dc_pred = dc;
  1519. data[0] = (short) (dc << j->succ_low);
  1520. } else {
  1521. // refinement scan for DC coefficient
  1522. if (stbi__jpeg_get_bit(j))
  1523. data[0] += (short) (1 << j->succ_low);
  1524. }
  1525. return 1;
  1526. }
  1527. // @OPTIMIZE: store non-zigzagged during the decode passes,
  1528. // and only de-zigzag when dequantizing
  1529. static int stbi__jpeg_decode_block_prog_ac(stbi__jpeg *j, short data[64], stbi__huffman *hac, stbi__int16 *fac)
  1530. {
  1531. int k;
  1532. if (j->spec_start == 0) return stbi__err("can't merge dc and ac", "Corrupt JPEG");
  1533. if (j->succ_high == 0) {
  1534. int shift = j->succ_low;
  1535. if (j->eob_run) {
  1536. --j->eob_run;
  1537. return 1;
  1538. }
  1539. k = j->spec_start;
  1540. do {
  1541. unsigned int zig;
  1542. int c,r,s;
  1543. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  1544. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  1545. r = fac[c];
  1546. if (r) { // fast-AC path
  1547. k += (r >> 4) & 15; // run
  1548. s = r & 15; // combined length
  1549. j->code_buffer <<= s;
  1550. j->code_bits -= s;
  1551. zig = stbi__jpeg_dezigzag[k++];
  1552. data[zig] = (short) ((r >> 8) << shift);
  1553. } else {
  1554. int rs = stbi__jpeg_huff_decode(j, hac);
  1555. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1556. s = rs & 15;
  1557. r = rs >> 4;
  1558. if (s == 0) {
  1559. if (r < 15) {
  1560. j->eob_run = (1 << r);
  1561. if (r)
  1562. j->eob_run += stbi__jpeg_get_bits(j, r);
  1563. --j->eob_run;
  1564. break;
  1565. }
  1566. k += 16;
  1567. } else {
  1568. k += r;
  1569. zig = stbi__jpeg_dezigzag[k++];
  1570. data[zig] = (short) (stbi__extend_receive(j,s) << shift);
  1571. }
  1572. }
  1573. } while (k <= j->spec_end);
  1574. } else {
  1575. // refinement scan for these AC coefficients
  1576. short bit = (short) (1 << j->succ_low);
  1577. if (j->eob_run) {
  1578. --j->eob_run;
  1579. for (k = j->spec_start; k <= j->spec_end; ++k) {
  1580. short *p = &data[stbi__jpeg_dezigzag[k]];
  1581. if (*p != 0)
  1582. if (stbi__jpeg_get_bit(j))
  1583. if ((*p & bit)==0) {
  1584. if (*p > 0)
  1585. *p += bit;
  1586. else
  1587. *p -= bit;
  1588. }
  1589. }
  1590. } else {
  1591. k = j->spec_start;
  1592. do {
  1593. int r,s;
  1594. int rs = stbi__jpeg_huff_decode(j, hac); // @OPTIMIZE see if we can use the fast path here, advance-by-r is so slow, eh
  1595. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1596. s = rs & 15;
  1597. r = rs >> 4;
  1598. if (s == 0) {
  1599. if (r < 15) {
  1600. j->eob_run = (1 << r) - 1;
  1601. if (r)
  1602. j->eob_run += stbi__jpeg_get_bits(j, r);
  1603. r = 64; // force end of block
  1604. } else {
  1605. // r=15 s=0 should write 16 0s, so we just do
  1606. // a run of 15 0s and then write s (which is 0),
  1607. // so we don't have to do anything special here
  1608. }
  1609. } else {
  1610. if (s != 1) return stbi__err("bad huffman code", "Corrupt JPEG");
  1611. // sign bit
  1612. if (stbi__jpeg_get_bit(j))
  1613. s = bit;
  1614. else
  1615. s = -bit;
  1616. }
  1617. // advance by r
  1618. while (k <= j->spec_end) {
  1619. short *p = &data[stbi__jpeg_dezigzag[k++]];
  1620. if (*p != 0) {
  1621. if (stbi__jpeg_get_bit(j))
  1622. if ((*p & bit)==0) {
  1623. if (*p > 0)
  1624. *p += bit;
  1625. else
  1626. *p -= bit;
  1627. }
  1628. } else {
  1629. if (r == 0) {
  1630. *p = (short) s;
  1631. break;
  1632. }
  1633. --r;
  1634. }
  1635. }
  1636. } while (k <= j->spec_end);
  1637. }
  1638. }
  1639. return 1;
  1640. }
  1641. // take a -128..127 value and stbi__clamp it and convert to 0..255
  1642. stbi_inline static stbi_uc stbi__clamp(int x)
  1643. {
  1644. // trick to use a single test to catch both cases
  1645. if ((unsigned int) x > 255) {
  1646. if (x < 0) return 0;
  1647. if (x > 255) return 255;
  1648. }
  1649. return (stbi_uc) x;
  1650. }
  1651. #define stbi__f2f(x) ((int) (((x) * 4096 + 0.5)))
  1652. #define stbi__fsh(x) ((x) << 12)
  1653. // derived from jidctint -- DCT_ISLOW
  1654. #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
  1655. int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
  1656. p2 = s2; \
  1657. p3 = s6; \
  1658. p1 = (p2+p3) * stbi__f2f(0.5411961f); \
  1659. t2 = p1 + p3*stbi__f2f(-1.847759065f); \
  1660. t3 = p1 + p2*stbi__f2f( 0.765366865f); \
  1661. p2 = s0; \
  1662. p3 = s4; \
  1663. t0 = stbi__fsh(p2+p3); \
  1664. t1 = stbi__fsh(p2-p3); \
  1665. x0 = t0+t3; \
  1666. x3 = t0-t3; \
  1667. x1 = t1+t2; \
  1668. x2 = t1-t2; \
  1669. t0 = s7; \
  1670. t1 = s5; \
  1671. t2 = s3; \
  1672. t3 = s1; \
  1673. p3 = t0+t2; \
  1674. p4 = t1+t3; \
  1675. p1 = t0+t3; \
  1676. p2 = t1+t2; \
  1677. p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
  1678. t0 = t0*stbi__f2f( 0.298631336f); \
  1679. t1 = t1*stbi__f2f( 2.053119869f); \
  1680. t2 = t2*stbi__f2f( 3.072711026f); \
  1681. t3 = t3*stbi__f2f( 1.501321110f); \
  1682. p1 = p5 + p1*stbi__f2f(-0.899976223f); \
  1683. p2 = p5 + p2*stbi__f2f(-2.562915447f); \
  1684. p3 = p3*stbi__f2f(-1.961570560f); \
  1685. p4 = p4*stbi__f2f(-0.390180644f); \
  1686. t3 += p1+p4; \
  1687. t2 += p2+p3; \
  1688. t1 += p2+p4; \
  1689. t0 += p1+p3;
  1690. static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64])
  1691. {
  1692. int i,val[64],*v=val;
  1693. stbi_uc *o;
  1694. short *d = data;
  1695. // columns
  1696. for (i=0; i < 8; ++i,++d, ++v) {
  1697. // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
  1698. if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
  1699. && d[40]==0 && d[48]==0 && d[56]==0) {
  1700. // no shortcut 0 seconds
  1701. // (1|2|3|4|5|6|7)==0 0 seconds
  1702. // all separate -0.047 seconds
  1703. // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
  1704. int dcterm = d[0] << 2;
  1705. v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
  1706. } else {
  1707. STBI__IDCT_1D(d[ 0],d[ 8],d[16],d[24],d[32],d[40],d[48],d[56])
  1708. // constants scaled things up by 1<<12; let's bring them back
  1709. // down, but keep 2 extra bits of precision
  1710. x0 += 512; x1 += 512; x2 += 512; x3 += 512;
  1711. v[ 0] = (x0+t3) >> 10;
  1712. v[56] = (x0-t3) >> 10;
  1713. v[ 8] = (x1+t2) >> 10;
  1714. v[48] = (x1-t2) >> 10;
  1715. v[16] = (x2+t1) >> 10;
  1716. v[40] = (x2-t1) >> 10;
  1717. v[24] = (x3+t0) >> 10;
  1718. v[32] = (x3-t0) >> 10;
  1719. }
  1720. }
  1721. for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
  1722. // no fast case since the first 1D IDCT spread components out
  1723. STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
  1724. // constants scaled things up by 1<<12, plus we had 1<<2 from first
  1725. // loop, plus horizontal and vertical each scale by sqrt(8) so together
  1726. // we've got an extra 1<<3, so 1<<17 total we need to remove.
  1727. // so we want to round that, which means adding 0.5 * 1<<17,
  1728. // aka 65536. Also, we'll end up with -128 to 127 that we want
  1729. // to encode as 0..255 by adding 128, so we'll add that before the shift
  1730. x0 += 65536 + (128<<17);
  1731. x1 += 65536 + (128<<17);
  1732. x2 += 65536 + (128<<17);
  1733. x3 += 65536 + (128<<17);
  1734. // tried computing the shifts into temps, or'ing the temps to see
  1735. // if any were out of range, but that was slower
  1736. o[0] = stbi__clamp((x0+t3) >> 17);
  1737. o[7] = stbi__clamp((x0-t3) >> 17);
  1738. o[1] = stbi__clamp((x1+t2) >> 17);
  1739. o[6] = stbi__clamp((x1-t2) >> 17);
  1740. o[2] = stbi__clamp((x2+t1) >> 17);
  1741. o[5] = stbi__clamp((x2-t1) >> 17);
  1742. o[3] = stbi__clamp((x3+t0) >> 17);
  1743. o[4] = stbi__clamp((x3-t0) >> 17);
  1744. }
  1745. }
  1746. #ifdef STBI_SSE2
  1747. // sse2 integer IDCT. not the fastest possible implementation but it
  1748. // produces bit-identical results to the generic C version so it's
  1749. // fully "transparent".
  1750. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  1751. {
  1752. // This is constructed to match our regular (generic) integer IDCT exactly.
  1753. __m128i row0, row1, row2, row3, row4, row5, row6, row7;
  1754. __m128i tmp;
  1755. // dot product constant: even elems=x, odd elems=y
  1756. #define dct_const(x,y) _mm_setr_epi16((x),(y),(x),(y),(x),(y),(x),(y))
  1757. // out(0) = c0[even]*x + c0[odd]*y (c0, x, y 16-bit, out 32-bit)
  1758. // out(1) = c1[even]*x + c1[odd]*y
  1759. #define dct_rot(out0,out1, x,y,c0,c1) \
  1760. __m128i c0##lo = _mm_unpacklo_epi16((x),(y)); \
  1761. __m128i c0##hi = _mm_unpackhi_epi16((x),(y)); \
  1762. __m128i out0##_l = _mm_madd_epi16(c0##lo, c0); \
  1763. __m128i out0##_h = _mm_madd_epi16(c0##hi, c0); \
  1764. __m128i out1##_l = _mm_madd_epi16(c0##lo, c1); \
  1765. __m128i out1##_h = _mm_madd_epi16(c0##hi, c1)
  1766. // out = in << 12 (in 16-bit, out 32-bit)
  1767. #define dct_widen(out, in) \
  1768. __m128i out##_l = _mm_srai_epi32(_mm_unpacklo_epi16(_mm_setzero_si128(), (in)), 4); \
  1769. __m128i out##_h = _mm_srai_epi32(_mm_unpackhi_epi16(_mm_setzero_si128(), (in)), 4)
  1770. // wide add
  1771. #define dct_wadd(out, a, b) \
  1772. __m128i out##_l = _mm_add_epi32(a##_l, b##_l); \
  1773. __m128i out##_h = _mm_add_epi32(a##_h, b##_h)
  1774. // wide sub
  1775. #define dct_wsub(out, a, b) \
  1776. __m128i out##_l = _mm_sub_epi32(a##_l, b##_l); \
  1777. __m128i out##_h = _mm_sub_epi32(a##_h, b##_h)
  1778. // butterfly a/b, add bias, then shift by "s" and pack
  1779. #define dct_bfly32o(out0, out1, a,b,bias,s) \
  1780. { \
  1781. __m128i abiased_l = _mm_add_epi32(a##_l, bias); \
  1782. __m128i abiased_h = _mm_add_epi32(a##_h, bias); \
  1783. dct_wadd(sum, abiased, b); \
  1784. dct_wsub(dif, abiased, b); \
  1785. out0 = _mm_packs_epi32(_mm_srai_epi32(sum_l, s), _mm_srai_epi32(sum_h, s)); \
  1786. out1 = _mm_packs_epi32(_mm_srai_epi32(dif_l, s), _mm_srai_epi32(dif_h, s)); \
  1787. }
  1788. // 8-bit interleave step (for transposes)
  1789. #define dct_interleave8(a, b) \
  1790. tmp = a; \
  1791. a = _mm_unpacklo_epi8(a, b); \
  1792. b = _mm_unpackhi_epi8(tmp, b)
  1793. // 16-bit interleave step (for transposes)
  1794. #define dct_interleave16(a, b) \
  1795. tmp = a; \
  1796. a = _mm_unpacklo_epi16(a, b); \
  1797. b = _mm_unpackhi_epi16(tmp, b)
  1798. #define dct_pass(bias,shift) \
  1799. { \
  1800. /* even part */ \
  1801. dct_rot(t2e,t3e, row2,row6, rot0_0,rot0_1); \
  1802. __m128i sum04 = _mm_add_epi16(row0, row4); \
  1803. __m128i dif04 = _mm_sub_epi16(row0, row4); \
  1804. dct_widen(t0e, sum04); \
  1805. dct_widen(t1e, dif04); \
  1806. dct_wadd(x0, t0e, t3e); \
  1807. dct_wsub(x3, t0e, t3e); \
  1808. dct_wadd(x1, t1e, t2e); \
  1809. dct_wsub(x2, t1e, t2e); \
  1810. /* odd part */ \
  1811. dct_rot(y0o,y2o, row7,row3, rot2_0,rot2_1); \
  1812. dct_rot(y1o,y3o, row5,row1, rot3_0,rot3_1); \
  1813. __m128i sum17 = _mm_add_epi16(row1, row7); \
  1814. __m128i sum35 = _mm_add_epi16(row3, row5); \
  1815. dct_rot(y4o,y5o, sum17,sum35, rot1_0,rot1_1); \
  1816. dct_wadd(x4, y0o, y4o); \
  1817. dct_wadd(x5, y1o, y5o); \
  1818. dct_wadd(x6, y2o, y5o); \
  1819. dct_wadd(x7, y3o, y4o); \
  1820. dct_bfly32o(row0,row7, x0,x7,bias,shift); \
  1821. dct_bfly32o(row1,row6, x1,x6,bias,shift); \
  1822. dct_bfly32o(row2,row5, x2,x5,bias,shift); \
  1823. dct_bfly32o(row3,row4, x3,x4,bias,shift); \
  1824. }
  1825. __m128i rot0_0 = dct_const(stbi__f2f(0.5411961f), stbi__f2f(0.5411961f) + stbi__f2f(-1.847759065f));
  1826. __m128i rot0_1 = dct_const(stbi__f2f(0.5411961f) + stbi__f2f( 0.765366865f), stbi__f2f(0.5411961f));
  1827. __m128i rot1_0 = dct_const(stbi__f2f(1.175875602f) + stbi__f2f(-0.899976223f), stbi__f2f(1.175875602f));
  1828. __m128i rot1_1 = dct_const(stbi__f2f(1.175875602f), stbi__f2f(1.175875602f) + stbi__f2f(-2.562915447f));
  1829. __m128i rot2_0 = dct_const(stbi__f2f(-1.961570560f) + stbi__f2f( 0.298631336f), stbi__f2f(-1.961570560f));
  1830. __m128i rot2_1 = dct_const(stbi__f2f(-1.961570560f), stbi__f2f(-1.961570560f) + stbi__f2f( 3.072711026f));
  1831. __m128i rot3_0 = dct_const(stbi__f2f(-0.390180644f) + stbi__f2f( 2.053119869f), stbi__f2f(-0.390180644f));
  1832. __m128i rot3_1 = dct_const(stbi__f2f(-0.390180644f), stbi__f2f(-0.390180644f) + stbi__f2f( 1.501321110f));
  1833. // rounding biases in column/row passes, see stbi__idct_block for explanation.
  1834. __m128i bias_0 = _mm_set1_epi32(512);
  1835. __m128i bias_1 = _mm_set1_epi32(65536 + (128<<17));
  1836. // load
  1837. row0 = _mm_load_si128((const __m128i *) (data + 0*8));
  1838. row1 = _mm_load_si128((const __m128i *) (data + 1*8));
  1839. row2 = _mm_load_si128((const __m128i *) (data + 2*8));
  1840. row3 = _mm_load_si128((const __m128i *) (data + 3*8));
  1841. row4 = _mm_load_si128((const __m128i *) (data + 4*8));
  1842. row5 = _mm_load_si128((const __m128i *) (data + 5*8));
  1843. row6 = _mm_load_si128((const __m128i *) (data + 6*8));
  1844. row7 = _mm_load_si128((const __m128i *) (data + 7*8));
  1845. // column pass
  1846. dct_pass(bias_0, 10);
  1847. {
  1848. // 16bit 8x8 transpose pass 1
  1849. dct_interleave16(row0, row4);
  1850. dct_interleave16(row1, row5);
  1851. dct_interleave16(row2, row6);
  1852. dct_interleave16(row3, row7);
  1853. // transpose pass 2
  1854. dct_interleave16(row0, row2);
  1855. dct_interleave16(row1, row3);
  1856. dct_interleave16(row4, row6);
  1857. dct_interleave16(row5, row7);
  1858. // transpose pass 3
  1859. dct_interleave16(row0, row1);
  1860. dct_interleave16(row2, row3);
  1861. dct_interleave16(row4, row5);
  1862. dct_interleave16(row6, row7);
  1863. }
  1864. // row pass
  1865. dct_pass(bias_1, 17);
  1866. {
  1867. // pack
  1868. __m128i p0 = _mm_packus_epi16(row0, row1); // a0a1a2a3...a7b0b1b2b3...b7
  1869. __m128i p1 = _mm_packus_epi16(row2, row3);
  1870. __m128i p2 = _mm_packus_epi16(row4, row5);
  1871. __m128i p3 = _mm_packus_epi16(row6, row7);
  1872. // 8bit 8x8 transpose pass 1
  1873. dct_interleave8(p0, p2); // a0e0a1e1...
  1874. dct_interleave8(p1, p3); // c0g0c1g1...
  1875. // transpose pass 2
  1876. dct_interleave8(p0, p1); // a0c0e0g0...
  1877. dct_interleave8(p2, p3); // b0d0f0h0...
  1878. // transpose pass 3
  1879. dct_interleave8(p0, p2); // a0b0c0d0...
  1880. dct_interleave8(p1, p3); // a4b4c4d4...
  1881. // store
  1882. _mm_storel_epi64((__m128i *) out, p0); out += out_stride;
  1883. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p0, 0x4e)); out += out_stride;
  1884. _mm_storel_epi64((__m128i *) out, p2); out += out_stride;
  1885. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p2, 0x4e)); out += out_stride;
  1886. _mm_storel_epi64((__m128i *) out, p1); out += out_stride;
  1887. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p1, 0x4e)); out += out_stride;
  1888. _mm_storel_epi64((__m128i *) out, p3); out += out_stride;
  1889. _mm_storel_epi64((__m128i *) out, _mm_shuffle_epi32(p3, 0x4e));
  1890. }
  1891. #undef dct_const
  1892. #undef dct_rot
  1893. #undef dct_widen
  1894. #undef dct_wadd
  1895. #undef dct_wsub
  1896. #undef dct_bfly32o
  1897. #undef dct_interleave8
  1898. #undef dct_interleave16
  1899. #undef dct_pass
  1900. }
  1901. #endif // STBI_SSE2
  1902. #ifdef STBI_NEON
  1903. // NEON integer IDCT. should produce bit-identical
  1904. // results to the generic C version.
  1905. static void stbi__idct_simd(stbi_uc *out, int out_stride, short data[64])
  1906. {
  1907. int16x8_t row0, row1, row2, row3, row4, row5, row6, row7;
  1908. int16x4_t rot0_0 = vdup_n_s16(stbi__f2f(0.5411961f));
  1909. int16x4_t rot0_1 = vdup_n_s16(stbi__f2f(-1.847759065f));
  1910. int16x4_t rot0_2 = vdup_n_s16(stbi__f2f( 0.765366865f));
  1911. int16x4_t rot1_0 = vdup_n_s16(stbi__f2f( 1.175875602f));
  1912. int16x4_t rot1_1 = vdup_n_s16(stbi__f2f(-0.899976223f));
  1913. int16x4_t rot1_2 = vdup_n_s16(stbi__f2f(-2.562915447f));
  1914. int16x4_t rot2_0 = vdup_n_s16(stbi__f2f(-1.961570560f));
  1915. int16x4_t rot2_1 = vdup_n_s16(stbi__f2f(-0.390180644f));
  1916. int16x4_t rot3_0 = vdup_n_s16(stbi__f2f( 0.298631336f));
  1917. int16x4_t rot3_1 = vdup_n_s16(stbi__f2f( 2.053119869f));
  1918. int16x4_t rot3_2 = vdup_n_s16(stbi__f2f( 3.072711026f));
  1919. int16x4_t rot3_3 = vdup_n_s16(stbi__f2f( 1.501321110f));
  1920. #define dct_long_mul(out, inq, coeff) \
  1921. int32x4_t out##_l = vmull_s16(vget_low_s16(inq), coeff); \
  1922. int32x4_t out##_h = vmull_s16(vget_high_s16(inq), coeff)
  1923. #define dct_long_mac(out, acc, inq, coeff) \
  1924. int32x4_t out##_l = vmlal_s16(acc##_l, vget_low_s16(inq), coeff); \
  1925. int32x4_t out##_h = vmlal_s16(acc##_h, vget_high_s16(inq), coeff)
  1926. #define dct_widen(out, inq) \
  1927. int32x4_t out##_l = vshll_n_s16(vget_low_s16(inq), 12); \
  1928. int32x4_t out##_h = vshll_n_s16(vget_high_s16(inq), 12)
  1929. // wide add
  1930. #define dct_wadd(out, a, b) \
  1931. int32x4_t out##_l = vaddq_s32(a##_l, b##_l); \
  1932. int32x4_t out##_h = vaddq_s32(a##_h, b##_h)
  1933. // wide sub
  1934. #define dct_wsub(out, a, b) \
  1935. int32x4_t out##_l = vsubq_s32(a##_l, b##_l); \
  1936. int32x4_t out##_h = vsubq_s32(a##_h, b##_h)
  1937. // butterfly a/b, then shift using "shiftop" by "s" and pack
  1938. #define dct_bfly32o(out0,out1, a,b,shiftop,s) \
  1939. { \
  1940. dct_wadd(sum, a, b); \
  1941. dct_wsub(dif, a, b); \
  1942. out0 = vcombine_s16(shiftop(sum_l, s), shiftop(sum_h, s)); \
  1943. out1 = vcombine_s16(shiftop(dif_l, s), shiftop(dif_h, s)); \
  1944. }
  1945. #define dct_pass(shiftop, shift) \
  1946. { \
  1947. /* even part */ \
  1948. int16x8_t sum26 = vaddq_s16(row2, row6); \
  1949. dct_long_mul(p1e, sum26, rot0_0); \
  1950. dct_long_mac(t2e, p1e, row6, rot0_1); \
  1951. dct_long_mac(t3e, p1e, row2, rot0_2); \
  1952. int16x8_t sum04 = vaddq_s16(row0, row4); \
  1953. int16x8_t dif04 = vsubq_s16(row0, row4); \
  1954. dct_widen(t0e, sum04); \
  1955. dct_widen(t1e, dif04); \
  1956. dct_wadd(x0, t0e, t3e); \
  1957. dct_wsub(x3, t0e, t3e); \
  1958. dct_wadd(x1, t1e, t2e); \
  1959. dct_wsub(x2, t1e, t2e); \
  1960. /* odd part */ \
  1961. int16x8_t sum15 = vaddq_s16(row1, row5); \
  1962. int16x8_t sum17 = vaddq_s16(row1, row7); \
  1963. int16x8_t sum35 = vaddq_s16(row3, row5); \
  1964. int16x8_t sum37 = vaddq_s16(row3, row7); \
  1965. int16x8_t sumodd = vaddq_s16(sum17, sum35); \
  1966. dct_long_mul(p5o, sumodd, rot1_0); \
  1967. dct_long_mac(p1o, p5o, sum17, rot1_1); \
  1968. dct_long_mac(p2o, p5o, sum35, rot1_2); \
  1969. dct_long_mul(p3o, sum37, rot2_0); \
  1970. dct_long_mul(p4o, sum15, rot2_1); \
  1971. dct_wadd(sump13o, p1o, p3o); \
  1972. dct_wadd(sump24o, p2o, p4o); \
  1973. dct_wadd(sump23o, p2o, p3o); \
  1974. dct_wadd(sump14o, p1o, p4o); \
  1975. dct_long_mac(x4, sump13o, row7, rot3_0); \
  1976. dct_long_mac(x5, sump24o, row5, rot3_1); \
  1977. dct_long_mac(x6, sump23o, row3, rot3_2); \
  1978. dct_long_mac(x7, sump14o, row1, rot3_3); \
  1979. dct_bfly32o(row0,row7, x0,x7,shiftop,shift); \
  1980. dct_bfly32o(row1,row6, x1,x6,shiftop,shift); \
  1981. dct_bfly32o(row2,row5, x2,x5,shiftop,shift); \
  1982. dct_bfly32o(row3,row4, x3,x4,shiftop,shift); \
  1983. }
  1984. // load
  1985. row0 = vld1q_s16(data + 0*8);
  1986. row1 = vld1q_s16(data + 1*8);
  1987. row2 = vld1q_s16(data + 2*8);
  1988. row3 = vld1q_s16(data + 3*8);
  1989. row4 = vld1q_s16(data + 4*8);
  1990. row5 = vld1q_s16(data + 5*8);
  1991. row6 = vld1q_s16(data + 6*8);
  1992. row7 = vld1q_s16(data + 7*8);
  1993. // add DC bias
  1994. row0 = vaddq_s16(row0, vsetq_lane_s16(1024, vdupq_n_s16(0), 0));
  1995. // column pass
  1996. dct_pass(vrshrn_n_s32, 10);
  1997. // 16bit 8x8 transpose
  1998. {
  1999. // these three map to a single VTRN.16, VTRN.32, and VSWP, respectively.
  2000. // whether compilers actually get this is another story, sadly.
  2001. #define dct_trn16(x, y) { int16x8x2_t t = vtrnq_s16(x, y); x = t.val[0]; y = t.val[1]; }
  2002. #define dct_trn32(x, y) { int32x4x2_t t = vtrnq_s32(vreinterpretq_s32_s16(x), vreinterpretq_s32_s16(y)); x = vreinterpretq_s16_s32(t.val[0]); y = vreinterpretq_s16_s32(t.val[1]); }
  2003. #define dct_trn64(x, y) { int16x8_t x0 = x; int16x8_t y0 = y; x = vcombine_s16(vget_low_s16(x0), vget_low_s16(y0)); y = vcombine_s16(vget_high_s16(x0), vget_high_s16(y0)); }
  2004. // pass 1
  2005. dct_trn16(row0, row1); // a0b0a2b2a4b4a6b6
  2006. dct_trn16(row2, row3);
  2007. dct_trn16(row4, row5);
  2008. dct_trn16(row6, row7);
  2009. // pass 2
  2010. dct_trn32(row0, row2); // a0b0c0d0a4b4c4d4
  2011. dct_trn32(row1, row3);
  2012. dct_trn32(row4, row6);
  2013. dct_trn32(row5, row7);
  2014. // pass 3
  2015. dct_trn64(row0, row4); // a0b0c0d0e0f0g0h0
  2016. dct_trn64(row1, row5);
  2017. dct_trn64(row2, row6);
  2018. dct_trn64(row3, row7);
  2019. #undef dct_trn16
  2020. #undef dct_trn32
  2021. #undef dct_trn64
  2022. }
  2023. // row pass
  2024. // vrshrn_n_s32 only supports shifts up to 16, we need
  2025. // 17. so do a non-rounding shift of 16 first then follow
  2026. // up with a rounding shift by 1.
  2027. dct_pass(vshrn_n_s32, 16);
  2028. {
  2029. // pack and round
  2030. uint8x8_t p0 = vqrshrun_n_s16(row0, 1);
  2031. uint8x8_t p1 = vqrshrun_n_s16(row1, 1);
  2032. uint8x8_t p2 = vqrshrun_n_s16(row2, 1);
  2033. uint8x8_t p3 = vqrshrun_n_s16(row3, 1);
  2034. uint8x8_t p4 = vqrshrun_n_s16(row4, 1);
  2035. uint8x8_t p5 = vqrshrun_n_s16(row5, 1);
  2036. uint8x8_t p6 = vqrshrun_n_s16(row6, 1);
  2037. uint8x8_t p7 = vqrshrun_n_s16(row7, 1);
  2038. // again, these can translate into one instruction, but often don't.
  2039. #define dct_trn8_8(x, y) { uint8x8x2_t t = vtrn_u8(x, y); x = t.val[0]; y = t.val[1]; }
  2040. #define dct_trn8_16(x, y) { uint16x4x2_t t = vtrn_u16(vreinterpret_u16_u8(x), vreinterpret_u16_u8(y)); x = vreinterpret_u8_u16(t.val[0]); y = vreinterpret_u8_u16(t.val[1]); }
  2041. #define dct_trn8_32(x, y) { uint32x2x2_t t = vtrn_u32(vreinterpret_u32_u8(x), vreinterpret_u32_u8(y)); x = vreinterpret_u8_u32(t.val[0]); y = vreinterpret_u8_u32(t.val[1]); }
  2042. // sadly can't use interleaved stores here since we only write
  2043. // 8 bytes to each scan line!
  2044. // 8x8 8-bit transpose pass 1
  2045. dct_trn8_8(p0, p1);
  2046. dct_trn8_8(p2, p3);
  2047. dct_trn8_8(p4, p5);
  2048. dct_trn8_8(p6, p7);
  2049. // pass 2
  2050. dct_trn8_16(p0, p2);
  2051. dct_trn8_16(p1, p3);
  2052. dct_trn8_16(p4, p6);
  2053. dct_trn8_16(p5, p7);
  2054. // pass 3
  2055. dct_trn8_32(p0, p4);
  2056. dct_trn8_32(p1, p5);
  2057. dct_trn8_32(p2, p6);
  2058. dct_trn8_32(p3, p7);
  2059. // store
  2060. vst1_u8(out, p0); out += out_stride;
  2061. vst1_u8(out, p1); out += out_stride;
  2062. vst1_u8(out, p2); out += out_stride;
  2063. vst1_u8(out, p3); out += out_stride;
  2064. vst1_u8(out, p4); out += out_stride;
  2065. vst1_u8(out, p5); out += out_stride;
  2066. vst1_u8(out, p6); out += out_stride;
  2067. vst1_u8(out, p7);
  2068. #undef dct_trn8_8
  2069. #undef dct_trn8_16
  2070. #undef dct_trn8_32
  2071. }
  2072. #undef dct_long_mul
  2073. #undef dct_long_mac
  2074. #undef dct_widen
  2075. #undef dct_wadd
  2076. #undef dct_wsub
  2077. #undef dct_bfly32o
  2078. #undef dct_pass
  2079. }
  2080. #endif // STBI_NEON
  2081. #define STBI__MARKER_none 0xff
  2082. // if there's a pending marker from the entropy stream, return that
  2083. // otherwise, fetch from the stream and get a marker. if there's no
  2084. // marker, return 0xff, which is never a valid marker value
  2085. static stbi_uc stbi__get_marker(stbi__jpeg *j)
  2086. {
  2087. stbi_uc x;
  2088. if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
  2089. x = stbi__get8(j->s);
  2090. if (x != 0xff) return STBI__MARKER_none;
  2091. while (x == 0xff)
  2092. x = stbi__get8(j->s);
  2093. return x;
  2094. }
  2095. // in each scan, we'll have scan_n components, and the order
  2096. // of the components is specified by order[]
  2097. #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
  2098. // after a restart interval, stbi__jpeg_reset the entropy decoder and
  2099. // the dc prediction
  2100. static void stbi__jpeg_reset(stbi__jpeg *j)
  2101. {
  2102. j->code_bits = 0;
  2103. j->code_buffer = 0;
  2104. j->nomore = 0;
  2105. j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
  2106. j->marker = STBI__MARKER_none;
  2107. j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
  2108. j->eob_run = 0;
  2109. // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
  2110. // since we don't even allow 1<<30 pixels
  2111. }
  2112. static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
  2113. {
  2114. stbi__jpeg_reset(z);
  2115. if (!z->progressive) {
  2116. if (z->scan_n == 1) {
  2117. int i,j;
  2118. STBI_SIMD_ALIGN(short, data[64]);
  2119. int n = z->order[0];
  2120. // non-interleaved data, we just need to process one block at a time,
  2121. // in trivial scanline order
  2122. // number of blocks to do just depends on how many actual "pixels" this
  2123. // component has, independent of interleaved MCU blocking and such
  2124. int w = (z->img_comp[n].x+7) >> 3;
  2125. int h = (z->img_comp[n].y+7) >> 3;
  2126. for (j=0; j < h; ++j) {
  2127. for (i=0; i < w; ++i) {
  2128. int ha = z->img_comp[n].ha;
  2129. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
  2130. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
  2131. // every data block is an MCU, so countdown the restart interval
  2132. if (--z->todo <= 0) {
  2133. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2134. // if it's NOT a restart, then just bail, so we get corrupt data
  2135. // rather than no data
  2136. if (!STBI__RESTART(z->marker)) return 1;
  2137. stbi__jpeg_reset(z);
  2138. }
  2139. }
  2140. }
  2141. return 1;
  2142. } else { // interleaved
  2143. int i,j,k,x,y;
  2144. STBI_SIMD_ALIGN(short, data[64]);
  2145. for (j=0; j < z->img_mcu_y; ++j) {
  2146. for (i=0; i < z->img_mcu_x; ++i) {
  2147. // scan an interleaved mcu... process scan_n components in order
  2148. for (k=0; k < z->scan_n; ++k) {
  2149. int n = z->order[k];
  2150. // scan out an mcu's worth of this component; that's just determined
  2151. // by the basic H and V specified for the component
  2152. for (y=0; y < z->img_comp[n].v; ++y) {
  2153. for (x=0; x < z->img_comp[n].h; ++x) {
  2154. int x2 = (i*z->img_comp[n].h + x)*8;
  2155. int y2 = (j*z->img_comp[n].v + y)*8;
  2156. int ha = z->img_comp[n].ha;
  2157. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+ha, z->fast_ac[ha], n, z->dequant[z->img_comp[n].tq])) return 0;
  2158. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data);
  2159. }
  2160. }
  2161. }
  2162. // after all interleaved components, that's an interleaved MCU,
  2163. // so now count down the restart interval
  2164. if (--z->todo <= 0) {
  2165. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2166. if (!STBI__RESTART(z->marker)) return 1;
  2167. stbi__jpeg_reset(z);
  2168. }
  2169. }
  2170. }
  2171. return 1;
  2172. }
  2173. } else {
  2174. if (z->scan_n == 1) {
  2175. int i,j;
  2176. int n = z->order[0];
  2177. // non-interleaved data, we just need to process one block at a time,
  2178. // in trivial scanline order
  2179. // number of blocks to do just depends on how many actual "pixels" this
  2180. // component has, independent of interleaved MCU blocking and such
  2181. int w = (z->img_comp[n].x+7) >> 3;
  2182. int h = (z->img_comp[n].y+7) >> 3;
  2183. for (j=0; j < h; ++j) {
  2184. for (i=0; i < w; ++i) {
  2185. short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
  2186. if (z->spec_start == 0) {
  2187. if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
  2188. return 0;
  2189. } else {
  2190. int ha = z->img_comp[n].ha;
  2191. if (!stbi__jpeg_decode_block_prog_ac(z, data, &z->huff_ac[ha], z->fast_ac[ha]))
  2192. return 0;
  2193. }
  2194. // every data block is an MCU, so countdown the restart interval
  2195. if (--z->todo <= 0) {
  2196. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2197. if (!STBI__RESTART(z->marker)) return 1;
  2198. stbi__jpeg_reset(z);
  2199. }
  2200. }
  2201. }
  2202. return 1;
  2203. } else { // interleaved
  2204. int i,j,k,x,y;
  2205. for (j=0; j < z->img_mcu_y; ++j) {
  2206. for (i=0; i < z->img_mcu_x; ++i) {
  2207. // scan an interleaved mcu... process scan_n components in order
  2208. for (k=0; k < z->scan_n; ++k) {
  2209. int n = z->order[k];
  2210. // scan out an mcu's worth of this component; that's just determined
  2211. // by the basic H and V specified for the component
  2212. for (y=0; y < z->img_comp[n].v; ++y) {
  2213. for (x=0; x < z->img_comp[n].h; ++x) {
  2214. int x2 = (i*z->img_comp[n].h + x);
  2215. int y2 = (j*z->img_comp[n].v + y);
  2216. short *data = z->img_comp[n].coeff + 64 * (x2 + y2 * z->img_comp[n].coeff_w);
  2217. if (!stbi__jpeg_decode_block_prog_dc(z, data, &z->huff_dc[z->img_comp[n].hd], n))
  2218. return 0;
  2219. }
  2220. }
  2221. }
  2222. // after all interleaved components, that's an interleaved MCU,
  2223. // so now count down the restart interval
  2224. if (--z->todo <= 0) {
  2225. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  2226. if (!STBI__RESTART(z->marker)) return 1;
  2227. stbi__jpeg_reset(z);
  2228. }
  2229. }
  2230. }
  2231. return 1;
  2232. }
  2233. }
  2234. }
  2235. static void stbi__jpeg_dequantize(short *data, stbi_uc *dequant)
  2236. {
  2237. int i;
  2238. for (i=0; i < 64; ++i)
  2239. data[i] *= dequant[i];
  2240. }
  2241. static void stbi__jpeg_finish(stbi__jpeg *z)
  2242. {
  2243. if (z->progressive) {
  2244. // dequantize and idct the data
  2245. int i,j,n;
  2246. for (n=0; n < z->s->img_n; ++n) {
  2247. int w = (z->img_comp[n].x+7) >> 3;
  2248. int h = (z->img_comp[n].y+7) >> 3;
  2249. for (j=0; j < h; ++j) {
  2250. for (i=0; i < w; ++i) {
  2251. short *data = z->img_comp[n].coeff + 64 * (i + j * z->img_comp[n].coeff_w);
  2252. stbi__jpeg_dequantize(data, z->dequant[z->img_comp[n].tq]);
  2253. z->idct_block_kernel(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data);
  2254. }
  2255. }
  2256. }
  2257. }
  2258. }
  2259. static int stbi__process_marker(stbi__jpeg *z, int m)
  2260. {
  2261. int L;
  2262. switch (m) {
  2263. case STBI__MARKER_none: // no marker found
  2264. return stbi__err("expected marker","Corrupt JPEG");
  2265. case 0xDD: // DRI - specify restart interval
  2266. if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
  2267. z->restart_interval = stbi__get16be(z->s);
  2268. return 1;
  2269. case 0xDB: // DQT - define quantization table
  2270. L = stbi__get16be(z->s)-2;
  2271. while (L > 0) {
  2272. int q = stbi__get8(z->s);
  2273. int p = q >> 4;
  2274. int t = q & 15,i;
  2275. if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG");
  2276. if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
  2277. for (i=0; i < 64; ++i)
  2278. z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s);
  2279. L -= 65;
  2280. }
  2281. return L==0;
  2282. case 0xC4: // DHT - define huffman table
  2283. L = stbi__get16be(z->s)-2;
  2284. while (L > 0) {
  2285. stbi_uc *v;
  2286. int sizes[16],i,n=0;
  2287. int q = stbi__get8(z->s);
  2288. int tc = q >> 4;
  2289. int th = q & 15;
  2290. if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
  2291. for (i=0; i < 16; ++i) {
  2292. sizes[i] = stbi__get8(z->s);
  2293. n += sizes[i];
  2294. }
  2295. L -= 17;
  2296. if (tc == 0) {
  2297. if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
  2298. v = z->huff_dc[th].values;
  2299. } else {
  2300. if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
  2301. v = z->huff_ac[th].values;
  2302. }
  2303. for (i=0; i < n; ++i)
  2304. v[i] = stbi__get8(z->s);
  2305. if (tc != 0)
  2306. stbi__build_fast_ac(z->fast_ac[th], z->huff_ac + th);
  2307. L -= n;
  2308. }
  2309. return L==0;
  2310. }
  2311. // check for comment block or APP blocks
  2312. if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
  2313. stbi__skip(z->s, stbi__get16be(z->s)-2);
  2314. return 1;
  2315. }
  2316. return 0;
  2317. }
  2318. // after we see SOS
  2319. static int stbi__process_scan_header(stbi__jpeg *z)
  2320. {
  2321. int i;
  2322. int Ls = stbi__get16be(z->s);
  2323. z->scan_n = stbi__get8(z->s);
  2324. if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad SOS component count","Corrupt JPEG");
  2325. if (Ls != 6+2*z->scan_n) return stbi__err("bad SOS len","Corrupt JPEG");
  2326. for (i=0; i < z->scan_n; ++i) {
  2327. int id = stbi__get8(z->s), which;
  2328. int q = stbi__get8(z->s);
  2329. for (which = 0; which < z->s->img_n; ++which)
  2330. if (z->img_comp[which].id == id)
  2331. break;
  2332. if (which == z->s->img_n) return 0; // no match
  2333. z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
  2334. z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
  2335. z->order[i] = which;
  2336. }
  2337. {
  2338. int aa;
  2339. z->spec_start = stbi__get8(z->s);
  2340. z->spec_end = stbi__get8(z->s); // should be 63, but might be 0
  2341. aa = stbi__get8(z->s);
  2342. z->succ_high = (aa >> 4);
  2343. z->succ_low = (aa & 15);
  2344. if (z->progressive) {
  2345. if (z->spec_start > 63 || z->spec_end > 63 || z->spec_start > z->spec_end || z->succ_high > 13 || z->succ_low > 13)
  2346. return stbi__err("bad SOS", "Corrupt JPEG");
  2347. } else {
  2348. if (z->spec_start != 0) return stbi__err("bad SOS","Corrupt JPEG");
  2349. if (z->succ_high != 0 || z->succ_low != 0) return stbi__err("bad SOS","Corrupt JPEG");
  2350. z->spec_end = 63;
  2351. }
  2352. }
  2353. return 1;
  2354. }
  2355. static int stbi__process_frame_header(stbi__jpeg *z, int scan)
  2356. {
  2357. stbi__context *s = z->s;
  2358. int Lf,p,i,q, h_max=1,v_max=1,c;
  2359. Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad SOF len","Corrupt JPEG"); // JPEG
  2360. p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
  2361. s->img_y = stbi__get16be(s); if (s->img_y == 0) return stbi__err("no header height", "JPEG format not supported: delayed height"); // Legal, but we don't handle it--but neither does IJG
  2362. s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
  2363. c = stbi__get8(s);
  2364. if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires
  2365. s->img_n = c;
  2366. for (i=0; i < c; ++i) {
  2367. z->img_comp[i].data = NULL;
  2368. z->img_comp[i].linebuf = NULL;
  2369. }
  2370. if (Lf != 8+3*s->img_n) return stbi__err("bad SOF len","Corrupt JPEG");
  2371. for (i=0; i < s->img_n; ++i) {
  2372. z->img_comp[i].id = stbi__get8(s);
  2373. if (z->img_comp[i].id != i+1) // JFIF requires
  2374. if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
  2375. return stbi__err("bad component ID","Corrupt JPEG");
  2376. q = stbi__get8(s);
  2377. z->img_comp[i].h = (q >> 4); if (!z->img_comp[i].h || z->img_comp[i].h > 4) return stbi__err("bad H","Corrupt JPEG");
  2378. z->img_comp[i].v = q & 15; if (!z->img_comp[i].v || z->img_comp[i].v > 4) return stbi__err("bad V","Corrupt JPEG");
  2379. z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
  2380. }
  2381. if (scan != STBI__SCAN_load) return 1;
  2382. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  2383. for (i=0; i < s->img_n; ++i) {
  2384. if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
  2385. if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
  2386. }
  2387. // compute interleaved mcu info
  2388. z->img_h_max = h_max;
  2389. z->img_v_max = v_max;
  2390. z->img_mcu_w = h_max * 8;
  2391. z->img_mcu_h = v_max * 8;
  2392. z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
  2393. z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
  2394. for (i=0; i < s->img_n; ++i) {
  2395. // number of effective pixels (e.g. for non-interleaved MCU)
  2396. z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
  2397. z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
  2398. // to simplify generation, we'll allocate enough memory to decode
  2399. // the bogus oversized data from using interleaved MCUs and their
  2400. // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
  2401. // discard the extra data until colorspace conversion
  2402. z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
  2403. z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
  2404. z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
  2405. if (z->img_comp[i].raw_data == NULL) {
  2406. for(--i; i >= 0; --i) {
  2407. STBI_FREE(z->img_comp[i].raw_data);
  2408. z->img_comp[i].data = NULL;
  2409. }
  2410. return stbi__err("outofmem", "Out of memory");
  2411. }
  2412. // align blocks for idct using mmx/sse
  2413. z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
  2414. z->img_comp[i].linebuf = NULL;
  2415. if (z->progressive) {
  2416. z->img_comp[i].coeff_w = (z->img_comp[i].w2 + 7) >> 3;
  2417. z->img_comp[i].coeff_h = (z->img_comp[i].h2 + 7) >> 3;
  2418. z->img_comp[i].raw_coeff = STBI_MALLOC(z->img_comp[i].coeff_w * z->img_comp[i].coeff_h * 64 * sizeof(short) + 15);
  2419. z->img_comp[i].coeff = (short*) (((size_t) z->img_comp[i].raw_coeff + 15) & ~15);
  2420. } else {
  2421. z->img_comp[i].coeff = 0;
  2422. z->img_comp[i].raw_coeff = 0;
  2423. }
  2424. }
  2425. return 1;
  2426. }
  2427. // use comparisons since in some cases we handle more than one case (e.g. SOF)
  2428. #define stbi__DNL(x) ((x) == 0xdc)
  2429. #define stbi__SOI(x) ((x) == 0xd8)
  2430. #define stbi__EOI(x) ((x) == 0xd9)
  2431. #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1 || (x) == 0xc2)
  2432. #define stbi__SOS(x) ((x) == 0xda)
  2433. #define stbi__SOF_progressive(x) ((x) == 0xc2)
  2434. static int stbi__decode_jpeg_header(stbi__jpeg *z, int scan)
  2435. {
  2436. int m;
  2437. z->marker = STBI__MARKER_none; // initialize cached marker to empty
  2438. m = stbi__get_marker(z);
  2439. if (!stbi__SOI(m)) return stbi__err("no SOI","Corrupt JPEG");
  2440. if (scan == STBI__SCAN_type) return 1;
  2441. m = stbi__get_marker(z);
  2442. while (!stbi__SOF(m)) {
  2443. if (!stbi__process_marker(z,m)) return 0;
  2444. m = stbi__get_marker(z);
  2445. while (m == STBI__MARKER_none) {
  2446. // some files have extra padding after their blocks, so ok, we'll scan
  2447. if (stbi__at_eof(z->s)) return stbi__err("no SOF", "Corrupt JPEG");
  2448. m = stbi__get_marker(z);
  2449. }
  2450. }
  2451. z->progressive = stbi__SOF_progressive(m);
  2452. if (!stbi__process_frame_header(z, scan)) return 0;
  2453. return 1;
  2454. }
  2455. // decode image to YCbCr format
  2456. static int stbi__decode_jpeg_image(stbi__jpeg *j)
  2457. {
  2458. int m;
  2459. for (m = 0; m < 4; m++) {
  2460. j->img_comp[m].raw_data = NULL;
  2461. j->img_comp[m].raw_coeff = NULL;
  2462. }
  2463. j->restart_interval = 0;
  2464. if (!stbi__decode_jpeg_header(j, STBI__SCAN_load)) return 0;
  2465. m = stbi__get_marker(j);
  2466. while (!stbi__EOI(m)) {
  2467. if (stbi__SOS(m)) {
  2468. if (!stbi__process_scan_header(j)) return 0;
  2469. if (!stbi__parse_entropy_coded_data(j)) return 0;
  2470. if (j->marker == STBI__MARKER_none ) {
  2471. // handle 0s at the end of image data from IP Kamera 9060
  2472. while (!stbi__at_eof(j->s)) {
  2473. int x = stbi__get8(j->s);
  2474. if (x == 255) {
  2475. j->marker = stbi__get8(j->s);
  2476. break;
  2477. } else if (x != 0) {
  2478. return stbi__err("junk before marker", "Corrupt JPEG");
  2479. }
  2480. }
  2481. // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
  2482. }
  2483. } else {
  2484. if (!stbi__process_marker(j, m)) return 0;
  2485. }
  2486. m = stbi__get_marker(j);
  2487. }
  2488. if (j->progressive)
  2489. stbi__jpeg_finish(j);
  2490. return 1;
  2491. }
  2492. // static jfif-centered resampling (across block boundaries)
  2493. typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
  2494. int w, int hs);
  2495. #define stbi__div4(x) ((stbi_uc) ((x) >> 2))
  2496. static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2497. {
  2498. STBI_NOTUSED(out);
  2499. STBI_NOTUSED(in_far);
  2500. STBI_NOTUSED(w);
  2501. STBI_NOTUSED(hs);
  2502. return in_near;
  2503. }
  2504. static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2505. {
  2506. // need to generate two samples vertically for every one in input
  2507. int i;
  2508. STBI_NOTUSED(hs);
  2509. for (i=0; i < w; ++i)
  2510. out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
  2511. return out;
  2512. }
  2513. static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2514. {
  2515. // need to generate two samples horizontally for every one in input
  2516. int i;
  2517. stbi_uc *input = in_near;
  2518. if (w == 1) {
  2519. // if only one sample, can't do any interpolation
  2520. out[0] = out[1] = input[0];
  2521. return out;
  2522. }
  2523. out[0] = input[0];
  2524. out[1] = stbi__div4(input[0]*3 + input[1] + 2);
  2525. for (i=1; i < w-1; ++i) {
  2526. int n = 3*input[i]+2;
  2527. out[i*2+0] = stbi__div4(n+input[i-1]);
  2528. out[i*2+1] = stbi__div4(n+input[i+1]);
  2529. }
  2530. out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
  2531. out[i*2+1] = input[w-1];
  2532. STBI_NOTUSED(in_far);
  2533. STBI_NOTUSED(hs);
  2534. return out;
  2535. }
  2536. #define stbi__div16(x) ((stbi_uc) ((x) >> 4))
  2537. static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2538. {
  2539. // need to generate 2x2 samples for every one in input
  2540. int i,t0,t1;
  2541. if (w == 1) {
  2542. out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
  2543. return out;
  2544. }
  2545. t1 = 3*in_near[0] + in_far[0];
  2546. out[0] = stbi__div4(t1+2);
  2547. for (i=1; i < w; ++i) {
  2548. t0 = t1;
  2549. t1 = 3*in_near[i]+in_far[i];
  2550. out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
  2551. out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
  2552. }
  2553. out[w*2-1] = stbi__div4(t1+2);
  2554. STBI_NOTUSED(hs);
  2555. return out;
  2556. }
  2557. #if defined(STBI_SSE2) || defined(STBI_NEON)
  2558. static stbi_uc *stbi__resample_row_hv_2_simd(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2559. {
  2560. // need to generate 2x2 samples for every one in input
  2561. int i=0,t0,t1;
  2562. if (w == 1) {
  2563. out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
  2564. return out;
  2565. }
  2566. t1 = 3*in_near[0] + in_far[0];
  2567. // process groups of 8 pixels for as long as we can.
  2568. // note we can't handle the last pixel in a row in this loop
  2569. // because we need to handle the filter boundary conditions.
  2570. for (; i < ((w-1) & ~7); i += 8) {
  2571. #if defined(STBI_SSE2)
  2572. // load and perform the vertical filtering pass
  2573. // this uses 3*x + y = 4*x + (y - x)
  2574. __m128i zero = _mm_setzero_si128();
  2575. __m128i farb = _mm_loadl_epi64((__m128i *) (in_far + i));
  2576. __m128i nearb = _mm_loadl_epi64((__m128i *) (in_near + i));
  2577. __m128i farw = _mm_unpacklo_epi8(farb, zero);
  2578. __m128i nearw = _mm_unpacklo_epi8(nearb, zero);
  2579. __m128i diff = _mm_sub_epi16(farw, nearw);
  2580. __m128i nears = _mm_slli_epi16(nearw, 2);
  2581. __m128i curr = _mm_add_epi16(nears, diff); // current row
  2582. // horizontal filter works the same based on shifted vers of current
  2583. // row. "prev" is current row shifted right by 1 pixel; we need to
  2584. // insert the previous pixel value (from t1).
  2585. // "next" is current row shifted left by 1 pixel, with first pixel
  2586. // of next block of 8 pixels added in.
  2587. __m128i prv0 = _mm_slli_si128(curr, 2);
  2588. __m128i nxt0 = _mm_srli_si128(curr, 2);
  2589. __m128i prev = _mm_insert_epi16(prv0, t1, 0);
  2590. __m128i next = _mm_insert_epi16(nxt0, 3*in_near[i+8] + in_far[i+8], 7);
  2591. // horizontal filter, polyphase implementation since it's convenient:
  2592. // even pixels = 3*cur + prev = cur*4 + (prev - cur)
  2593. // odd pixels = 3*cur + next = cur*4 + (next - cur)
  2594. // note the shared term.
  2595. __m128i bias = _mm_set1_epi16(8);
  2596. __m128i curs = _mm_slli_epi16(curr, 2);
  2597. __m128i prvd = _mm_sub_epi16(prev, curr);
  2598. __m128i nxtd = _mm_sub_epi16(next, curr);
  2599. __m128i curb = _mm_add_epi16(curs, bias);
  2600. __m128i even = _mm_add_epi16(prvd, curb);
  2601. __m128i odd = _mm_add_epi16(nxtd, curb);
  2602. // interleave even and odd pixels, then undo scaling.
  2603. __m128i int0 = _mm_unpacklo_epi16(even, odd);
  2604. __m128i int1 = _mm_unpackhi_epi16(even, odd);
  2605. __m128i de0 = _mm_srli_epi16(int0, 4);
  2606. __m128i de1 = _mm_srli_epi16(int1, 4);
  2607. // pack and write output
  2608. __m128i outv = _mm_packus_epi16(de0, de1);
  2609. _mm_storeu_si128((__m128i *) (out + i*2), outv);
  2610. #elif defined(STBI_NEON)
  2611. // load and perform the vertical filtering pass
  2612. // this uses 3*x + y = 4*x + (y - x)
  2613. uint8x8_t farb = vld1_u8(in_far + i);
  2614. uint8x8_t nearb = vld1_u8(in_near + i);
  2615. int16x8_t diff = vreinterpretq_s16_u16(vsubl_u8(farb, nearb));
  2616. int16x8_t nears = vreinterpretq_s16_u16(vshll_n_u8(nearb, 2));
  2617. int16x8_t curr = vaddq_s16(nears, diff); // current row
  2618. // horizontal filter works the same based on shifted vers of current
  2619. // row. "prev" is current row shifted right by 1 pixel; we need to
  2620. // insert the previous pixel value (from t1).
  2621. // "next" is current row shifted left by 1 pixel, with first pixel
  2622. // of next block of 8 pixels added in.
  2623. int16x8_t prv0 = vextq_s16(curr, curr, 7);
  2624. int16x8_t nxt0 = vextq_s16(curr, curr, 1);
  2625. int16x8_t prev = vsetq_lane_s16(t1, prv0, 0);
  2626. int16x8_t next = vsetq_lane_s16(3*in_near[i+8] + in_far[i+8], nxt0, 7);
  2627. // horizontal filter, polyphase implementation since it's convenient:
  2628. // even pixels = 3*cur + prev = cur*4 + (prev - cur)
  2629. // odd pixels = 3*cur + next = cur*4 + (next - cur)
  2630. // note the shared term.
  2631. int16x8_t curs = vshlq_n_s16(curr, 2);
  2632. int16x8_t prvd = vsubq_s16(prev, curr);
  2633. int16x8_t nxtd = vsubq_s16(next, curr);
  2634. int16x8_t even = vaddq_s16(curs, prvd);
  2635. int16x8_t odd = vaddq_s16(curs, nxtd);
  2636. // undo scaling and round, then store with even/odd phases interleaved
  2637. uint8x8x2_t o;
  2638. o.val[0] = vqrshrun_n_s16(even, 4);
  2639. o.val[1] = vqrshrun_n_s16(odd, 4);
  2640. vst2_u8(out + i*2, o);
  2641. #endif
  2642. // "previous" value for next iter
  2643. t1 = 3*in_near[i+7] + in_far[i+7];
  2644. }
  2645. t0 = t1;
  2646. t1 = 3*in_near[i] + in_far[i];
  2647. out[i*2] = stbi__div16(3*t1 + t0 + 8);
  2648. for (++i; i < w; ++i) {
  2649. t0 = t1;
  2650. t1 = 3*in_near[i]+in_far[i];
  2651. out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
  2652. out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
  2653. }
  2654. out[w*2-1] = stbi__div4(t1+2);
  2655. STBI_NOTUSED(hs);
  2656. return out;
  2657. }
  2658. #endif
  2659. static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  2660. {
  2661. // resample with nearest-neighbor
  2662. int i,j;
  2663. STBI_NOTUSED(in_far);
  2664. for (i=0; i < w; ++i)
  2665. for (j=0; j < hs; ++j)
  2666. out[i*hs+j] = in_near[i];
  2667. return out;
  2668. }
  2669. #ifdef STBI_JPEG_OLD
  2670. // this is the same YCbCr-to-RGB calculation that stb_image has used
  2671. // historically before the algorithm changes in 1.49
  2672. #define float2fixed(x) ((int) ((x) * 65536 + 0.5))
  2673. static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
  2674. {
  2675. int i;
  2676. for (i=0; i < count; ++i) {
  2677. int y_fixed = (y[i] << 16) + 32768; // rounding
  2678. int r,g,b;
  2679. int cr = pcr[i] - 128;
  2680. int cb = pcb[i] - 128;
  2681. r = y_fixed + cr*float2fixed(1.40200f);
  2682. g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
  2683. b = y_fixed + cb*float2fixed(1.77200f);
  2684. r >>= 16;
  2685. g >>= 16;
  2686. b >>= 16;
  2687. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2688. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2689. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2690. out[0] = (stbi_uc)r;
  2691. out[1] = (stbi_uc)g;
  2692. out[2] = (stbi_uc)b;
  2693. out[3] = 255;
  2694. out += step;
  2695. }
  2696. }
  2697. #else
  2698. // this is a reduced-precision calculation of YCbCr-to-RGB introduced
  2699. // to make sure the code produces the same results in both SIMD and scalar
  2700. #define float2fixed(x) (((int) ((x) * 4096.0f + 0.5f)) << 8)
  2701. static void stbi__YCbCr_to_RGB_row(stbi_uc *out, const stbi_uc *y, const stbi_uc *pcb, const stbi_uc *pcr, int count, int step)
  2702. {
  2703. int i;
  2704. for (i=0; i < count; ++i) {
  2705. int y_fixed = (y[i] << 20) + (1<<19); // rounding
  2706. int r,g,b;
  2707. int cr = pcr[i] - 128;
  2708. int cb = pcb[i] - 128;
  2709. r = y_fixed + cr* float2fixed(1.40200f);
  2710. g = y_fixed + (cr*-float2fixed(0.71414f)) + ((cb*-float2fixed(0.34414f)) & 0xffff0000);
  2711. b = y_fixed + cb* float2fixed(1.77200f);
  2712. r >>= 20;
  2713. g >>= 20;
  2714. b >>= 20;
  2715. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2716. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2717. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2718. out[0] = (stbi_uc)r;
  2719. out[1] = (stbi_uc)g;
  2720. out[2] = (stbi_uc)b;
  2721. out[3] = 255;
  2722. out += step;
  2723. }
  2724. }
  2725. #endif
  2726. #if defined(STBI_SSE2) || defined(STBI_NEON)
  2727. static void stbi__YCbCr_to_RGB_simd(stbi_uc *out, stbi_uc const *y, stbi_uc const *pcb, stbi_uc const *pcr, int count, int step)
  2728. {
  2729. int i = 0;
  2730. #ifdef STBI_SSE2
  2731. // step == 3 is pretty ugly on the final interleave, and i'm not convinced
  2732. // it's useful in practice (you wouldn't use it for textures, for example).
  2733. // so just accelerate step == 4 case.
  2734. if (step == 4) {
  2735. // this is a fairly straightforward implementation and not super-optimized.
  2736. __m128i signflip = _mm_set1_epi8(-0x80);
  2737. __m128i cr_const0 = _mm_set1_epi16( (short) ( 1.40200f*4096.0f+0.5f));
  2738. __m128i cr_const1 = _mm_set1_epi16( - (short) ( 0.71414f*4096.0f+0.5f));
  2739. __m128i cb_const0 = _mm_set1_epi16( - (short) ( 0.34414f*4096.0f+0.5f));
  2740. __m128i cb_const1 = _mm_set1_epi16( (short) ( 1.77200f*4096.0f+0.5f));
  2741. __m128i y_bias = _mm_set1_epi8((char) (unsigned char) 128);
  2742. __m128i xw = _mm_set1_epi16(255); // alpha channel
  2743. for (; i+7 < count; i += 8) {
  2744. // load
  2745. __m128i y_bytes = _mm_loadl_epi64((__m128i *) (y+i));
  2746. __m128i cr_bytes = _mm_loadl_epi64((__m128i *) (pcr+i));
  2747. __m128i cb_bytes = _mm_loadl_epi64((__m128i *) (pcb+i));
  2748. __m128i cr_biased = _mm_xor_si128(cr_bytes, signflip); // -128
  2749. __m128i cb_biased = _mm_xor_si128(cb_bytes, signflip); // -128
  2750. // unpack to short (and left-shift cr, cb by 8)
  2751. __m128i yw = _mm_unpacklo_epi8(y_bias, y_bytes);
  2752. __m128i crw = _mm_unpacklo_epi8(_mm_setzero_si128(), cr_biased);
  2753. __m128i cbw = _mm_unpacklo_epi8(_mm_setzero_si128(), cb_biased);
  2754. // color transform
  2755. __m128i yws = _mm_srli_epi16(yw, 4);
  2756. __m128i cr0 = _mm_mulhi_epi16(cr_const0, crw);
  2757. __m128i cb0 = _mm_mulhi_epi16(cb_const0, cbw);
  2758. __m128i cb1 = _mm_mulhi_epi16(cbw, cb_const1);
  2759. __m128i cr1 = _mm_mulhi_epi16(crw, cr_const1);
  2760. __m128i rws = _mm_add_epi16(cr0, yws);
  2761. __m128i gwt = _mm_add_epi16(cb0, yws);
  2762. __m128i bws = _mm_add_epi16(yws, cb1);
  2763. __m128i gws = _mm_add_epi16(gwt, cr1);
  2764. // descale
  2765. __m128i rw = _mm_srai_epi16(rws, 4);
  2766. __m128i bw = _mm_srai_epi16(bws, 4);
  2767. __m128i gw = _mm_srai_epi16(gws, 4);
  2768. // back to byte, set up for transpose
  2769. __m128i brb = _mm_packus_epi16(rw, bw);
  2770. __m128i gxb = _mm_packus_epi16(gw, xw);
  2771. // transpose to interleave channels
  2772. __m128i t0 = _mm_unpacklo_epi8(brb, gxb);
  2773. __m128i t1 = _mm_unpackhi_epi8(brb, gxb);
  2774. __m128i o0 = _mm_unpacklo_epi16(t0, t1);
  2775. __m128i o1 = _mm_unpackhi_epi16(t0, t1);
  2776. // store
  2777. _mm_storeu_si128((__m128i *) (out + 0), o0);
  2778. _mm_storeu_si128((__m128i *) (out + 16), o1);
  2779. out += 32;
  2780. }
  2781. }
  2782. #endif
  2783. #ifdef STBI_NEON
  2784. // in this version, step=3 support would be easy to add. but is there demand?
  2785. if (step == 4) {
  2786. // this is a fairly straightforward implementation and not super-optimized.
  2787. uint8x8_t signflip = vdup_n_u8(0x80);
  2788. int16x8_t cr_const0 = vdupq_n_s16( (short) ( 1.40200f*4096.0f+0.5f));
  2789. int16x8_t cr_const1 = vdupq_n_s16( - (short) ( 0.71414f*4096.0f+0.5f));
  2790. int16x8_t cb_const0 = vdupq_n_s16( - (short) ( 0.34414f*4096.0f+0.5f));
  2791. int16x8_t cb_const1 = vdupq_n_s16( (short) ( 1.77200f*4096.0f+0.5f));
  2792. for (; i+7 < count; i += 8) {
  2793. // load
  2794. uint8x8_t y_bytes = vld1_u8(y + i);
  2795. uint8x8_t cr_bytes = vld1_u8(pcr + i);
  2796. uint8x8_t cb_bytes = vld1_u8(pcb + i);
  2797. int8x8_t cr_biased = vreinterpret_s8_u8(vsub_u8(cr_bytes, signflip));
  2798. int8x8_t cb_biased = vreinterpret_s8_u8(vsub_u8(cb_bytes, signflip));
  2799. // expand to s16
  2800. int16x8_t yws = vreinterpretq_s16_u16(vshll_n_u8(y_bytes, 4));
  2801. int16x8_t crw = vshll_n_s8(cr_biased, 7);
  2802. int16x8_t cbw = vshll_n_s8(cb_biased, 7);
  2803. // color transform
  2804. int16x8_t cr0 = vqdmulhq_s16(crw, cr_const0);
  2805. int16x8_t cb0 = vqdmulhq_s16(cbw, cb_const0);
  2806. int16x8_t cr1 = vqdmulhq_s16(crw, cr_const1);
  2807. int16x8_t cb1 = vqdmulhq_s16(cbw, cb_const1);
  2808. int16x8_t rws = vaddq_s16(yws, cr0);
  2809. int16x8_t gws = vaddq_s16(vaddq_s16(yws, cb0), cr1);
  2810. int16x8_t bws = vaddq_s16(yws, cb1);
  2811. // undo scaling, round, convert to byte
  2812. uint8x8x4_t o;
  2813. o.val[0] = vqrshrun_n_s16(rws, 4);
  2814. o.val[1] = vqrshrun_n_s16(gws, 4);
  2815. o.val[2] = vqrshrun_n_s16(bws, 4);
  2816. o.val[3] = vdup_n_u8(255);
  2817. // store, interleaving r/g/b/a
  2818. vst4_u8(out, o);
  2819. out += 8*4;
  2820. }
  2821. }
  2822. #endif
  2823. for (; i < count; ++i) {
  2824. int y_fixed = (y[i] << 20) + (1<<19); // rounding
  2825. int r,g,b;
  2826. int cr = pcr[i] - 128;
  2827. int cb = pcb[i] - 128;
  2828. r = y_fixed + cr* float2fixed(1.40200f);
  2829. g = y_fixed + cr*-float2fixed(0.71414f) + ((cb*-float2fixed(0.34414f)) & 0xffff0000);
  2830. b = y_fixed + cb* float2fixed(1.77200f);
  2831. r >>= 20;
  2832. g >>= 20;
  2833. b >>= 20;
  2834. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  2835. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  2836. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  2837. out[0] = (stbi_uc)r;
  2838. out[1] = (stbi_uc)g;
  2839. out[2] = (stbi_uc)b;
  2840. out[3] = 255;
  2841. out += step;
  2842. }
  2843. }
  2844. #endif
  2845. // set up the kernels
  2846. static void stbi__setup_jpeg(stbi__jpeg *j)
  2847. {
  2848. j->idct_block_kernel = stbi__idct_block;
  2849. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_row;
  2850. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2;
  2851. #ifdef STBI_SSE2
  2852. if (stbi__sse2_available()) {
  2853. j->idct_block_kernel = stbi__idct_simd;
  2854. #ifndef STBI_JPEG_OLD
  2855. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
  2856. #endif
  2857. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
  2858. }
  2859. #endif
  2860. #ifdef STBI_NEON
  2861. j->idct_block_kernel = stbi__idct_simd;
  2862. #ifndef STBI_JPEG_OLD
  2863. j->YCbCr_to_RGB_kernel = stbi__YCbCr_to_RGB_simd;
  2864. #endif
  2865. j->resample_row_hv_2_kernel = stbi__resample_row_hv_2_simd;
  2866. #endif
  2867. }
  2868. // clean up the temporary component buffers
  2869. static void stbi__cleanup_jpeg(stbi__jpeg *j)
  2870. {
  2871. int i;
  2872. for (i=0; i < j->s->img_n; ++i) {
  2873. if (j->img_comp[i].raw_data) {
  2874. STBI_FREE(j->img_comp[i].raw_data);
  2875. j->img_comp[i].raw_data = NULL;
  2876. j->img_comp[i].data = NULL;
  2877. }
  2878. if (j->img_comp[i].raw_coeff) {
  2879. STBI_FREE(j->img_comp[i].raw_coeff);
  2880. j->img_comp[i].raw_coeff = 0;
  2881. j->img_comp[i].coeff = 0;
  2882. }
  2883. if (j->img_comp[i].linebuf) {
  2884. STBI_FREE(j->img_comp[i].linebuf);
  2885. j->img_comp[i].linebuf = NULL;
  2886. }
  2887. }
  2888. }
  2889. typedef struct
  2890. {
  2891. resample_row_func resample;
  2892. stbi_uc *line0,*line1;
  2893. int hs,vs; // expansion factor in each axis
  2894. int w_lores; // horizontal pixels pre-expansion
  2895. int ystep; // how far through vertical expansion we are
  2896. int ypos; // which pre-expansion row we're on
  2897. } stbi__resample;
  2898. static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
  2899. {
  2900. int n, decode_n;
  2901. z->s->img_n = 0; // make stbi__cleanup_jpeg safe
  2902. // validate req_comp
  2903. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  2904. // load a jpeg image from whichever source, but leave in YCbCr format
  2905. if (!stbi__decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
  2906. // determine actual number of components to generate
  2907. n = req_comp ? req_comp : z->s->img_n;
  2908. if (z->s->img_n == 3 && n < 3)
  2909. decode_n = 1;
  2910. else
  2911. decode_n = z->s->img_n;
  2912. // resample and color-convert
  2913. {
  2914. int k;
  2915. unsigned int i,j;
  2916. stbi_uc *output;
  2917. stbi_uc *coutput[4];
  2918. stbi__resample res_comp[4];
  2919. for (k=0; k < decode_n; ++k) {
  2920. stbi__resample *r = &res_comp[k];
  2921. // allocate line buffer big enough for upsampling off the edges
  2922. // with upsample factor of 4
  2923. z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
  2924. if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  2925. r->hs = z->img_h_max / z->img_comp[k].h;
  2926. r->vs = z->img_v_max / z->img_comp[k].v;
  2927. r->ystep = r->vs >> 1;
  2928. r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
  2929. r->ypos = 0;
  2930. r->line0 = r->line1 = z->img_comp[k].data;
  2931. if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
  2932. else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
  2933. else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
  2934. else if (r->hs == 2 && r->vs == 2) r->resample = z->resample_row_hv_2_kernel;
  2935. else r->resample = stbi__resample_row_generic;
  2936. }
  2937. // can't error after this so, this is safe
  2938. output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1);
  2939. if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  2940. // now go ahead and resample
  2941. for (j=0; j < z->s->img_y; ++j) {
  2942. stbi_uc *out = output + n * z->s->img_x * j;
  2943. for (k=0; k < decode_n; ++k) {
  2944. stbi__resample *r = &res_comp[k];
  2945. int y_bot = r->ystep >= (r->vs >> 1);
  2946. coutput[k] = r->resample(z->img_comp[k].linebuf,
  2947. y_bot ? r->line1 : r->line0,
  2948. y_bot ? r->line0 : r->line1,
  2949. r->w_lores, r->hs);
  2950. if (++r->ystep >= r->vs) {
  2951. r->ystep = 0;
  2952. r->line0 = r->line1;
  2953. if (++r->ypos < z->img_comp[k].y)
  2954. r->line1 += z->img_comp[k].w2;
  2955. }
  2956. }
  2957. if (n >= 3) {
  2958. stbi_uc *y = coutput[0];
  2959. if (z->s->img_n == 3) {
  2960. z->YCbCr_to_RGB_kernel(out, y, coutput[1], coutput[2], z->s->img_x, n);
  2961. } else
  2962. for (i=0; i < z->s->img_x; ++i) {
  2963. out[0] = out[1] = out[2] = y[i];
  2964. out[3] = 255; // not used if n==3
  2965. out += n;
  2966. }
  2967. } else {
  2968. stbi_uc *y = coutput[0];
  2969. if (n == 1)
  2970. for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
  2971. else
  2972. for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
  2973. }
  2974. }
  2975. stbi__cleanup_jpeg(z);
  2976. *out_x = z->s->img_x;
  2977. *out_y = z->s->img_y;
  2978. if (comp) *comp = z->s->img_n; // report original components, not output
  2979. return output;
  2980. }
  2981. }
  2982. static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  2983. {
  2984. stbi__jpeg j;
  2985. j.s = s;
  2986. stbi__setup_jpeg(&j);
  2987. return load_jpeg_image(&j, x,y,comp,req_comp);
  2988. }
  2989. static int stbi__jpeg_test(stbi__context *s)
  2990. {
  2991. int r;
  2992. stbi__jpeg j;
  2993. j.s = s;
  2994. stbi__setup_jpeg(&j);
  2995. r = stbi__decode_jpeg_header(&j, STBI__SCAN_type);
  2996. stbi__rewind(s);
  2997. return r;
  2998. }
  2999. static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
  3000. {
  3001. if (!stbi__decode_jpeg_header(j, STBI__SCAN_header)) {
  3002. stbi__rewind( j->s );
  3003. return 0;
  3004. }
  3005. if (x) *x = j->s->img_x;
  3006. if (y) *y = j->s->img_y;
  3007. if (comp) *comp = j->s->img_n;
  3008. return 1;
  3009. }
  3010. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
  3011. {
  3012. stbi__jpeg j;
  3013. j.s = s;
  3014. return stbi__jpeg_info_raw(&j, x, y, comp);
  3015. }
  3016. #endif
  3017. // public domain zlib decode v0.2 Sean Barrett 2006-11-18
  3018. // simple implementation
  3019. // - all input must be provided in an upfront buffer
  3020. // - all output is written to a single output buffer (can malloc/realloc)
  3021. // performance
  3022. // - fast huffman
  3023. #ifndef STBI_NO_ZLIB
  3024. // fast-way is faster to check than jpeg huffman, but slow way is slower
  3025. #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
  3026. #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
  3027. // zlib-style huffman encoding
  3028. // (jpegs packs from left, zlib from right, so can't share code)
  3029. typedef struct
  3030. {
  3031. stbi__uint16 fast[1 << STBI__ZFAST_BITS];
  3032. stbi__uint16 firstcode[16];
  3033. int maxcode[17];
  3034. stbi__uint16 firstsymbol[16];
  3035. stbi_uc size[288];
  3036. stbi__uint16 value[288];
  3037. } stbi__zhuffman;
  3038. stbi_inline static int stbi__bitreverse16(int n)
  3039. {
  3040. n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
  3041. n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
  3042. n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
  3043. n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
  3044. return n;
  3045. }
  3046. stbi_inline static int stbi__bit_reverse(int v, int bits)
  3047. {
  3048. STBI_ASSERT(bits <= 16);
  3049. // to bit reverse n bits, reverse 16 and shift
  3050. // e.g. 11 bits, bit reverse and shift away 5
  3051. return stbi__bitreverse16(v) >> (16-bits);
  3052. }
  3053. static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num)
  3054. {
  3055. int i,k=0;
  3056. int code, next_code[16], sizes[17];
  3057. // DEFLATE spec for generating codes
  3058. memset(sizes, 0, sizeof(sizes));
  3059. memset(z->fast, 0, sizeof(z->fast));
  3060. for (i=0; i < num; ++i)
  3061. ++sizes[sizelist[i]];
  3062. sizes[0] = 0;
  3063. for (i=1; i < 16; ++i)
  3064. if (sizes[i] > (1 << i))
  3065. return stbi__err("bad sizes", "Corrupt PNG");
  3066. code = 0;
  3067. for (i=1; i < 16; ++i) {
  3068. next_code[i] = code;
  3069. z->firstcode[i] = (stbi__uint16) code;
  3070. z->firstsymbol[i] = (stbi__uint16) k;
  3071. code = (code + sizes[i]);
  3072. if (sizes[i])
  3073. if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt PNG");
  3074. z->maxcode[i] = code << (16-i); // preshift for inner loop
  3075. code <<= 1;
  3076. k += sizes[i];
  3077. }
  3078. z->maxcode[16] = 0x10000; // sentinel
  3079. for (i=0; i < num; ++i) {
  3080. int s = sizelist[i];
  3081. if (s) {
  3082. int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
  3083. stbi__uint16 fastv = (stbi__uint16) ((s << 9) | i);
  3084. z->size [c] = (stbi_uc ) s;
  3085. z->value[c] = (stbi__uint16) i;
  3086. if (s <= STBI__ZFAST_BITS) {
  3087. int k = stbi__bit_reverse(next_code[s],s);
  3088. while (k < (1 << STBI__ZFAST_BITS)) {
  3089. z->fast[k] = fastv;
  3090. k += (1 << s);
  3091. }
  3092. }
  3093. ++next_code[s];
  3094. }
  3095. }
  3096. return 1;
  3097. }
  3098. // zlib-from-memory implementation for PNG reading
  3099. // because PNG allows splitting the zlib stream arbitrarily,
  3100. // and it's annoying structurally to have PNG call ZLIB call PNG,
  3101. // we require PNG read all the IDATs and combine them into a single
  3102. // memory buffer
  3103. typedef struct
  3104. {
  3105. stbi_uc *zbuffer, *zbuffer_end;
  3106. int num_bits;
  3107. stbi__uint32 code_buffer;
  3108. char *zout;
  3109. char *zout_start;
  3110. char *zout_end;
  3111. int z_expandable;
  3112. stbi__zhuffman z_length, z_distance;
  3113. } stbi__zbuf;
  3114. stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
  3115. {
  3116. if (z->zbuffer >= z->zbuffer_end) return 0;
  3117. return *z->zbuffer++;
  3118. }
  3119. static void stbi__fill_bits(stbi__zbuf *z)
  3120. {
  3121. do {
  3122. STBI_ASSERT(z->code_buffer < (1U << z->num_bits));
  3123. z->code_buffer |= stbi__zget8(z) << z->num_bits;
  3124. z->num_bits += 8;
  3125. } while (z->num_bits <= 24);
  3126. }
  3127. stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
  3128. {
  3129. unsigned int k;
  3130. if (z->num_bits < n) stbi__fill_bits(z);
  3131. k = z->code_buffer & ((1 << n) - 1);
  3132. z->code_buffer >>= n;
  3133. z->num_bits -= n;
  3134. return k;
  3135. }
  3136. static int stbi__zhuffman_decode_slowpath(stbi__zbuf *a, stbi__zhuffman *z)
  3137. {
  3138. int b,s,k;
  3139. // not resolved by fast table, so compute it the slow way
  3140. // use jpeg approach, which requires MSbits at top
  3141. k = stbi__bit_reverse(a->code_buffer, 16);
  3142. for (s=STBI__ZFAST_BITS+1; ; ++s)
  3143. if (k < z->maxcode[s])
  3144. break;
  3145. if (s == 16) return -1; // invalid code!
  3146. // code size is s, so:
  3147. b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
  3148. STBI_ASSERT(z->size[b] == s);
  3149. a->code_buffer >>= s;
  3150. a->num_bits -= s;
  3151. return z->value[b];
  3152. }
  3153. stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
  3154. {
  3155. int b,s;
  3156. if (a->num_bits < 16) stbi__fill_bits(a);
  3157. b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
  3158. if (b) {
  3159. s = b >> 9;
  3160. a->code_buffer >>= s;
  3161. a->num_bits -= s;
  3162. return b & 511;
  3163. }
  3164. return stbi__zhuffman_decode_slowpath(a, z);
  3165. }
  3166. static int stbi__zexpand(stbi__zbuf *z, char *zout, int n) // need to make room for n bytes
  3167. {
  3168. char *q;
  3169. int cur, limit;
  3170. z->zout = zout;
  3171. if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
  3172. cur = (int) (z->zout - z->zout_start);
  3173. limit = (int) (z->zout_end - z->zout_start);
  3174. while (cur + n > limit)
  3175. limit *= 2;
  3176. q = (char *) STBI_REALLOC(z->zout_start, limit);
  3177. if (q == NULL) return stbi__err("outofmem", "Out of memory");
  3178. z->zout_start = q;
  3179. z->zout = q + cur;
  3180. z->zout_end = q + limit;
  3181. return 1;
  3182. }
  3183. static int stbi__zlength_base[31] = {
  3184. 3,4,5,6,7,8,9,10,11,13,
  3185. 15,17,19,23,27,31,35,43,51,59,
  3186. 67,83,99,115,131,163,195,227,258,0,0 };
  3187. static int stbi__zlength_extra[31]=
  3188. { 0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0 };
  3189. static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
  3190. 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  3191. static int stbi__zdist_extra[32] =
  3192. { 0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
  3193. static int stbi__parse_huffman_block(stbi__zbuf *a)
  3194. {
  3195. char *zout = a->zout;
  3196. for(;;) {
  3197. int z = stbi__zhuffman_decode(a, &a->z_length);
  3198. if (z < 256) {
  3199. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
  3200. if (zout >= a->zout_end) {
  3201. if (!stbi__zexpand(a, zout, 1)) return 0;
  3202. zout = a->zout;
  3203. }
  3204. *zout++ = (char) z;
  3205. } else {
  3206. stbi_uc *p;
  3207. int len,dist;
  3208. if (z == 256) {
  3209. a->zout = zout;
  3210. return 1;
  3211. }
  3212. z -= 257;
  3213. len = stbi__zlength_base[z];
  3214. if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
  3215. z = stbi__zhuffman_decode(a, &a->z_distance);
  3216. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");
  3217. dist = stbi__zdist_base[z];
  3218. if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
  3219. if (zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
  3220. if (zout + len > a->zout_end) {
  3221. if (!stbi__zexpand(a, zout, len)) return 0;
  3222. zout = a->zout;
  3223. }
  3224. p = (stbi_uc *) (zout - dist);
  3225. if (dist == 1) { // run of one byte; common in images.
  3226. stbi_uc v = *p;
  3227. if (len) { do *zout++ = v; while (--len); }
  3228. } else {
  3229. if (len) { do *zout++ = *p++; while (--len); }
  3230. }
  3231. }
  3232. }
  3233. }
  3234. static int stbi__compute_huffman_codes(stbi__zbuf *a)
  3235. {
  3236. static stbi_uc length_dezigzag[19] = { 16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15 };
  3237. stbi__zhuffman z_codelength;
  3238. stbi_uc lencodes[286+32+137];//padding for maximum single op
  3239. stbi_uc codelength_sizes[19];
  3240. int i,n;
  3241. int hlit = stbi__zreceive(a,5) + 257;
  3242. int hdist = stbi__zreceive(a,5) + 1;
  3243. int hclen = stbi__zreceive(a,4) + 4;
  3244. memset(codelength_sizes, 0, sizeof(codelength_sizes));
  3245. for (i=0; i < hclen; ++i) {
  3246. int s = stbi__zreceive(a,3);
  3247. codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
  3248. }
  3249. if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
  3250. n = 0;
  3251. while (n < hlit + hdist) {
  3252. int c = stbi__zhuffman_decode(a, &z_codelength);
  3253. if (c < 0 || c >= 19) return stbi__err("bad codelengths", "Corrupt PNG");
  3254. if (c < 16)
  3255. lencodes[n++] = (stbi_uc) c;
  3256. else if (c == 16) {
  3257. c = stbi__zreceive(a,2)+3;
  3258. memset(lencodes+n, lencodes[n-1], c);
  3259. n += c;
  3260. } else if (c == 17) {
  3261. c = stbi__zreceive(a,3)+3;
  3262. memset(lencodes+n, 0, c);
  3263. n += c;
  3264. } else {
  3265. STBI_ASSERT(c == 18);
  3266. c = stbi__zreceive(a,7)+11;
  3267. memset(lencodes+n, 0, c);
  3268. n += c;
  3269. }
  3270. }
  3271. if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");
  3272. if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
  3273. if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
  3274. return 1;
  3275. }
  3276. static int stbi__parse_uncomperssed_block(stbi__zbuf *a)
  3277. {
  3278. stbi_uc header[4];
  3279. int len,nlen,k;
  3280. if (a->num_bits & 7)
  3281. stbi__zreceive(a, a->num_bits & 7); // discard
  3282. // drain the bit-packed data into header
  3283. k = 0;
  3284. while (a->num_bits > 0) {
  3285. header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
  3286. a->code_buffer >>= 8;
  3287. a->num_bits -= 8;
  3288. }
  3289. STBI_ASSERT(a->num_bits == 0);
  3290. // now fill header the normal way
  3291. while (k < 4)
  3292. header[k++] = stbi__zget8(a);
  3293. len = header[1] * 256 + header[0];
  3294. nlen = header[3] * 256 + header[2];
  3295. if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
  3296. if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
  3297. if (a->zout + len > a->zout_end)
  3298. if (!stbi__zexpand(a, a->zout, len)) return 0;
  3299. memcpy(a->zout, a->zbuffer, len);
  3300. a->zbuffer += len;
  3301. a->zout += len;
  3302. return 1;
  3303. }
  3304. static int stbi__parse_zlib_header(stbi__zbuf *a)
  3305. {
  3306. int cmf = stbi__zget8(a);
  3307. int cm = cmf & 15;
  3308. /* int cinfo = cmf >> 4; */
  3309. int flg = stbi__zget8(a);
  3310. if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
  3311. if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
  3312. if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
  3313. // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
  3314. return 1;
  3315. }
  3316. // @TODO: should statically initialize these for optimal thread safety
  3317. static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32];
  3318. static void stbi__init_zdefaults(void)
  3319. {
  3320. int i; // use <= to match clearly with spec
  3321. for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
  3322. for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
  3323. for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
  3324. for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
  3325. for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
  3326. }
  3327. static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
  3328. {
  3329. int final, type;
  3330. if (parse_header)
  3331. if (!stbi__parse_zlib_header(a)) return 0;
  3332. a->num_bits = 0;
  3333. a->code_buffer = 0;
  3334. do {
  3335. final = stbi__zreceive(a,1);
  3336. type = stbi__zreceive(a,2);
  3337. if (type == 0) {
  3338. if (!stbi__parse_uncomperssed_block(a)) return 0;
  3339. } else if (type == 3) {
  3340. return 0;
  3341. } else {
  3342. if (type == 1) {
  3343. // use fixed code lengths
  3344. if (!stbi__zdefault_distance[31]) stbi__init_zdefaults();
  3345. if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;
  3346. if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
  3347. } else {
  3348. if (!stbi__compute_huffman_codes(a)) return 0;
  3349. }
  3350. if (!stbi__parse_huffman_block(a)) return 0;
  3351. }
  3352. } while (!final);
  3353. return 1;
  3354. }
  3355. static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
  3356. {
  3357. a->zout_start = obuf;
  3358. a->zout = obuf;
  3359. a->zout_end = obuf + olen;
  3360. a->z_expandable = exp;
  3361. return stbi__parse_zlib(a, parse_header);
  3362. }
  3363. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
  3364. {
  3365. stbi__zbuf a;
  3366. char *p = (char *) stbi__malloc(initial_size);
  3367. if (p == NULL) return NULL;
  3368. a.zbuffer = (stbi_uc *) buffer;
  3369. a.zbuffer_end = (stbi_uc *) buffer + len;
  3370. if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
  3371. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3372. return a.zout_start;
  3373. } else {
  3374. STBI_FREE(a.zout_start);
  3375. return NULL;
  3376. }
  3377. }
  3378. STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
  3379. {
  3380. return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
  3381. }
  3382. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
  3383. {
  3384. stbi__zbuf a;
  3385. char *p = (char *) stbi__malloc(initial_size);
  3386. if (p == NULL) return NULL;
  3387. a.zbuffer = (stbi_uc *) buffer;
  3388. a.zbuffer_end = (stbi_uc *) buffer + len;
  3389. if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
  3390. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3391. return a.zout_start;
  3392. } else {
  3393. STBI_FREE(a.zout_start);
  3394. return NULL;
  3395. }
  3396. }
  3397. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
  3398. {
  3399. stbi__zbuf a;
  3400. a.zbuffer = (stbi_uc *) ibuffer;
  3401. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  3402. if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
  3403. return (int) (a.zout - a.zout_start);
  3404. else
  3405. return -1;
  3406. }
  3407. STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
  3408. {
  3409. stbi__zbuf a;
  3410. char *p = (char *) stbi__malloc(16384);
  3411. if (p == NULL) return NULL;
  3412. a.zbuffer = (stbi_uc *) buffer;
  3413. a.zbuffer_end = (stbi_uc *) buffer+len;
  3414. if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
  3415. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  3416. return a.zout_start;
  3417. } else {
  3418. STBI_FREE(a.zout_start);
  3419. return NULL;
  3420. }
  3421. }
  3422. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
  3423. {
  3424. stbi__zbuf a;
  3425. a.zbuffer = (stbi_uc *) ibuffer;
  3426. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  3427. if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
  3428. return (int) (a.zout - a.zout_start);
  3429. else
  3430. return -1;
  3431. }
  3432. #endif
  3433. // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
  3434. // simple implementation
  3435. // - only 8-bit samples
  3436. // - no CRC checking
  3437. // - allocates lots of intermediate memory
  3438. // - avoids problem of streaming data between subsystems
  3439. // - avoids explicit window management
  3440. // performance
  3441. // - uses stb_zlib, a PD zlib implementation with fast huffman decoding
  3442. #ifndef STBI_NO_PNG
  3443. typedef struct
  3444. {
  3445. stbi__uint32 length;
  3446. stbi__uint32 type;
  3447. } stbi__pngchunk;
  3448. static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
  3449. {
  3450. stbi__pngchunk c;
  3451. c.length = stbi__get32be(s);
  3452. c.type = stbi__get32be(s);
  3453. return c;
  3454. }
  3455. static int stbi__check_png_header(stbi__context *s)
  3456. {
  3457. static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
  3458. int i;
  3459. for (i=0; i < 8; ++i)
  3460. if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
  3461. return 1;
  3462. }
  3463. typedef struct
  3464. {
  3465. stbi__context *s;
  3466. stbi_uc *idata, *expanded, *out;
  3467. } stbi__png;
  3468. enum {
  3469. STBI__F_none=0,
  3470. STBI__F_sub=1,
  3471. STBI__F_up=2,
  3472. STBI__F_avg=3,
  3473. STBI__F_paeth=4,
  3474. // synthetic filters used for first scanline to avoid needing a dummy row of 0s
  3475. STBI__F_avg_first,
  3476. STBI__F_paeth_first
  3477. };
  3478. static stbi_uc first_row_filter[5] =
  3479. {
  3480. STBI__F_none,
  3481. STBI__F_sub,
  3482. STBI__F_none,
  3483. STBI__F_avg_first,
  3484. STBI__F_paeth_first
  3485. };
  3486. static int stbi__paeth(int a, int b, int c)
  3487. {
  3488. int p = a + b - c;
  3489. int pa = abs(p-a);
  3490. int pb = abs(p-b);
  3491. int pc = abs(p-c);
  3492. if (pa <= pb && pa <= pc) return a;
  3493. if (pb <= pc) return b;
  3494. return c;
  3495. }
  3496. static stbi_uc stbi__depth_scale_table[9] = { 0, 0xff, 0x55, 0, 0x11, 0,0,0, 0x01 };
  3497. // create the png data from post-deflated data
  3498. static int stbi__create_png_image_raw(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, stbi__uint32 x, stbi__uint32 y, int depth, int color)
  3499. {
  3500. stbi__context *s = a->s;
  3501. stbi__uint32 i,j,stride = x*out_n;
  3502. stbi__uint32 img_len, img_width_bytes;
  3503. int k;
  3504. int img_n = s->img_n; // copy it into a local for later
  3505. STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
  3506. a->out = (stbi_uc *) stbi__malloc(x * y * out_n); // extra bytes to write off the end into
  3507. if (!a->out) return stbi__err("outofmem", "Out of memory");
  3508. img_width_bytes = (((img_n * x * depth) + 7) >> 3);
  3509. img_len = (img_width_bytes + 1) * y;
  3510. if (s->img_x == x && s->img_y == y) {
  3511. if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG");
  3512. } else { // interlaced:
  3513. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
  3514. }
  3515. for (j=0; j < y; ++j) {
  3516. stbi_uc *cur = a->out + stride*j;
  3517. stbi_uc *prior = cur - stride;
  3518. int filter = *raw++;
  3519. int filter_bytes = img_n;
  3520. int width = x;
  3521. if (filter > 4)
  3522. return stbi__err("invalid filter","Corrupt PNG");
  3523. if (depth < 8) {
  3524. STBI_ASSERT(img_width_bytes <= x);
  3525. cur += x*out_n - img_width_bytes; // store output to the rightmost img_len bytes, so we can decode in place
  3526. filter_bytes = 1;
  3527. width = img_width_bytes;
  3528. }
  3529. // if first row, use special filter that doesn't sample previous row
  3530. if (j == 0) filter = first_row_filter[filter];
  3531. // handle first byte explicitly
  3532. for (k=0; k < filter_bytes; ++k) {
  3533. switch (filter) {
  3534. case STBI__F_none : cur[k] = raw[k]; break;
  3535. case STBI__F_sub : cur[k] = raw[k]; break;
  3536. case STBI__F_up : cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3537. case STBI__F_avg : cur[k] = STBI__BYTECAST(raw[k] + (prior[k]>>1)); break;
  3538. case STBI__F_paeth : cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(0,prior[k],0)); break;
  3539. case STBI__F_avg_first : cur[k] = raw[k]; break;
  3540. case STBI__F_paeth_first: cur[k] = raw[k]; break;
  3541. }
  3542. }
  3543. if (depth == 8) {
  3544. if (img_n != out_n)
  3545. cur[img_n] = 255; // first pixel
  3546. raw += img_n;
  3547. cur += out_n;
  3548. prior += out_n;
  3549. } else {
  3550. raw += 1;
  3551. cur += 1;
  3552. prior += 1;
  3553. }
  3554. // this is a little gross, so that we don't switch per-pixel or per-component
  3555. if (depth < 8 || img_n == out_n) {
  3556. int nk = (width - 1)*img_n;
  3557. #define CASE(f) \
  3558. case f: \
  3559. for (k=0; k < nk; ++k)
  3560. switch (filter) {
  3561. // "none" filter turns into a memcpy here; make that explicit.
  3562. case STBI__F_none: memcpy(cur, raw, nk); break;
  3563. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-filter_bytes]); break;
  3564. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3565. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-filter_bytes])>>1)); break;
  3566. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],prior[k],prior[k-filter_bytes])); break;
  3567. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-filter_bytes] >> 1)); break;
  3568. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-filter_bytes],0,0)); break;
  3569. }
  3570. #undef CASE
  3571. raw += nk;
  3572. } else {
  3573. STBI_ASSERT(img_n+1 == out_n);
  3574. #define CASE(f) \
  3575. case f: \
  3576. for (i=x-1; i >= 1; --i, cur[img_n]=255,raw+=img_n,cur+=out_n,prior+=out_n) \
  3577. for (k=0; k < img_n; ++k)
  3578. switch (filter) {
  3579. CASE(STBI__F_none) cur[k] = raw[k]; break;
  3580. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(raw[k] + cur[k-out_n]); break;
  3581. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(raw[k] + prior[k]); break;
  3582. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(raw[k] + ((prior[k] + cur[k-out_n])>>1)); break;
  3583. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
  3584. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(raw[k] + (cur[k-out_n] >> 1)); break;
  3585. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(raw[k] + stbi__paeth(cur[k-out_n],0,0)); break;
  3586. }
  3587. #undef CASE
  3588. }
  3589. }
  3590. // we make a separate pass to expand bits to pixels; for performance,
  3591. // this could run two scanlines behind the above code, so it won't
  3592. // intefere with filtering but will still be in the cache.
  3593. if (depth < 8) {
  3594. for (j=0; j < y; ++j) {
  3595. stbi_uc *cur = a->out + stride*j;
  3596. stbi_uc *in = a->out + stride*j + x*out_n - img_width_bytes;
  3597. // unpack 1/2/4-bit into a 8-bit buffer. allows us to keep the common 8-bit path optimal at minimal cost for 1/2/4-bit
  3598. // png guarante byte alignment, if width is not multiple of 8/4/2 we'll decode dummy trailing data that will be skipped in the later loop
  3599. stbi_uc scale = (color == 0) ? stbi__depth_scale_table[depth] : 1; // scale grayscale values to 0..255 range
  3600. // note that the final byte might overshoot and write more data than desired.
  3601. // we can allocate enough data that this never writes out of memory, but it
  3602. // could also overwrite the next scanline. can it overwrite non-empty data
  3603. // on the next scanline? yes, consider 1-pixel-wide scanlines with 1-bit-per-pixel.
  3604. // so we need to explicitly clamp the final ones
  3605. if (depth == 4) {
  3606. for (k=x*img_n; k >= 2; k-=2, ++in) {
  3607. *cur++ = scale * ((*in >> 4) );
  3608. *cur++ = scale * ((*in ) & 0x0f);
  3609. }
  3610. if (k > 0) *cur++ = scale * ((*in >> 4) );
  3611. } else if (depth == 2) {
  3612. for (k=x*img_n; k >= 4; k-=4, ++in) {
  3613. *cur++ = scale * ((*in >> 6) );
  3614. *cur++ = scale * ((*in >> 4) & 0x03);
  3615. *cur++ = scale * ((*in >> 2) & 0x03);
  3616. *cur++ = scale * ((*in ) & 0x03);
  3617. }
  3618. if (k > 0) *cur++ = scale * ((*in >> 6) );
  3619. if (k > 1) *cur++ = scale * ((*in >> 4) & 0x03);
  3620. if (k > 2) *cur++ = scale * ((*in >> 2) & 0x03);
  3621. } else if (depth == 1) {
  3622. for (k=x*img_n; k >= 8; k-=8, ++in) {
  3623. *cur++ = scale * ((*in >> 7) );
  3624. *cur++ = scale * ((*in >> 6) & 0x01);
  3625. *cur++ = scale * ((*in >> 5) & 0x01);
  3626. *cur++ = scale * ((*in >> 4) & 0x01);
  3627. *cur++ = scale * ((*in >> 3) & 0x01);
  3628. *cur++ = scale * ((*in >> 2) & 0x01);
  3629. *cur++ = scale * ((*in >> 1) & 0x01);
  3630. *cur++ = scale * ((*in ) & 0x01);
  3631. }
  3632. if (k > 0) *cur++ = scale * ((*in >> 7) );
  3633. if (k > 1) *cur++ = scale * ((*in >> 6) & 0x01);
  3634. if (k > 2) *cur++ = scale * ((*in >> 5) & 0x01);
  3635. if (k > 3) *cur++ = scale * ((*in >> 4) & 0x01);
  3636. if (k > 4) *cur++ = scale * ((*in >> 3) & 0x01);
  3637. if (k > 5) *cur++ = scale * ((*in >> 2) & 0x01);
  3638. if (k > 6) *cur++ = scale * ((*in >> 1) & 0x01);
  3639. }
  3640. if (img_n != out_n) {
  3641. // insert alpha = 255
  3642. stbi_uc *cur = a->out + stride*j;
  3643. int i;
  3644. if (img_n == 1) {
  3645. for (i=x-1; i >= 0; --i) {
  3646. cur[i*2+1] = 255;
  3647. cur[i*2+0] = cur[i];
  3648. }
  3649. } else {
  3650. STBI_ASSERT(img_n == 3);
  3651. for (i=x-1; i >= 0; --i) {
  3652. cur[i*4+3] = 255;
  3653. cur[i*4+2] = cur[i*3+2];
  3654. cur[i*4+1] = cur[i*3+1];
  3655. cur[i*4+0] = cur[i*3+0];
  3656. }
  3657. }
  3658. }
  3659. }
  3660. }
  3661. return 1;
  3662. }
  3663. static int stbi__create_png_image(stbi__png *a, stbi_uc *image_data, stbi__uint32 image_data_len, int out_n, int depth, int color, int interlaced)
  3664. {
  3665. stbi_uc *final;
  3666. int p;
  3667. if (!interlaced)
  3668. return stbi__create_png_image_raw(a, image_data, image_data_len, out_n, a->s->img_x, a->s->img_y, depth, color);
  3669. // de-interlacing
  3670. final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n);
  3671. for (p=0; p < 7; ++p) {
  3672. int xorig[] = { 0,4,0,2,0,1,0 };
  3673. int yorig[] = { 0,0,4,0,2,0,1 };
  3674. int xspc[] = { 8,8,4,4,2,2,1 };
  3675. int yspc[] = { 8,8,8,4,4,2,2 };
  3676. int i,j,x,y;
  3677. // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
  3678. x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
  3679. y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
  3680. if (x && y) {
  3681. stbi__uint32 img_len = ((((a->s->img_n * x * depth) + 7) >> 3) + 1) * y;
  3682. if (!stbi__create_png_image_raw(a, image_data, image_data_len, out_n, x, y, depth, color)) {
  3683. STBI_FREE(final);
  3684. return 0;
  3685. }
  3686. for (j=0; j < y; ++j) {
  3687. for (i=0; i < x; ++i) {
  3688. int out_y = j*yspc[p]+yorig[p];
  3689. int out_x = i*xspc[p]+xorig[p];
  3690. memcpy(final + out_y*a->s->img_x*out_n + out_x*out_n,
  3691. a->out + (j*x+i)*out_n, out_n);
  3692. }
  3693. }
  3694. STBI_FREE(a->out);
  3695. image_data += img_len;
  3696. image_data_len -= img_len;
  3697. }
  3698. }
  3699. a->out = final;
  3700. return 1;
  3701. }
  3702. static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
  3703. {
  3704. stbi__context *s = z->s;
  3705. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  3706. stbi_uc *p = z->out;
  3707. // compute color-based transparency, assuming we've
  3708. // already got 255 as the alpha value in the output
  3709. STBI_ASSERT(out_n == 2 || out_n == 4);
  3710. if (out_n == 2) {
  3711. for (i=0; i < pixel_count; ++i) {
  3712. p[1] = (p[0] == tc[0] ? 0 : 255);
  3713. p += 2;
  3714. }
  3715. } else {
  3716. for (i=0; i < pixel_count; ++i) {
  3717. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  3718. p[3] = 0;
  3719. p += 4;
  3720. }
  3721. }
  3722. return 1;
  3723. }
  3724. static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
  3725. {
  3726. stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
  3727. stbi_uc *p, *temp_out, *orig = a->out;
  3728. p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n);
  3729. if (p == NULL) return stbi__err("outofmem", "Out of memory");
  3730. // between here and free(out) below, exitting would leak
  3731. temp_out = p;
  3732. if (pal_img_n == 3) {
  3733. for (i=0; i < pixel_count; ++i) {
  3734. int n = orig[i]*4;
  3735. p[0] = palette[n ];
  3736. p[1] = palette[n+1];
  3737. p[2] = palette[n+2];
  3738. p += 3;
  3739. }
  3740. } else {
  3741. for (i=0; i < pixel_count; ++i) {
  3742. int n = orig[i]*4;
  3743. p[0] = palette[n ];
  3744. p[1] = palette[n+1];
  3745. p[2] = palette[n+2];
  3746. p[3] = palette[n+3];
  3747. p += 4;
  3748. }
  3749. }
  3750. STBI_FREE(a->out);
  3751. a->out = temp_out;
  3752. STBI_NOTUSED(len);
  3753. return 1;
  3754. }
  3755. static int stbi__unpremultiply_on_load = 0;
  3756. static int stbi__de_iphone_flag = 0;
  3757. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
  3758. {
  3759. stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
  3760. }
  3761. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
  3762. {
  3763. stbi__de_iphone_flag = flag_true_if_should_convert;
  3764. }
  3765. static void stbi__de_iphone(stbi__png *z)
  3766. {
  3767. stbi__context *s = z->s;
  3768. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  3769. stbi_uc *p = z->out;
  3770. if (s->img_out_n == 3) { // convert bgr to rgb
  3771. for (i=0; i < pixel_count; ++i) {
  3772. stbi_uc t = p[0];
  3773. p[0] = p[2];
  3774. p[2] = t;
  3775. p += 3;
  3776. }
  3777. } else {
  3778. STBI_ASSERT(s->img_out_n == 4);
  3779. if (stbi__unpremultiply_on_load) {
  3780. // convert bgr to rgb and unpremultiply
  3781. for (i=0; i < pixel_count; ++i) {
  3782. stbi_uc a = p[3];
  3783. stbi_uc t = p[0];
  3784. if (a) {
  3785. p[0] = p[2] * 255 / a;
  3786. p[1] = p[1] * 255 / a;
  3787. p[2] = t * 255 / a;
  3788. } else {
  3789. p[0] = p[2];
  3790. p[2] = t;
  3791. }
  3792. p += 4;
  3793. }
  3794. } else {
  3795. // convert bgr to rgb
  3796. for (i=0; i < pixel_count; ++i) {
  3797. stbi_uc t = p[0];
  3798. p[0] = p[2];
  3799. p[2] = t;
  3800. p += 4;
  3801. }
  3802. }
  3803. }
  3804. }
  3805. #define STBI__PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
  3806. static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
  3807. {
  3808. stbi_uc palette[1024], pal_img_n=0;
  3809. stbi_uc has_trans=0, tc[3];
  3810. stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
  3811. int first=1,k,interlace=0, color=0, depth=0, is_iphone=0;
  3812. stbi__context *s = z->s;
  3813. z->expanded = NULL;
  3814. z->idata = NULL;
  3815. z->out = NULL;
  3816. if (!stbi__check_png_header(s)) return 0;
  3817. if (scan == STBI__SCAN_type) return 1;
  3818. for (;;) {
  3819. stbi__pngchunk c = stbi__get_chunk_header(s);
  3820. switch (c.type) {
  3821. case STBI__PNG_TYPE('C','g','B','I'):
  3822. is_iphone = 1;
  3823. stbi__skip(s, c.length);
  3824. break;
  3825. case STBI__PNG_TYPE('I','H','D','R'): {
  3826. int comp,filter;
  3827. if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
  3828. first = 0;
  3829. if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
  3830. s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  3831. s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  3832. depth = stbi__get8(s); if (depth != 1 && depth != 2 && depth != 4 && depth != 8) return stbi__err("1/2/4/8-bit only","PNG not supported: 1/2/4/8-bit only");
  3833. color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
  3834. if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
  3835. comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
  3836. filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
  3837. interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
  3838. if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
  3839. if (!pal_img_n) {
  3840. s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
  3841. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  3842. if (scan == STBI__SCAN_header) return 1;
  3843. } else {
  3844. // if paletted, then pal_n is our final components, and
  3845. // img_n is # components to decompress/filter.
  3846. s->img_n = 1;
  3847. if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
  3848. // if SCAN_header, have to scan to see if we have a tRNS
  3849. }
  3850. break;
  3851. }
  3852. case STBI__PNG_TYPE('P','L','T','E'): {
  3853. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3854. if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
  3855. pal_len = c.length / 3;
  3856. if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
  3857. for (i=0; i < pal_len; ++i) {
  3858. palette[i*4+0] = stbi__get8(s);
  3859. palette[i*4+1] = stbi__get8(s);
  3860. palette[i*4+2] = stbi__get8(s);
  3861. palette[i*4+3] = 255;
  3862. }
  3863. break;
  3864. }
  3865. case STBI__PNG_TYPE('t','R','N','S'): {
  3866. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3867. if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
  3868. if (pal_img_n) {
  3869. if (scan == STBI__SCAN_header) { s->img_n = 4; return 1; }
  3870. if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
  3871. if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
  3872. pal_img_n = 4;
  3873. for (i=0; i < c.length; ++i)
  3874. palette[i*4+3] = stbi__get8(s);
  3875. } else {
  3876. if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
  3877. if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
  3878. has_trans = 1;
  3879. for (k=0; k < s->img_n; ++k)
  3880. tc[k] = (stbi_uc) (stbi__get16be(s) & 255) * stbi__depth_scale_table[depth]; // non 8-bit images will be larger
  3881. }
  3882. break;
  3883. }
  3884. case STBI__PNG_TYPE('I','D','A','T'): {
  3885. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3886. if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
  3887. if (scan == STBI__SCAN_header) { s->img_n = pal_img_n; return 1; }
  3888. if ((int)(ioff + c.length) < (int)ioff) return 0;
  3889. if (ioff + c.length > idata_limit) {
  3890. stbi_uc *p;
  3891. if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
  3892. while (ioff + c.length > idata_limit)
  3893. idata_limit *= 2;
  3894. p = (stbi_uc *) STBI_REALLOC(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
  3895. z->idata = p;
  3896. }
  3897. if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
  3898. ioff += c.length;
  3899. break;
  3900. }
  3901. case STBI__PNG_TYPE('I','E','N','D'): {
  3902. stbi__uint32 raw_len, bpl;
  3903. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3904. if (scan != STBI__SCAN_load) return 1;
  3905. if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
  3906. // initial guess for decoded data size to avoid unnecessary reallocs
  3907. bpl = (s->img_x * depth + 7) / 8; // bytes per line, per component
  3908. raw_len = bpl * s->img_y * s->img_n /* pixels */ + s->img_y /* filter mode per row */;
  3909. z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, raw_len, (int *) &raw_len, !is_iphone);
  3910. if (z->expanded == NULL) return 0; // zlib should set error
  3911. STBI_FREE(z->idata); z->idata = NULL;
  3912. if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
  3913. s->img_out_n = s->img_n+1;
  3914. else
  3915. s->img_out_n = s->img_n;
  3916. if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0;
  3917. if (has_trans)
  3918. if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
  3919. if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
  3920. stbi__de_iphone(z);
  3921. if (pal_img_n) {
  3922. // pal_img_n == 3 or 4
  3923. s->img_n = pal_img_n; // record the actual colors we had
  3924. s->img_out_n = pal_img_n;
  3925. if (req_comp >= 3) s->img_out_n = req_comp;
  3926. if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
  3927. return 0;
  3928. }
  3929. STBI_FREE(z->expanded); z->expanded = NULL;
  3930. return 1;
  3931. }
  3932. default:
  3933. // if critical, fail
  3934. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  3935. if ((c.type & (1 << 29)) == 0) {
  3936. #ifndef STBI_NO_FAILURE_STRINGS
  3937. // not threadsafe
  3938. static char invalid_chunk[] = "XXXX PNG chunk not known";
  3939. invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
  3940. invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
  3941. invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
  3942. invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
  3943. #endif
  3944. return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
  3945. }
  3946. stbi__skip(s, c.length);
  3947. break;
  3948. }
  3949. // end of PNG chunk, read and skip CRC
  3950. stbi__get32be(s);
  3951. }
  3952. }
  3953. static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)
  3954. {
  3955. unsigned char *result=NULL;
  3956. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  3957. if (stbi__parse_png_file(p, STBI__SCAN_load, req_comp)) {
  3958. result = p->out;
  3959. p->out = NULL;
  3960. if (req_comp && req_comp != p->s->img_out_n) {
  3961. result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  3962. p->s->img_out_n = req_comp;
  3963. if (result == NULL) return result;
  3964. }
  3965. *x = p->s->img_x;
  3966. *y = p->s->img_y;
  3967. if (n) *n = p->s->img_out_n;
  3968. }
  3969. STBI_FREE(p->out); p->out = NULL;
  3970. STBI_FREE(p->expanded); p->expanded = NULL;
  3971. STBI_FREE(p->idata); p->idata = NULL;
  3972. return result;
  3973. }
  3974. static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  3975. {
  3976. stbi__png p;
  3977. p.s = s;
  3978. return stbi__do_png(&p, x,y,comp,req_comp);
  3979. }
  3980. static int stbi__png_test(stbi__context *s)
  3981. {
  3982. int r;
  3983. r = stbi__check_png_header(s);
  3984. stbi__rewind(s);
  3985. return r;
  3986. }
  3987. static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
  3988. {
  3989. if (!stbi__parse_png_file(p, STBI__SCAN_header, 0)) {
  3990. stbi__rewind( p->s );
  3991. return 0;
  3992. }
  3993. if (x) *x = p->s->img_x;
  3994. if (y) *y = p->s->img_y;
  3995. if (comp) *comp = p->s->img_n;
  3996. return 1;
  3997. }
  3998. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
  3999. {
  4000. stbi__png p;
  4001. p.s = s;
  4002. return stbi__png_info_raw(&p, x, y, comp);
  4003. }
  4004. #endif
  4005. // Microsoft/Windows BMP image
  4006. #ifndef STBI_NO_BMP
  4007. static int stbi__bmp_test_raw(stbi__context *s)
  4008. {
  4009. int r;
  4010. int sz;
  4011. if (stbi__get8(s) != 'B') return 0;
  4012. if (stbi__get8(s) != 'M') return 0;
  4013. stbi__get32le(s); // discard filesize
  4014. stbi__get16le(s); // discard reserved
  4015. stbi__get16le(s); // discard reserved
  4016. stbi__get32le(s); // discard data offset
  4017. sz = stbi__get32le(s);
  4018. r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
  4019. return r;
  4020. }
  4021. static int stbi__bmp_test(stbi__context *s)
  4022. {
  4023. int r = stbi__bmp_test_raw(s);
  4024. stbi__rewind(s);
  4025. return r;
  4026. }
  4027. // returns 0..31 for the highest set bit
  4028. static int stbi__high_bit(unsigned int z)
  4029. {
  4030. int n=0;
  4031. if (z == 0) return -1;
  4032. if (z >= 0x10000) n += 16, z >>= 16;
  4033. if (z >= 0x00100) n += 8, z >>= 8;
  4034. if (z >= 0x00010) n += 4, z >>= 4;
  4035. if (z >= 0x00004) n += 2, z >>= 2;
  4036. if (z >= 0x00002) n += 1, z >>= 1;
  4037. return n;
  4038. }
  4039. static int stbi__bitcount(unsigned int a)
  4040. {
  4041. a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
  4042. a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
  4043. a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
  4044. a = (a + (a >> 8)); // max 16 per 8 bits
  4045. a = (a + (a >> 16)); // max 32 per 8 bits
  4046. return a & 0xff;
  4047. }
  4048. static int stbi__shiftsigned(int v, int shift, int bits)
  4049. {
  4050. int result;
  4051. int z=0;
  4052. if (shift < 0) v <<= -shift;
  4053. else v >>= shift;
  4054. result = v;
  4055. z = bits;
  4056. while (z < 8) {
  4057. result += v >> z;
  4058. z += bits;
  4059. }
  4060. return result;
  4061. }
  4062. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4063. {
  4064. stbi_uc *out;
  4065. unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
  4066. stbi_uc pal[256][4];
  4067. int psize=0,i,j,compress=0,width;
  4068. int bpp, flip_vertically, pad, target, offset, hsz;
  4069. if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
  4070. stbi__get32le(s); // discard filesize
  4071. stbi__get16le(s); // discard reserved
  4072. stbi__get16le(s); // discard reserved
  4073. offset = stbi__get32le(s);
  4074. hsz = stbi__get32le(s);
  4075. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
  4076. if (hsz == 12) {
  4077. s->img_x = stbi__get16le(s);
  4078. s->img_y = stbi__get16le(s);
  4079. } else {
  4080. s->img_x = stbi__get32le(s);
  4081. s->img_y = stbi__get32le(s);
  4082. }
  4083. if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
  4084. bpp = stbi__get16le(s);
  4085. if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit");
  4086. flip_vertically = ((int) s->img_y) > 0;
  4087. s->img_y = abs((int) s->img_y);
  4088. if (hsz == 12) {
  4089. if (bpp < 24)
  4090. psize = (offset - 14 - 24) / 3;
  4091. } else {
  4092. compress = stbi__get32le(s);
  4093. if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
  4094. stbi__get32le(s); // discard sizeof
  4095. stbi__get32le(s); // discard hres
  4096. stbi__get32le(s); // discard vres
  4097. stbi__get32le(s); // discard colorsused
  4098. stbi__get32le(s); // discard max important
  4099. if (hsz == 40 || hsz == 56) {
  4100. if (hsz == 56) {
  4101. stbi__get32le(s);
  4102. stbi__get32le(s);
  4103. stbi__get32le(s);
  4104. stbi__get32le(s);
  4105. }
  4106. if (bpp == 16 || bpp == 32) {
  4107. mr = mg = mb = 0;
  4108. if (compress == 0) {
  4109. if (bpp == 32) {
  4110. mr = 0xffu << 16;
  4111. mg = 0xffu << 8;
  4112. mb = 0xffu << 0;
  4113. ma = 0xffu << 24;
  4114. fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
  4115. STBI_NOTUSED(fake_a);
  4116. } else {
  4117. mr = 31u << 10;
  4118. mg = 31u << 5;
  4119. mb = 31u << 0;
  4120. }
  4121. } else if (compress == 3) {
  4122. mr = stbi__get32le(s);
  4123. mg = stbi__get32le(s);
  4124. mb = stbi__get32le(s);
  4125. // not documented, but generated by photoshop and handled by mspaint
  4126. if (mr == mg && mg == mb) {
  4127. // ?!?!?
  4128. return stbi__errpuc("bad BMP", "bad BMP");
  4129. }
  4130. } else
  4131. return stbi__errpuc("bad BMP", "bad BMP");
  4132. }
  4133. } else {
  4134. STBI_ASSERT(hsz == 108 || hsz == 124);
  4135. mr = stbi__get32le(s);
  4136. mg = stbi__get32le(s);
  4137. mb = stbi__get32le(s);
  4138. ma = stbi__get32le(s);
  4139. stbi__get32le(s); // discard color space
  4140. for (i=0; i < 12; ++i)
  4141. stbi__get32le(s); // discard color space parameters
  4142. if (hsz == 124) {
  4143. stbi__get32le(s); // discard rendering intent
  4144. stbi__get32le(s); // discard offset of profile data
  4145. stbi__get32le(s); // discard size of profile data
  4146. stbi__get32le(s); // discard reserved
  4147. }
  4148. }
  4149. if (bpp < 16)
  4150. psize = (offset - 14 - hsz) >> 2;
  4151. }
  4152. s->img_n = ma ? 4 : 3;
  4153. if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
  4154. target = req_comp;
  4155. else
  4156. target = s->img_n; // if they want monochrome, we'll post-convert
  4157. out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y);
  4158. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  4159. if (bpp < 16) {
  4160. int z=0;
  4161. if (psize == 0 || psize > 256) { STBI_FREE(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
  4162. for (i=0; i < psize; ++i) {
  4163. pal[i][2] = stbi__get8(s);
  4164. pal[i][1] = stbi__get8(s);
  4165. pal[i][0] = stbi__get8(s);
  4166. if (hsz != 12) stbi__get8(s);
  4167. pal[i][3] = 255;
  4168. }
  4169. stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
  4170. if (bpp == 4) width = (s->img_x + 1) >> 1;
  4171. else if (bpp == 8) width = s->img_x;
  4172. else { STBI_FREE(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
  4173. pad = (-width)&3;
  4174. for (j=0; j < (int) s->img_y; ++j) {
  4175. for (i=0; i < (int) s->img_x; i += 2) {
  4176. int v=stbi__get8(s),v2=0;
  4177. if (bpp == 4) {
  4178. v2 = v & 15;
  4179. v >>= 4;
  4180. }
  4181. out[z++] = pal[v][0];
  4182. out[z++] = pal[v][1];
  4183. out[z++] = pal[v][2];
  4184. if (target == 4) out[z++] = 255;
  4185. if (i+1 == (int) s->img_x) break;
  4186. v = (bpp == 8) ? stbi__get8(s) : v2;
  4187. out[z++] = pal[v][0];
  4188. out[z++] = pal[v][1];
  4189. out[z++] = pal[v][2];
  4190. if (target == 4) out[z++] = 255;
  4191. }
  4192. stbi__skip(s, pad);
  4193. }
  4194. } else {
  4195. int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
  4196. int z = 0;
  4197. int easy=0;
  4198. stbi__skip(s, offset - 14 - hsz);
  4199. if (bpp == 24) width = 3 * s->img_x;
  4200. else if (bpp == 16) width = 2*s->img_x;
  4201. else /* bpp = 32 and pad = 0 */ width=0;
  4202. pad = (-width) & 3;
  4203. if (bpp == 24) {
  4204. easy = 1;
  4205. } else if (bpp == 32) {
  4206. if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
  4207. easy = 2;
  4208. }
  4209. if (!easy) {
  4210. if (!mr || !mg || !mb) { STBI_FREE(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
  4211. // right shift amt to put high bit in position #7
  4212. rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
  4213. gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
  4214. bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
  4215. ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
  4216. }
  4217. for (j=0; j < (int) s->img_y; ++j) {
  4218. if (easy) {
  4219. for (i=0; i < (int) s->img_x; ++i) {
  4220. unsigned char a;
  4221. out[z+2] = stbi__get8(s);
  4222. out[z+1] = stbi__get8(s);
  4223. out[z+0] = stbi__get8(s);
  4224. z += 3;
  4225. a = (easy == 2 ? stbi__get8(s) : 255);
  4226. if (target == 4) out[z++] = a;
  4227. }
  4228. } else {
  4229. for (i=0; i < (int) s->img_x; ++i) {
  4230. stbi__uint32 v = (bpp == 16 ? (stbi__uint32) stbi__get16le(s) : stbi__get32le(s));
  4231. int a;
  4232. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
  4233. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
  4234. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
  4235. a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
  4236. if (target == 4) out[z++] = STBI__BYTECAST(a);
  4237. }
  4238. }
  4239. stbi__skip(s, pad);
  4240. }
  4241. }
  4242. if (flip_vertically) {
  4243. stbi_uc t;
  4244. for (j=0; j < (int) s->img_y>>1; ++j) {
  4245. stbi_uc *p1 = out + j *s->img_x*target;
  4246. stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
  4247. for (i=0; i < (int) s->img_x*target; ++i) {
  4248. t = p1[i], p1[i] = p2[i], p2[i] = t;
  4249. }
  4250. }
  4251. }
  4252. if (req_comp && req_comp != target) {
  4253. out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
  4254. if (out == NULL) return out; // stbi__convert_format frees input on failure
  4255. }
  4256. *x = s->img_x;
  4257. *y = s->img_y;
  4258. if (comp) *comp = s->img_n;
  4259. return out;
  4260. }
  4261. #endif
  4262. // Targa Truevision - TGA
  4263. // by Jonathan Dummer
  4264. #ifndef STBI_NO_TGA
  4265. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
  4266. {
  4267. int tga_w, tga_h, tga_comp;
  4268. int sz;
  4269. stbi__get8(s); // discard Offset
  4270. sz = stbi__get8(s); // color type
  4271. if( sz > 1 ) {
  4272. stbi__rewind(s);
  4273. return 0; // only RGB or indexed allowed
  4274. }
  4275. sz = stbi__get8(s); // image type
  4276. // only RGB or grey allowed, +/- RLE
  4277. if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
  4278. stbi__skip(s,9);
  4279. tga_w = stbi__get16le(s);
  4280. if( tga_w < 1 ) {
  4281. stbi__rewind(s);
  4282. return 0; // test width
  4283. }
  4284. tga_h = stbi__get16le(s);
  4285. if( tga_h < 1 ) {
  4286. stbi__rewind(s);
  4287. return 0; // test height
  4288. }
  4289. sz = stbi__get8(s); // bits per pixel
  4290. // only RGB or RGBA or grey allowed
  4291. if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
  4292. stbi__rewind(s);
  4293. return 0;
  4294. }
  4295. tga_comp = sz;
  4296. if (x) *x = tga_w;
  4297. if (y) *y = tga_h;
  4298. if (comp) *comp = tga_comp / 8;
  4299. return 1; // seems to have passed everything
  4300. }
  4301. static int stbi__tga_test(stbi__context *s)
  4302. {
  4303. int res;
  4304. int sz;
  4305. stbi__get8(s); // discard Offset
  4306. sz = stbi__get8(s); // color type
  4307. if ( sz > 1 ) return 0; // only RGB or indexed allowed
  4308. sz = stbi__get8(s); // image type
  4309. if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
  4310. stbi__get16be(s); // discard palette start
  4311. stbi__get16be(s); // discard palette length
  4312. stbi__get8(s); // discard bits per palette color entry
  4313. stbi__get16be(s); // discard x origin
  4314. stbi__get16be(s); // discard y origin
  4315. if ( stbi__get16be(s) < 1 ) return 0; // test width
  4316. if ( stbi__get16be(s) < 1 ) return 0; // test height
  4317. sz = stbi__get8(s); // bits per pixel
  4318. if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) )
  4319. res = 0;
  4320. else
  4321. res = 1;
  4322. stbi__rewind(s);
  4323. return res;
  4324. }
  4325. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4326. {
  4327. // read in the TGA header stuff
  4328. int tga_offset = stbi__get8(s);
  4329. int tga_indexed = stbi__get8(s);
  4330. int tga_image_type = stbi__get8(s);
  4331. int tga_is_RLE = 0;
  4332. int tga_palette_start = stbi__get16le(s);
  4333. int tga_palette_len = stbi__get16le(s);
  4334. int tga_palette_bits = stbi__get8(s);
  4335. int tga_x_origin = stbi__get16le(s);
  4336. int tga_y_origin = stbi__get16le(s);
  4337. int tga_width = stbi__get16le(s);
  4338. int tga_height = stbi__get16le(s);
  4339. int tga_bits_per_pixel = stbi__get8(s);
  4340. int tga_comp = tga_bits_per_pixel / 8;
  4341. int tga_inverted = stbi__get8(s);
  4342. // image data
  4343. unsigned char *tga_data;
  4344. unsigned char *tga_palette = NULL;
  4345. int i, j;
  4346. unsigned char raw_data[4];
  4347. int RLE_count = 0;
  4348. int RLE_repeating = 0;
  4349. int read_next_pixel = 1;
  4350. // do a tiny bit of precessing
  4351. if ( tga_image_type >= 8 )
  4352. {
  4353. tga_image_type -= 8;
  4354. tga_is_RLE = 1;
  4355. }
  4356. /* int tga_alpha_bits = tga_inverted & 15; */
  4357. tga_inverted = 1 - ((tga_inverted >> 5) & 1);
  4358. // error check
  4359. if ( //(tga_indexed) ||
  4360. (tga_width < 1) || (tga_height < 1) ||
  4361. (tga_image_type < 1) || (tga_image_type > 3) ||
  4362. ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
  4363. (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
  4364. )
  4365. {
  4366. return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
  4367. }
  4368. // If I'm paletted, then I'll use the number of bits from the palette
  4369. if ( tga_indexed )
  4370. {
  4371. tga_comp = tga_palette_bits / 8;
  4372. }
  4373. // tga info
  4374. *x = tga_width;
  4375. *y = tga_height;
  4376. if (comp) *comp = tga_comp;
  4377. tga_data = (unsigned char*)stbi__malloc( (size_t)tga_width * tga_height * tga_comp );
  4378. if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
  4379. // skip to the data's starting position (offset usually = 0)
  4380. stbi__skip(s, tga_offset );
  4381. if ( !tga_indexed && !tga_is_RLE) {
  4382. for (i=0; i < tga_height; ++i) {
  4383. int y = tga_inverted ? tga_height -i - 1 : i;
  4384. stbi_uc *tga_row = tga_data + y*tga_width*tga_comp;
  4385. stbi__getn(s, tga_row, tga_width * tga_comp);
  4386. }
  4387. } else {
  4388. // do I need to load a palette?
  4389. if ( tga_indexed)
  4390. {
  4391. // any data to skip? (offset usually = 0)
  4392. stbi__skip(s, tga_palette_start );
  4393. // load the palette
  4394. tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_palette_bits / 8 );
  4395. if (!tga_palette) {
  4396. STBI_FREE(tga_data);
  4397. return stbi__errpuc("outofmem", "Out of memory");
  4398. }
  4399. if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
  4400. STBI_FREE(tga_data);
  4401. STBI_FREE(tga_palette);
  4402. return stbi__errpuc("bad palette", "Corrupt TGA");
  4403. }
  4404. }
  4405. // load the data
  4406. for (i=0; i < tga_width * tga_height; ++i)
  4407. {
  4408. // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
  4409. if ( tga_is_RLE )
  4410. {
  4411. if ( RLE_count == 0 )
  4412. {
  4413. // yep, get the next byte as a RLE command
  4414. int RLE_cmd = stbi__get8(s);
  4415. RLE_count = 1 + (RLE_cmd & 127);
  4416. RLE_repeating = RLE_cmd >> 7;
  4417. read_next_pixel = 1;
  4418. } else if ( !RLE_repeating )
  4419. {
  4420. read_next_pixel = 1;
  4421. }
  4422. } else
  4423. {
  4424. read_next_pixel = 1;
  4425. }
  4426. // OK, if I need to read a pixel, do it now
  4427. if ( read_next_pixel )
  4428. {
  4429. // load however much data we did have
  4430. if ( tga_indexed )
  4431. {
  4432. // read in 1 byte, then perform the lookup
  4433. int pal_idx = stbi__get8(s);
  4434. if ( pal_idx >= tga_palette_len )
  4435. {
  4436. // invalid index
  4437. pal_idx = 0;
  4438. }
  4439. pal_idx *= tga_bits_per_pixel / 8;
  4440. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  4441. {
  4442. raw_data[j] = tga_palette[pal_idx+j];
  4443. }
  4444. } else
  4445. {
  4446. // read in the data raw
  4447. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  4448. {
  4449. raw_data[j] = stbi__get8(s);
  4450. }
  4451. }
  4452. // clear the reading flag for the next pixel
  4453. read_next_pixel = 0;
  4454. } // end of reading a pixel
  4455. // copy data
  4456. for (j = 0; j < tga_comp; ++j)
  4457. tga_data[i*tga_comp+j] = raw_data[j];
  4458. // in case we're in RLE mode, keep counting down
  4459. --RLE_count;
  4460. }
  4461. // do I need to invert the image?
  4462. if ( tga_inverted )
  4463. {
  4464. for (j = 0; j*2 < tga_height; ++j)
  4465. {
  4466. int index1 = j * tga_width * tga_comp;
  4467. int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
  4468. for (i = tga_width * tga_comp; i > 0; --i)
  4469. {
  4470. unsigned char temp = tga_data[index1];
  4471. tga_data[index1] = tga_data[index2];
  4472. tga_data[index2] = temp;
  4473. ++index1;
  4474. ++index2;
  4475. }
  4476. }
  4477. }
  4478. // clear my palette, if I had one
  4479. if ( tga_palette != NULL )
  4480. {
  4481. STBI_FREE( tga_palette );
  4482. }
  4483. }
  4484. // swap RGB
  4485. if (tga_comp >= 3)
  4486. {
  4487. unsigned char* tga_pixel = tga_data;
  4488. for (i=0; i < tga_width * tga_height; ++i)
  4489. {
  4490. unsigned char temp = tga_pixel[0];
  4491. tga_pixel[0] = tga_pixel[2];
  4492. tga_pixel[2] = temp;
  4493. tga_pixel += tga_comp;
  4494. }
  4495. }
  4496. // convert to target component count
  4497. if (req_comp && req_comp != tga_comp)
  4498. tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
  4499. // the things I do to get rid of an error message, and yet keep
  4500. // Microsoft's C compilers happy... [8^(
  4501. tga_palette_start = tga_palette_len = tga_palette_bits =
  4502. tga_x_origin = tga_y_origin = 0;
  4503. // OK, done
  4504. return tga_data;
  4505. }
  4506. #endif
  4507. // *************************************************************************************************
  4508. // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
  4509. #ifndef STBI_NO_PSD
  4510. static int stbi__psd_test(stbi__context *s)
  4511. {
  4512. int r = (stbi__get32be(s) == 0x38425053);
  4513. stbi__rewind(s);
  4514. return r;
  4515. }
  4516. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  4517. {
  4518. int pixelCount;
  4519. int channelCount, compression;
  4520. int channel, i, count, len;
  4521. int w,h;
  4522. stbi_uc *out;
  4523. // Check identifier
  4524. if (stbi__get32be(s) != 0x38425053) // "8BPS"
  4525. return stbi__errpuc("not PSD", "Corrupt PSD image");
  4526. // Check file type version.
  4527. if (stbi__get16be(s) != 1)
  4528. return stbi__errpuc("wrong version", "Unsupported version of PSD image");
  4529. // Skip 6 reserved bytes.
  4530. stbi__skip(s, 6 );
  4531. // Read the number of channels (R, G, B, A, etc).
  4532. channelCount = stbi__get16be(s);
  4533. if (channelCount < 0 || channelCount > 16)
  4534. return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
  4535. // Read the rows and columns of the image.
  4536. h = stbi__get32be(s);
  4537. w = stbi__get32be(s);
  4538. // Make sure the depth is 8 bits.
  4539. if (stbi__get16be(s) != 8)
  4540. return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 bit");
  4541. // Make sure the color mode is RGB.
  4542. // Valid options are:
  4543. // 0: Bitmap
  4544. // 1: Grayscale
  4545. // 2: Indexed color
  4546. // 3: RGB color
  4547. // 4: CMYK color
  4548. // 7: Multichannel
  4549. // 8: Duotone
  4550. // 9: Lab color
  4551. if (stbi__get16be(s) != 3)
  4552. return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
  4553. // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
  4554. stbi__skip(s,stbi__get32be(s) );
  4555. // Skip the image resources. (resolution, pen tool paths, etc)
  4556. stbi__skip(s, stbi__get32be(s) );
  4557. // Skip the reserved data.
  4558. stbi__skip(s, stbi__get32be(s) );
  4559. // Find out if the data is compressed.
  4560. // Known values:
  4561. // 0: no compression
  4562. // 1: RLE compressed
  4563. compression = stbi__get16be(s);
  4564. if (compression > 1)
  4565. return stbi__errpuc("bad compression", "PSD has an unknown compression format");
  4566. // Create the destination image.
  4567. out = (stbi_uc *) stbi__malloc(4 * w*h);
  4568. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  4569. pixelCount = w*h;
  4570. // Initialize the data to zero.
  4571. //memset( out, 0, pixelCount * 4 );
  4572. // Finally, the image data.
  4573. if (compression) {
  4574. // RLE as used by .PSD and .TIFF
  4575. // Loop until you get the number of unpacked bytes you are expecting:
  4576. // Read the next source byte into n.
  4577. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
  4578. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
  4579. // Else if n is 128, noop.
  4580. // Endloop
  4581. // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
  4582. // which we're going to just skip.
  4583. stbi__skip(s, h * channelCount * 2 );
  4584. // Read the RLE data by channel.
  4585. for (channel = 0; channel < 4; channel++) {
  4586. stbi_uc *p;
  4587. p = out+channel;
  4588. if (channel >= channelCount) {
  4589. // Fill this channel with default data.
  4590. for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
  4591. } else {
  4592. // Read the RLE data.
  4593. count = 0;
  4594. while (count < pixelCount) {
  4595. len = stbi__get8(s);
  4596. if (len == 128) {
  4597. // No-op.
  4598. } else if (len < 128) {
  4599. // Copy next len+1 bytes literally.
  4600. len++;
  4601. count += len;
  4602. while (len) {
  4603. *p = stbi__get8(s);
  4604. p += 4;
  4605. len--;
  4606. }
  4607. } else if (len > 128) {
  4608. stbi_uc val;
  4609. // Next -len+1 bytes in the dest are replicated from next source byte.
  4610. // (Interpret len as a negative 8-bit int.)
  4611. len ^= 0x0FF;
  4612. len += 2;
  4613. val = stbi__get8(s);
  4614. count += len;
  4615. while (len) {
  4616. *p = val;
  4617. p += 4;
  4618. len--;
  4619. }
  4620. }
  4621. }
  4622. }
  4623. }
  4624. } else {
  4625. // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
  4626. // where each channel consists of an 8-bit value for each pixel in the image.
  4627. // Read the data by channel.
  4628. for (channel = 0; channel < 4; channel++) {
  4629. stbi_uc *p;
  4630. p = out + channel;
  4631. if (channel > channelCount) {
  4632. // Fill this channel with default data.
  4633. for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
  4634. } else {
  4635. // Read the data.
  4636. for (i = 0; i < pixelCount; i++)
  4637. *p = stbi__get8(s), p += 4;
  4638. }
  4639. }
  4640. }
  4641. if (req_comp && req_comp != 4) {
  4642. out = stbi__convert_format(out, 4, req_comp, w, h);
  4643. if (out == NULL) return out; // stbi__convert_format frees input on failure
  4644. }
  4645. if (comp) *comp = channelCount;
  4646. *y = h;
  4647. *x = w;
  4648. return out;
  4649. }
  4650. #endif
  4651. // *************************************************************************************************
  4652. // Softimage PIC loader
  4653. // by Tom Seddon
  4654. //
  4655. // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
  4656. // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
  4657. #ifndef STBI_NO_PIC
  4658. static int stbi__pic_is4(stbi__context *s,const char *str)
  4659. {
  4660. int i;
  4661. for (i=0; i<4; ++i)
  4662. if (stbi__get8(s) != (stbi_uc)str[i])
  4663. return 0;
  4664. return 1;
  4665. }
  4666. static int stbi__pic_test_core(stbi__context *s)
  4667. {
  4668. int i;
  4669. if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
  4670. return 0;
  4671. for(i=0;i<84;++i)
  4672. stbi__get8(s);
  4673. if (!stbi__pic_is4(s,"PICT"))
  4674. return 0;
  4675. return 1;
  4676. }
  4677. typedef struct
  4678. {
  4679. stbi_uc size,type,channel;
  4680. } stbi__pic_packet;
  4681. static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
  4682. {
  4683. int mask=0x80, i;
  4684. for (i=0; i<4; ++i, mask>>=1) {
  4685. if (channel & mask) {
  4686. if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
  4687. dest[i]=stbi__get8(s);
  4688. }
  4689. }
  4690. return dest;
  4691. }
  4692. static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
  4693. {
  4694. int mask=0x80,i;
  4695. for (i=0;i<4; ++i, mask>>=1)
  4696. if (channel&mask)
  4697. dest[i]=src[i];
  4698. }
  4699. static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
  4700. {
  4701. int act_comp=0,num_packets=0,y,chained;
  4702. stbi__pic_packet packets[10];
  4703. // this will (should...) cater for even some bizarre stuff like having data
  4704. // for the same channel in multiple packets.
  4705. do {
  4706. stbi__pic_packet *packet;
  4707. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  4708. return stbi__errpuc("bad format","too many packets");
  4709. packet = &packets[num_packets++];
  4710. chained = stbi__get8(s);
  4711. packet->size = stbi__get8(s);
  4712. packet->type = stbi__get8(s);
  4713. packet->channel = stbi__get8(s);
  4714. act_comp |= packet->channel;
  4715. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
  4716. if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
  4717. } while (chained);
  4718. *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
  4719. for(y=0; y<height; ++y) {
  4720. int packet_idx;
  4721. for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
  4722. stbi__pic_packet *packet = &packets[packet_idx];
  4723. stbi_uc *dest = result+y*width*4;
  4724. switch (packet->type) {
  4725. default:
  4726. return stbi__errpuc("bad format","packet has bad compression type");
  4727. case 0: {//uncompressed
  4728. int x;
  4729. for(x=0;x<width;++x, dest+=4)
  4730. if (!stbi__readval(s,packet->channel,dest))
  4731. return 0;
  4732. break;
  4733. }
  4734. case 1://Pure RLE
  4735. {
  4736. int left=width, i;
  4737. while (left>0) {
  4738. stbi_uc count,value[4];
  4739. count=stbi__get8(s);
  4740. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
  4741. if (count > left)
  4742. count = (stbi_uc) left;
  4743. if (!stbi__readval(s,packet->channel,value)) return 0;
  4744. for(i=0; i<count; ++i,dest+=4)
  4745. stbi__copyval(packet->channel,dest,value);
  4746. left -= count;
  4747. }
  4748. }
  4749. break;
  4750. case 2: {//Mixed RLE
  4751. int left=width;
  4752. while (left>0) {
  4753. int count = stbi__get8(s), i;
  4754. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
  4755. if (count >= 128) { // Repeated
  4756. stbi_uc value[4];
  4757. int i;
  4758. if (count==128)
  4759. count = stbi__get16be(s);
  4760. else
  4761. count -= 127;
  4762. if (count > left)
  4763. return stbi__errpuc("bad file","scanline overrun");
  4764. if (!stbi__readval(s,packet->channel,value))
  4765. return 0;
  4766. for(i=0;i<count;++i, dest += 4)
  4767. stbi__copyval(packet->channel,dest,value);
  4768. } else { // Raw
  4769. ++count;
  4770. if (count>left) return stbi__errpuc("bad file","scanline overrun");
  4771. for(i=0;i<count;++i, dest+=4)
  4772. if (!stbi__readval(s,packet->channel,dest))
  4773. return 0;
  4774. }
  4775. left-=count;
  4776. }
  4777. break;
  4778. }
  4779. }
  4780. }
  4781. }
  4782. return result;
  4783. }
  4784. static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)
  4785. {
  4786. stbi_uc *result;
  4787. int i, x,y;
  4788. for (i=0; i<92; ++i)
  4789. stbi__get8(s);
  4790. x = stbi__get16be(s);
  4791. y = stbi__get16be(s);
  4792. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
  4793. if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode");
  4794. stbi__get32be(s); //skip `ratio'
  4795. stbi__get16be(s); //skip `fields'
  4796. stbi__get16be(s); //skip `pad'
  4797. // intermediate buffer is RGBA
  4798. result = (stbi_uc *) stbi__malloc(x*y*4);
  4799. memset(result, 0xff, x*y*4);
  4800. if (!stbi__pic_load_core(s,x,y,comp, result)) {
  4801. STBI_FREE(result);
  4802. result=0;
  4803. }
  4804. *px = x;
  4805. *py = y;
  4806. if (req_comp == 0) req_comp = *comp;
  4807. result=stbi__convert_format(result,4,req_comp,x,y);
  4808. return result;
  4809. }
  4810. static int stbi__pic_test(stbi__context *s)
  4811. {
  4812. int r = stbi__pic_test_core(s);
  4813. stbi__rewind(s);
  4814. return r;
  4815. }
  4816. #endif
  4817. // *************************************************************************************************
  4818. // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
  4819. #ifndef STBI_NO_GIF
  4820. typedef struct
  4821. {
  4822. stbi__int16 prefix;
  4823. stbi_uc first;
  4824. stbi_uc suffix;
  4825. } stbi__gif_lzw;
  4826. typedef struct
  4827. {
  4828. int w,h;
  4829. stbi_uc *out; // output buffer (always 4 components)
  4830. int flags, bgindex, ratio, transparent, eflags;
  4831. stbi_uc pal[256][4];
  4832. stbi_uc lpal[256][4];
  4833. stbi__gif_lzw codes[4096];
  4834. stbi_uc *color_table;
  4835. int parse, step;
  4836. int lflags;
  4837. int start_x, start_y;
  4838. int max_x, max_y;
  4839. int cur_x, cur_y;
  4840. int line_size;
  4841. } stbi__gif;
  4842. static int stbi__gif_test_raw(stbi__context *s)
  4843. {
  4844. int sz;
  4845. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
  4846. sz = stbi__get8(s);
  4847. if (sz != '9' && sz != '7') return 0;
  4848. if (stbi__get8(s) != 'a') return 0;
  4849. return 1;
  4850. }
  4851. static int stbi__gif_test(stbi__context *s)
  4852. {
  4853. int r = stbi__gif_test_raw(s);
  4854. stbi__rewind(s);
  4855. return r;
  4856. }
  4857. static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
  4858. {
  4859. int i;
  4860. for (i=0; i < num_entries; ++i) {
  4861. pal[i][2] = stbi__get8(s);
  4862. pal[i][1] = stbi__get8(s);
  4863. pal[i][0] = stbi__get8(s);
  4864. pal[i][3] = transp == i ? 0 : 255;
  4865. }
  4866. }
  4867. static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
  4868. {
  4869. stbi_uc version;
  4870. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
  4871. return stbi__err("not GIF", "Corrupt GIF");
  4872. version = stbi__get8(s);
  4873. if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
  4874. if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
  4875. stbi__g_failure_reason = "";
  4876. g->w = stbi__get16le(s);
  4877. g->h = stbi__get16le(s);
  4878. g->flags = stbi__get8(s);
  4879. g->bgindex = stbi__get8(s);
  4880. g->ratio = stbi__get8(s);
  4881. g->transparent = -1;
  4882. if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
  4883. if (is_info) return 1;
  4884. if (g->flags & 0x80)
  4885. stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
  4886. return 1;
  4887. }
  4888. static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
  4889. {
  4890. stbi__gif g;
  4891. if (!stbi__gif_header(s, &g, comp, 1)) {
  4892. stbi__rewind( s );
  4893. return 0;
  4894. }
  4895. if (x) *x = g.w;
  4896. if (y) *y = g.h;
  4897. return 1;
  4898. }
  4899. static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
  4900. {
  4901. stbi_uc *p, *c;
  4902. // recurse to decode the prefixes, since the linked-list is backwards,
  4903. // and working backwards through an interleaved image would be nasty
  4904. if (g->codes[code].prefix >= 0)
  4905. stbi__out_gif_code(g, g->codes[code].prefix);
  4906. if (g->cur_y >= g->max_y) return;
  4907. p = &g->out[g->cur_x + g->cur_y];
  4908. c = &g->color_table[g->codes[code].suffix * 4];
  4909. if (c[3] >= 128) {
  4910. p[0] = c[2];
  4911. p[1] = c[1];
  4912. p[2] = c[0];
  4913. p[3] = c[3];
  4914. }
  4915. g->cur_x += 4;
  4916. if (g->cur_x >= g->max_x) {
  4917. g->cur_x = g->start_x;
  4918. g->cur_y += g->step;
  4919. while (g->cur_y >= g->max_y && g->parse > 0) {
  4920. g->step = (1 << g->parse) * g->line_size;
  4921. g->cur_y = g->start_y + (g->step >> 1);
  4922. --g->parse;
  4923. }
  4924. }
  4925. }
  4926. static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
  4927. {
  4928. stbi_uc lzw_cs;
  4929. stbi__int32 len, code;
  4930. stbi__uint32 first;
  4931. stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
  4932. stbi__gif_lzw *p;
  4933. lzw_cs = stbi__get8(s);
  4934. if (lzw_cs > 12) return NULL;
  4935. clear = 1 << lzw_cs;
  4936. first = 1;
  4937. codesize = lzw_cs + 1;
  4938. codemask = (1 << codesize) - 1;
  4939. bits = 0;
  4940. valid_bits = 0;
  4941. for (code = 0; code < clear; code++) {
  4942. g->codes[code].prefix = -1;
  4943. g->codes[code].first = (stbi_uc) code;
  4944. g->codes[code].suffix = (stbi_uc) code;
  4945. }
  4946. // support no starting clear code
  4947. avail = clear+2;
  4948. oldcode = -1;
  4949. len = 0;
  4950. for(;;) {
  4951. if (valid_bits < codesize) {
  4952. if (len == 0) {
  4953. len = stbi__get8(s); // start new block
  4954. if (len == 0)
  4955. return g->out;
  4956. }
  4957. --len;
  4958. bits |= (stbi__int32) stbi__get8(s) << valid_bits;
  4959. valid_bits += 8;
  4960. } else {
  4961. stbi__int32 code = bits & codemask;
  4962. bits >>= codesize;
  4963. valid_bits -= codesize;
  4964. // @OPTIMIZE: is there some way we can accelerate the non-clear path?
  4965. if (code == clear) { // clear code
  4966. codesize = lzw_cs + 1;
  4967. codemask = (1 << codesize) - 1;
  4968. avail = clear + 2;
  4969. oldcode = -1;
  4970. first = 0;
  4971. } else if (code == clear + 1) { // end of stream code
  4972. stbi__skip(s, len);
  4973. while ((len = stbi__get8(s)) > 0)
  4974. stbi__skip(s,len);
  4975. return g->out;
  4976. } else if (code <= avail) {
  4977. if (first) return stbi__errpuc("no clear code", "Corrupt GIF");
  4978. if (oldcode >= 0) {
  4979. p = &g->codes[avail++];
  4980. if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF");
  4981. p->prefix = (stbi__int16) oldcode;
  4982. p->first = g->codes[oldcode].first;
  4983. p->suffix = (code == avail) ? p->first : g->codes[code].first;
  4984. } else if (code == avail)
  4985. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  4986. stbi__out_gif_code(g, (stbi__uint16) code);
  4987. if ((avail & codemask) == 0 && avail <= 0x0FFF) {
  4988. codesize++;
  4989. codemask = (1 << codesize) - 1;
  4990. }
  4991. oldcode = code;
  4992. } else {
  4993. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  4994. }
  4995. }
  4996. }
  4997. }
  4998. static void stbi__fill_gif_background(stbi__gif *g)
  4999. {
  5000. int i;
  5001. stbi_uc *c = g->pal[g->bgindex];
  5002. // @OPTIMIZE: write a dword at a time
  5003. for (i = 0; i < g->w * g->h * 4; i += 4) {
  5004. stbi_uc *p = &g->out[i];
  5005. p[0] = c[2];
  5006. p[1] = c[1];
  5007. p[2] = c[0];
  5008. p[3] = c[3];
  5009. }
  5010. }
  5011. // this function is designed to support animated gifs, although stb_image doesn't support it
  5012. static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp)
  5013. {
  5014. int i;
  5015. stbi_uc *old_out = 0;
  5016. if (g->out == 0) {
  5017. if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
  5018. g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);
  5019. if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
  5020. stbi__fill_gif_background(g);
  5021. } else {
  5022. // animated-gif-only path
  5023. if (((g->eflags & 0x1C) >> 2) == 3) {
  5024. old_out = g->out;
  5025. g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);
  5026. if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
  5027. memcpy(g->out, old_out, g->w*g->h*4);
  5028. }
  5029. }
  5030. for (;;) {
  5031. switch (stbi__get8(s)) {
  5032. case 0x2C: /* Image Descriptor */
  5033. {
  5034. stbi__int32 x, y, w, h;
  5035. stbi_uc *o;
  5036. x = stbi__get16le(s);
  5037. y = stbi__get16le(s);
  5038. w = stbi__get16le(s);
  5039. h = stbi__get16le(s);
  5040. if (((x + w) > (g->w)) || ((y + h) > (g->h)))
  5041. return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
  5042. g->line_size = g->w * 4;
  5043. g->start_x = x * 4;
  5044. g->start_y = y * g->line_size;
  5045. g->max_x = g->start_x + w * 4;
  5046. g->max_y = g->start_y + h * g->line_size;
  5047. g->cur_x = g->start_x;
  5048. g->cur_y = g->start_y;
  5049. g->lflags = stbi__get8(s);
  5050. if (g->lflags & 0x40) {
  5051. g->step = 8 * g->line_size; // first interlaced spacing
  5052. g->parse = 3;
  5053. } else {
  5054. g->step = g->line_size;
  5055. g->parse = 0;
  5056. }
  5057. if (g->lflags & 0x80) {
  5058. stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
  5059. g->color_table = (stbi_uc *) g->lpal;
  5060. } else if (g->flags & 0x80) {
  5061. for (i=0; i < 256; ++i) // @OPTIMIZE: stbi__jpeg_reset only the previous transparent
  5062. g->pal[i][3] = 255;
  5063. if (g->transparent >= 0 && (g->eflags & 0x01))
  5064. g->pal[g->transparent][3] = 0;
  5065. g->color_table = (stbi_uc *) g->pal;
  5066. } else
  5067. return stbi__errpuc("missing color table", "Corrupt GIF");
  5068. o = stbi__process_gif_raster(s, g);
  5069. if (o == NULL) return NULL;
  5070. if (req_comp && req_comp != 4)
  5071. o = stbi__convert_format(o, 4, req_comp, g->w, g->h);
  5072. return o;
  5073. }
  5074. case 0x21: // Comment Extension.
  5075. {
  5076. int len;
  5077. if (stbi__get8(s) == 0xF9) { // Graphic Control Extension.
  5078. len = stbi__get8(s);
  5079. if (len == 4) {
  5080. g->eflags = stbi__get8(s);
  5081. stbi__get16le(s); // delay
  5082. g->transparent = stbi__get8(s);
  5083. } else {
  5084. stbi__skip(s, len);
  5085. break;
  5086. }
  5087. }
  5088. while ((len = stbi__get8(s)) != 0)
  5089. stbi__skip(s, len);
  5090. break;
  5091. }
  5092. case 0x3B: // gif stream termination code
  5093. return (stbi_uc *) s; // using '1' causes warning on some compilers
  5094. default:
  5095. return stbi__errpuc("unknown code", "Corrupt GIF");
  5096. }
  5097. }
  5098. }
  5099. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5100. {
  5101. stbi_uc *u = 0;
  5102. stbi__gif g;
  5103. memset(&g, 0, sizeof(g));
  5104. u = stbi__gif_load_next(s, &g, comp, req_comp);
  5105. if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
  5106. if (u) {
  5107. *x = g.w;
  5108. *y = g.h;
  5109. }
  5110. return u;
  5111. }
  5112. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
  5113. {
  5114. return stbi__gif_info_raw(s,x,y,comp);
  5115. }
  5116. #endif
  5117. // *************************************************************************************************
  5118. // Radiance RGBE HDR loader
  5119. // originally by Nicolas Schulz
  5120. #ifndef STBI_NO_HDR
  5121. static int stbi__hdr_test_core(stbi__context *s)
  5122. {
  5123. const char *signature = "#?RADIANCE\n";
  5124. int i;
  5125. for (i=0; signature[i]; ++i)
  5126. if (stbi__get8(s) != signature[i])
  5127. return 0;
  5128. return 1;
  5129. }
  5130. static int stbi__hdr_test(stbi__context* s)
  5131. {
  5132. int r = stbi__hdr_test_core(s);
  5133. stbi__rewind(s);
  5134. return r;
  5135. }
  5136. #define STBI__HDR_BUFLEN 1024
  5137. static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
  5138. {
  5139. int len=0;
  5140. char c = '\0';
  5141. c = (char) stbi__get8(z);
  5142. while (!stbi__at_eof(z) && c != '\n') {
  5143. buffer[len++] = c;
  5144. if (len == STBI__HDR_BUFLEN-1) {
  5145. // flush to end of line
  5146. while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
  5147. ;
  5148. break;
  5149. }
  5150. c = (char) stbi__get8(z);
  5151. }
  5152. buffer[len] = 0;
  5153. return buffer;
  5154. }
  5155. static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
  5156. {
  5157. if ( input[3] != 0 ) {
  5158. float f1;
  5159. // Exponent
  5160. f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
  5161. if (req_comp <= 2)
  5162. output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
  5163. else {
  5164. output[0] = input[0] * f1;
  5165. output[1] = input[1] * f1;
  5166. output[2] = input[2] * f1;
  5167. }
  5168. if (req_comp == 2) output[1] = 1;
  5169. if (req_comp == 4) output[3] = 1;
  5170. } else {
  5171. switch (req_comp) {
  5172. case 4: output[3] = 1; /* fallthrough */
  5173. case 3: output[0] = output[1] = output[2] = 0;
  5174. break;
  5175. case 2: output[1] = 1; /* fallthrough */
  5176. case 1: output[0] = 0;
  5177. break;
  5178. }
  5179. }
  5180. }
  5181. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5182. {
  5183. char buffer[STBI__HDR_BUFLEN];
  5184. char *token;
  5185. int valid = 0;
  5186. int width, height;
  5187. stbi_uc *scanline;
  5188. float *hdr_data;
  5189. int len;
  5190. unsigned char count, value;
  5191. int i, j, k, c1,c2, z;
  5192. // Check identifier
  5193. if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
  5194. return stbi__errpf("not HDR", "Corrupt HDR image");
  5195. // Parse header
  5196. for(;;) {
  5197. token = stbi__hdr_gettoken(s,buffer);
  5198. if (token[0] == 0) break;
  5199. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  5200. }
  5201. if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
  5202. // Parse width and height
  5203. // can't use sscanf() if we're not using stdio!
  5204. token = stbi__hdr_gettoken(s,buffer);
  5205. if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  5206. token += 3;
  5207. height = (int) strtol(token, &token, 10);
  5208. while (*token == ' ') ++token;
  5209. if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  5210. token += 3;
  5211. width = (int) strtol(token, NULL, 10);
  5212. *x = width;
  5213. *y = height;
  5214. if (comp) *comp = 3;
  5215. if (req_comp == 0) req_comp = 3;
  5216. // Read data
  5217. hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float));
  5218. // Load image data
  5219. // image data is stored as some number of sca
  5220. if ( width < 8 || width >= 32768) {
  5221. // Read flat data
  5222. for (j=0; j < height; ++j) {
  5223. for (i=0; i < width; ++i) {
  5224. stbi_uc rgbe[4];
  5225. main_decode_loop:
  5226. stbi__getn(s, rgbe, 4);
  5227. stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
  5228. }
  5229. }
  5230. } else {
  5231. // Read RLE-encoded data
  5232. scanline = NULL;
  5233. for (j = 0; j < height; ++j) {
  5234. c1 = stbi__get8(s);
  5235. c2 = stbi__get8(s);
  5236. len = stbi__get8(s);
  5237. if (c1 != 2 || c2 != 2 || (len & 0x80)) {
  5238. // not run-length encoded, so we have to actually use THIS data as a decoded
  5239. // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
  5240. stbi_uc rgbe[4];
  5241. rgbe[0] = (stbi_uc) c1;
  5242. rgbe[1] = (stbi_uc) c2;
  5243. rgbe[2] = (stbi_uc) len;
  5244. rgbe[3] = (stbi_uc) stbi__get8(s);
  5245. stbi__hdr_convert(hdr_data, rgbe, req_comp);
  5246. i = 1;
  5247. j = 0;
  5248. STBI_FREE(scanline);
  5249. goto main_decode_loop; // yes, this makes no sense
  5250. }
  5251. len <<= 8;
  5252. len |= stbi__get8(s);
  5253. if (len != width) { STBI_FREE(hdr_data); STBI_FREE(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
  5254. if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4);
  5255. for (k = 0; k < 4; ++k) {
  5256. i = 0;
  5257. while (i < width) {
  5258. count = stbi__get8(s);
  5259. if (count > 128) {
  5260. // Run
  5261. value = stbi__get8(s);
  5262. count -= 128;
  5263. for (z = 0; z < count; ++z)
  5264. scanline[i++ * 4 + k] = value;
  5265. } else {
  5266. // Dump
  5267. for (z = 0; z < count; ++z)
  5268. scanline[i++ * 4 + k] = stbi__get8(s);
  5269. }
  5270. }
  5271. }
  5272. for (i=0; i < width; ++i)
  5273. stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
  5274. }
  5275. STBI_FREE(scanline);
  5276. }
  5277. return hdr_data;
  5278. }
  5279. static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
  5280. {
  5281. char buffer[STBI__HDR_BUFLEN];
  5282. char *token;
  5283. int valid = 0;
  5284. if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
  5285. stbi__rewind( s );
  5286. return 0;
  5287. }
  5288. for(;;) {
  5289. token = stbi__hdr_gettoken(s,buffer);
  5290. if (token[0] == 0) break;
  5291. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  5292. }
  5293. if (!valid) {
  5294. stbi__rewind( s );
  5295. return 0;
  5296. }
  5297. token = stbi__hdr_gettoken(s,buffer);
  5298. if (strncmp(token, "-Y ", 3)) {
  5299. stbi__rewind( s );
  5300. return 0;
  5301. }
  5302. token += 3;
  5303. *y = (int) strtol(token, &token, 10);
  5304. while (*token == ' ') ++token;
  5305. if (strncmp(token, "+X ", 3)) {
  5306. stbi__rewind( s );
  5307. return 0;
  5308. }
  5309. token += 3;
  5310. *x = (int) strtol(token, NULL, 10);
  5311. *comp = 3;
  5312. return 1;
  5313. }
  5314. #endif // STBI_NO_HDR
  5315. #ifndef STBI_NO_BMP
  5316. static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
  5317. {
  5318. int hsz;
  5319. if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') {
  5320. stbi__rewind( s );
  5321. return 0;
  5322. }
  5323. stbi__skip(s,12);
  5324. hsz = stbi__get32le(s);
  5325. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) {
  5326. stbi__rewind( s );
  5327. return 0;
  5328. }
  5329. if (hsz == 12) {
  5330. *x = stbi__get16le(s);
  5331. *y = stbi__get16le(s);
  5332. } else {
  5333. *x = stbi__get32le(s);
  5334. *y = stbi__get32le(s);
  5335. }
  5336. if (stbi__get16le(s) != 1) {
  5337. stbi__rewind( s );
  5338. return 0;
  5339. }
  5340. *comp = stbi__get16le(s) / 8;
  5341. return 1;
  5342. }
  5343. #endif
  5344. #ifndef STBI_NO_PSD
  5345. static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
  5346. {
  5347. int channelCount;
  5348. if (stbi__get32be(s) != 0x38425053) {
  5349. stbi__rewind( s );
  5350. return 0;
  5351. }
  5352. if (stbi__get16be(s) != 1) {
  5353. stbi__rewind( s );
  5354. return 0;
  5355. }
  5356. stbi__skip(s, 6);
  5357. channelCount = stbi__get16be(s);
  5358. if (channelCount < 0 || channelCount > 16) {
  5359. stbi__rewind( s );
  5360. return 0;
  5361. }
  5362. *y = stbi__get32be(s);
  5363. *x = stbi__get32be(s);
  5364. if (stbi__get16be(s) != 8) {
  5365. stbi__rewind( s );
  5366. return 0;
  5367. }
  5368. if (stbi__get16be(s) != 3) {
  5369. stbi__rewind( s );
  5370. return 0;
  5371. }
  5372. *comp = 4;
  5373. return 1;
  5374. }
  5375. #endif
  5376. #ifndef STBI_NO_PIC
  5377. static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
  5378. {
  5379. int act_comp=0,num_packets=0,chained;
  5380. stbi__pic_packet packets[10];
  5381. stbi__skip(s, 92);
  5382. *x = stbi__get16be(s);
  5383. *y = stbi__get16be(s);
  5384. if (stbi__at_eof(s)) return 0;
  5385. if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
  5386. stbi__rewind( s );
  5387. return 0;
  5388. }
  5389. stbi__skip(s, 8);
  5390. do {
  5391. stbi__pic_packet *packet;
  5392. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  5393. return 0;
  5394. packet = &packets[num_packets++];
  5395. chained = stbi__get8(s);
  5396. packet->size = stbi__get8(s);
  5397. packet->type = stbi__get8(s);
  5398. packet->channel = stbi__get8(s);
  5399. act_comp |= packet->channel;
  5400. if (stbi__at_eof(s)) {
  5401. stbi__rewind( s );
  5402. return 0;
  5403. }
  5404. if (packet->size != 8) {
  5405. stbi__rewind( s );
  5406. return 0;
  5407. }
  5408. } while (chained);
  5409. *comp = (act_comp & 0x10 ? 4 : 3);
  5410. return 1;
  5411. }
  5412. #endif
  5413. // *************************************************************************************************
  5414. // Portable Gray Map and Portable Pixel Map loader
  5415. // by Ken Miller
  5416. //
  5417. // PGM: http://netpbm.sourceforge.net/doc/pgm.html
  5418. // PPM: http://netpbm.sourceforge.net/doc/ppm.html
  5419. //
  5420. // Known limitations:
  5421. // Does not support comments in the header section
  5422. // Does not support ASCII image data (formats P2 and P3)
  5423. // Does not support 16-bit-per-channel
  5424. #ifndef STBI_NO_PNM
  5425. static int stbi__pnm_test(stbi__context *s)
  5426. {
  5427. char p, t;
  5428. p = (char) stbi__get8(s);
  5429. t = (char) stbi__get8(s);
  5430. if (p != 'P' || (t != '5' && t != '6')) {
  5431. stbi__rewind( s );
  5432. return 0;
  5433. }
  5434. return 1;
  5435. }
  5436. static stbi_uc *stbi__pnm_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  5437. {
  5438. stbi_uc *out;
  5439. if (!stbi__pnm_info(s, (int *)&s->img_x, (int *)&s->img_y, (int *)&s->img_n))
  5440. return 0;
  5441. *x = s->img_x;
  5442. *y = s->img_y;
  5443. *comp = s->img_n;
  5444. out = (stbi_uc *) stbi__malloc(s->img_n * s->img_x * s->img_y);
  5445. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  5446. stbi__getn(s, out, s->img_n * s->img_x * s->img_y);
  5447. if (req_comp && req_comp != s->img_n) {
  5448. out = stbi__convert_format(out, s->img_n, req_comp, s->img_x, s->img_y);
  5449. if (out == NULL) return out; // stbi__convert_format frees input on failure
  5450. }
  5451. return out;
  5452. }
  5453. static int stbi__pnm_isspace(char c)
  5454. {
  5455. return c == ' ' || c == '\t' || c == '\n' || c == '\v' || c == '\f' || c == '\r';
  5456. }
  5457. static void stbi__pnm_skip_whitespace(stbi__context *s, char *c)
  5458. {
  5459. while (!stbi__at_eof(s) && stbi__pnm_isspace(*c))
  5460. *c = (char) stbi__get8(s);
  5461. }
  5462. static int stbi__pnm_isdigit(char c)
  5463. {
  5464. return c >= '0' && c <= '9';
  5465. }
  5466. static int stbi__pnm_getinteger(stbi__context *s, char *c)
  5467. {
  5468. int value = 0;
  5469. while (!stbi__at_eof(s) && stbi__pnm_isdigit(*c)) {
  5470. value = value*10 + (*c - '0');
  5471. *c = (char) stbi__get8(s);
  5472. }
  5473. return value;
  5474. }
  5475. static int stbi__pnm_info(stbi__context *s, int *x, int *y, int *comp)
  5476. {
  5477. int maxv;
  5478. char c, p, t;
  5479. stbi__rewind( s );
  5480. // Get identifier
  5481. p = (char) stbi__get8(s);
  5482. t = (char) stbi__get8(s);
  5483. if (p != 'P' || (t != '5' && t != '6')) {
  5484. stbi__rewind( s );
  5485. return 0;
  5486. }
  5487. *comp = (t == '6') ? 3 : 1; // '5' is 1-component .pgm; '6' is 3-component .ppm
  5488. c = (char) stbi__get8(s);
  5489. stbi__pnm_skip_whitespace(s, &c);
  5490. *x = stbi__pnm_getinteger(s, &c); // read width
  5491. stbi__pnm_skip_whitespace(s, &c);
  5492. *y = stbi__pnm_getinteger(s, &c); // read height
  5493. stbi__pnm_skip_whitespace(s, &c);
  5494. maxv = stbi__pnm_getinteger(s, &c); // read max value
  5495. if (maxv > 255)
  5496. return stbi__err("max value > 255", "PPM image not 8-bit");
  5497. else
  5498. return 1;
  5499. }
  5500. #endif
  5501. static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
  5502. {
  5503. #ifndef STBI_NO_JPEG
  5504. if (stbi__jpeg_info(s, x, y, comp)) return 1;
  5505. #endif
  5506. #ifndef STBI_NO_PNG
  5507. if (stbi__png_info(s, x, y, comp)) return 1;
  5508. #endif
  5509. #ifndef STBI_NO_GIF
  5510. if (stbi__gif_info(s, x, y, comp)) return 1;
  5511. #endif
  5512. #ifndef STBI_NO_BMP
  5513. if (stbi__bmp_info(s, x, y, comp)) return 1;
  5514. #endif
  5515. #ifndef STBI_NO_PSD
  5516. if (stbi__psd_info(s, x, y, comp)) return 1;
  5517. #endif
  5518. #ifndef STBI_NO_PIC
  5519. if (stbi__pic_info(s, x, y, comp)) return 1;
  5520. #endif
  5521. #ifndef STBI_NO_PNM
  5522. if (stbi__pnm_info(s, x, y, comp)) return 1;
  5523. #endif
  5524. #ifndef STBI_NO_HDR
  5525. if (stbi__hdr_info(s, x, y, comp)) return 1;
  5526. #endif
  5527. // test tga last because it's a crappy test!
  5528. #ifndef STBI_NO_TGA
  5529. if (stbi__tga_info(s, x, y, comp))
  5530. return 1;
  5531. #endif
  5532. return stbi__err("unknown image type", "Image not of any known type, or corrupt");
  5533. }
  5534. #ifndef STBI_NO_STDIO
  5535. STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
  5536. {
  5537. FILE *f = stbi__fopen(filename, "rb");
  5538. int result;
  5539. if (!f) return stbi__err("can't fopen", "Unable to open file");
  5540. result = stbi_info_from_file(f, x, y, comp);
  5541. fclose(f);
  5542. return result;
  5543. }
  5544. STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
  5545. {
  5546. int r;
  5547. stbi__context s;
  5548. long pos = ftell(f);
  5549. stbi__start_file(&s, f);
  5550. r = stbi__info_main(&s,x,y,comp);
  5551. fseek(f,pos,SEEK_SET);
  5552. return r;
  5553. }
  5554. #endif // !STBI_NO_STDIO
  5555. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
  5556. {
  5557. stbi__context s;
  5558. stbi__start_mem(&s,buffer,len);
  5559. return stbi__info_main(&s,x,y,comp);
  5560. }
  5561. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
  5562. {
  5563. stbi__context s;
  5564. stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
  5565. return stbi__info_main(&s,x,y,comp);
  5566. }
  5567. #endif // STB_IMAGE_IMPLEMENTATION
  5568. /*
  5569. revision history:
  5570. 2.05 (2015-04-19) fix bug in progressive JPEG handling, fix warning
  5571. 2.04 (2015-04-15) try to re-enable SIMD on MinGW 64-bit
  5572. 2.03 (2015-04-12) extra corruption checking (mmozeiko)
  5573. stbi_set_flip_vertically_on_load (nguillemot)
  5574. fix NEON support; fix mingw support
  5575. 2.02 (2015-01-19) fix incorrect assert, fix warning
  5576. 2.01 (2015-01-17) fix various warnings; suppress SIMD on gcc 32-bit without -msse2
  5577. 2.00b (2014-12-25) fix STBI_MALLOC in progressive JPEG
  5578. 2.00 (2014-12-25) optimize JPG, including x86 SSE2 & NEON SIMD (ryg)
  5579. progressive JPEG (stb)
  5580. PGM/PPM support (Ken Miller)
  5581. STBI_MALLOC,STBI_REALLOC,STBI_FREE
  5582. GIF bugfix -- seemingly never worked
  5583. STBI_NO_*, STBI_ONLY_*
  5584. 1.48 (2014-12-14) fix incorrectly-named assert()
  5585. 1.47 (2014-12-14) 1/2/4-bit PNG support, both direct and paletted (Omar Cornut & stb)
  5586. optimize PNG (ryg)
  5587. fix bug in interlaced PNG with user-specified channel count (stb)
  5588. 1.46 (2014-08-26)
  5589. fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
  5590. 1.45 (2014-08-16)
  5591. fix MSVC-ARM internal compiler error by wrapping malloc
  5592. 1.44 (2014-08-07)
  5593. various warning fixes from Ronny Chevalier
  5594. 1.43 (2014-07-15)
  5595. fix MSVC-only compiler problem in code changed in 1.42
  5596. 1.42 (2014-07-09)
  5597. don't define _CRT_SECURE_NO_WARNINGS (affects user code)
  5598. fixes to stbi__cleanup_jpeg path
  5599. added STBI_ASSERT to avoid requiring assert.h
  5600. 1.41 (2014-06-25)
  5601. fix search&replace from 1.36 that messed up comments/error messages
  5602. 1.40 (2014-06-22)
  5603. fix gcc struct-initialization warning
  5604. 1.39 (2014-06-15)
  5605. fix to TGA optimization when req_comp != number of components in TGA;
  5606. fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
  5607. add support for BMP version 5 (more ignored fields)
  5608. 1.38 (2014-06-06)
  5609. suppress MSVC warnings on integer casts truncating values
  5610. fix accidental rename of 'skip' field of I/O
  5611. 1.37 (2014-06-04)
  5612. remove duplicate typedef
  5613. 1.36 (2014-06-03)
  5614. convert to header file single-file library
  5615. if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
  5616. 1.35 (2014-05-27)
  5617. various warnings
  5618. fix broken STBI_SIMD path
  5619. fix bug where stbi_load_from_file no longer left file pointer in correct place
  5620. fix broken non-easy path for 32-bit BMP (possibly never used)
  5621. TGA optimization by Arseny Kapoulkine
  5622. 1.34 (unknown)
  5623. use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
  5624. 1.33 (2011-07-14)
  5625. make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
  5626. 1.32 (2011-07-13)
  5627. support for "info" function for all supported filetypes (SpartanJ)
  5628. 1.31 (2011-06-20)
  5629. a few more leak fixes, bug in PNG handling (SpartanJ)
  5630. 1.30 (2011-06-11)
  5631. added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
  5632. removed deprecated format-specific test/load functions
  5633. removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
  5634. error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
  5635. fix inefficiency in decoding 32-bit BMP (David Woo)
  5636. 1.29 (2010-08-16)
  5637. various warning fixes from Aurelien Pocheville
  5638. 1.28 (2010-08-01)
  5639. fix bug in GIF palette transparency (SpartanJ)
  5640. 1.27 (2010-08-01)
  5641. cast-to-stbi_uc to fix warnings
  5642. 1.26 (2010-07-24)
  5643. fix bug in file buffering for PNG reported by SpartanJ
  5644. 1.25 (2010-07-17)
  5645. refix trans_data warning (Won Chun)
  5646. 1.24 (2010-07-12)
  5647. perf improvements reading from files on platforms with lock-heavy fgetc()
  5648. minor perf improvements for jpeg
  5649. deprecated type-specific functions so we'll get feedback if they're needed
  5650. attempt to fix trans_data warning (Won Chun)
  5651. 1.23 fixed bug in iPhone support
  5652. 1.22 (2010-07-10)
  5653. removed image *writing* support
  5654. stbi_info support from Jetro Lauha
  5655. GIF support from Jean-Marc Lienher
  5656. iPhone PNG-extensions from James Brown
  5657. warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
  5658. 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
  5659. 1.20 added support for Softimage PIC, by Tom Seddon
  5660. 1.19 bug in interlaced PNG corruption check (found by ryg)
  5661. 1.18 (2008-08-02)
  5662. fix a threading bug (local mutable static)
  5663. 1.17 support interlaced PNG
  5664. 1.16 major bugfix - stbi__convert_format converted one too many pixels
  5665. 1.15 initialize some fields for thread safety
  5666. 1.14 fix threadsafe conversion bug
  5667. header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
  5668. 1.13 threadsafe
  5669. 1.12 const qualifiers in the API
  5670. 1.11 Support installable IDCT, colorspace conversion routines
  5671. 1.10 Fixes for 64-bit (don't use "unsigned long")
  5672. optimized upsampling by Fabian "ryg" Giesen
  5673. 1.09 Fix format-conversion for PSD code (bad global variables!)
  5674. 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
  5675. 1.07 attempt to fix C++ warning/errors again
  5676. 1.06 attempt to fix C++ warning/errors again
  5677. 1.05 fix TGA loading to return correct *comp and use good luminance calc
  5678. 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
  5679. 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
  5680. 1.02 support for (subset of) HDR files, float interface for preferred access to them
  5681. 1.01 fix bug: possible bug in handling right-side up bmps... not sure
  5682. fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
  5683. 1.00 interface to zlib that skips zlib header
  5684. 0.99 correct handling of alpha in palette
  5685. 0.98 TGA loader by lonesock; dynamically add loaders (untested)
  5686. 0.97 jpeg errors on too large a file; also catch another malloc failure
  5687. 0.96 fix detection of invalid v value - particleman@mollyrocket forum
  5688. 0.95 during header scan, seek to markers in case of padding
  5689. 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
  5690. 0.93 handle jpegtran output; verbose errors
  5691. 0.92 read 4,8,16,24,32-bit BMP files of several formats
  5692. 0.91 output 24-bit Windows 3.0 BMP files
  5693. 0.90 fix a few more warnings; bump version number to approach 1.0
  5694. 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
  5695. 0.60 fix compiling as c++
  5696. 0.59 fix warnings: merge Dave Moore's -Wall fixes
  5697. 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
  5698. 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
  5699. 0.56 fix bug: zlib uncompressed mode len vs. nlen
  5700. 0.55 fix bug: restart_interval not initialized to 0
  5701. 0.54 allow NULL for 'int *comp'
  5702. 0.53 fix bug in png 3->4; speedup png decoding
  5703. 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
  5704. 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
  5705. on 'test' only check type, not whether we support this variant
  5706. 0.50 (2006-11-19)
  5707. first released version
  5708. */