You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stb_image.h 222KB

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