stb_image.cpp 221 KB

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