stb_image.cpp 260 KB

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