stb_image.c 215 KB

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