stb_image.h 315 KB

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