stb_image.h 244 KB

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