stb_image.h 257 KB

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