stb_image.h 266 KB

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