stb_image.h 276 KB

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