stb_image.c 203 KB

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