stb_image.h 285 KB

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