stb_image.h 257 KB

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