stb_image.h 218 KB

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