Open Source Tomb Raider Engine
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

stb_image.h 210KB

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