stb_image.c 221 KB

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