stb_image.h 156 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744
  1. /* stb_image - v1.46 - public domain JPEG/PNG reader - http://nothings.org/stb_image.c
  2. when you control the images you're loading
  3. no warranty implied; use at your own risk
  4. Do this:
  5. #define STB_IMAGE_IMPLEMENTATION
  6. before you include this file in *one* C or C++ file to create the implementation.
  7. #define STBI_ASSERT(x) to avoid using assert.h.
  8. QUICK NOTES:
  9. Primarily of interest to game developers and other people who can
  10. avoid problematic images and only need the trivial interface
  11. JPEG baseline (no JPEG progressive)
  12. PNG 1/2/4/8-bit-per-channel (16 bpc not supported)
  13. TGA (not sure what subset, if a subset)
  14. BMP non-1bpp, non-RLE
  15. PSD (composited view only, no extra channels)
  16. GIF (*comp always reports as 4-channel)
  17. HDR (radiance rgbE format)
  18. PIC (Softimage PIC)
  19. - decode from memory or through FILE (define STBI_NO_STDIO to remove code)
  20. - decode from arbitrary I/O callbacks
  21. - overridable dequantizing-IDCT, YCbCr-to-RGB conversion (define STBI_SIMD)
  22. Latest revisions:
  23. 1.xx (2014-09-26) 1/2/4-bit PNG support (both grayscale and paletted)
  24. 1.46 (2014-08-26) fix broken tRNS chunk in non-paletted PNG
  25. 1.45 (2014-08-16) workaround MSVC-ARM internal compiler error by wrapping malloc
  26. 1.44 (2014-08-07) warnings
  27. 1.43 (2014-07-15) fix MSVC-only bug in 1.42
  28. 1.42 (2014-07-09) no _CRT_SECURE_NO_WARNINGS; error-path fixes; STBI_ASSERT
  29. 1.41 (2014-06-25) fix search&replace that messed up comments/error messages
  30. 1.40 (2014-06-22) gcc warning
  31. 1.39 (2014-06-15) TGA optimization bugfix, multiple BMP fixes
  32. 1.38 (2014-06-06) suppress MSVC run-time warnings, fix accidental rename of 'skip'
  33. 1.37 (2014-06-04) remove duplicate typedef
  34. 1.36 (2014-06-03) converted to header file, allow reading incorrect iphoned-images without iphone flag
  35. 1.35 (2014-05-27) warnings, bugfixes, TGA optimization, etc
  36. See end of file for full revision history.
  37. TODO:
  38. stbi_info support for BMP,PSD,HDR,PIC
  39. ============================ Contributors =========================
  40. Image formats Bug fixes & warning fixes
  41. Sean Barrett (jpeg, png, bmp) Marc LeBlanc
  42. Nicolas Schulz (hdr, psd) Christpher Lloyd
  43. Jonathan Dummer (tga) Dave Moore
  44. Jean-Marc Lienher (gif) Won Chun
  45. Tom Seddon (pic) the Horde3D community
  46. Thatcher Ulrich (psd) Janez Zemva
  47. Jonathan Blow
  48. Laurent Gomila
  49. Extensions, features Aruelien Pocheville
  50. Jetro Lauha (stbi_info) Ryamond Barbiero
  51. James "moose2000" Brown (iPhone PNG) David Woo
  52. Ben "Disch" Wenger (io callbacks) Roy Eltham
  53. Martin "SpartanJ" Golini Luke Graham
  54. Omar Cornut (1/2/4-bit png) Thomas Ruf
  55. John Bartholomew
  56. Optimizations & bugfixes Ken Hamada
  57. Fabian "ryg" Giesen Cort Stratton
  58. Arseny Kapoulkine Blazej Dariusz Roszkowski
  59. Thibault Reuille
  60. Paul Du Bois
  61. Guillaume George
  62. Jerry Jansson
  63. If your name should be here but Hayaki Saito
  64. isn't, let Sean know. Johan Duparc
  65. Ronny Chevalier
  66. Michal Cichon
  67. */
  68. #ifndef STBI_INCLUDE_STB_IMAGE_H
  69. #define STBI_INCLUDE_STB_IMAGE_H
  70. // Limitations:
  71. // - no jpeg progressive support
  72. // - non-HDR formats support 8-bit samples only (jpeg, png)
  73. // - no delayed line count (jpeg) -- IJG doesn't support either
  74. // - no 1-bit BMP
  75. // - GIF always returns *comp=4
  76. //
  77. // Basic usage (see HDR discussion below):
  78. // int x,y,n;
  79. // unsigned char *data = stbi_load(filename, &x, &y, &n, 0);
  80. // // ... process data if not NULL ...
  81. // // ... x = width, y = height, n = # 8-bit components per pixel ...
  82. // // ... replace '0' with '1'..'4' to force that many components per pixel
  83. // // ... but 'n' will always be the number that it would have been if you said 0
  84. // stbi_image_free(data)
  85. //
  86. // Standard parameters:
  87. // int *x -- outputs image width in pixels
  88. // int *y -- outputs image height in pixels
  89. // int *comp -- outputs # of image components in image file
  90. // int req_comp -- if non-zero, # of image components requested in result
  91. //
  92. // The return value from an image loader is an 'unsigned char *' which points
  93. // to the pixel data. The pixel data consists of *y scanlines of *x pixels,
  94. // with each pixel consisting of N interleaved 8-bit components; the first
  95. // pixel pointed to is top-left-most in the image. There is no padding between
  96. // image scanlines or between pixels, regardless of format. The number of
  97. // components N is 'req_comp' if req_comp is non-zero, or *comp otherwise.
  98. // If req_comp is non-zero, *comp has the number of components that _would_
  99. // have been output otherwise. E.g. if you set req_comp to 4, you will always
  100. // get RGBA output, but you can check *comp to easily see if it's opaque.
  101. //
  102. // An output image with N components has the following components interleaved
  103. // in this order in each pixel:
  104. //
  105. // N=#comp components
  106. // 1 grey
  107. // 2 grey, alpha
  108. // 3 red, green, blue
  109. // 4 red, green, blue, alpha
  110. //
  111. // If image loading fails for any reason, the return value will be NULL,
  112. // and *x, *y, *comp will be unchanged. The function stbi_failure_reason()
  113. // can be queried for an extremely brief, end-user unfriendly explanation
  114. // of why the load failed. Define STBI_NO_FAILURE_STRINGS to avoid
  115. // compiling these strings at all, and STBI_FAILURE_USERMSG to get slightly
  116. // more user-friendly ones.
  117. //
  118. // Paletted PNG, BMP, GIF, and PIC images are automatically depalettized.
  119. //
  120. // ===========================================================================
  121. //
  122. // iPhone PNG support:
  123. //
  124. // By default we convert iphone-formatted PNGs back to RGB; nominally they
  125. // would silently load as BGR, except the existing code should have just
  126. // failed on such iPhone PNGs. But you can disable this conversion by
  127. // by calling stbi_convert_iphone_png_to_rgb(0), in which case
  128. // you will always just get the native iphone "format" through.
  129. //
  130. // Call stbi_set_unpremultiply_on_load(1) as well to force a divide per
  131. // pixel to remove any premultiplied alpha *only* if the image file explicitly
  132. // says there's premultiplied data (currently only happens in iPhone images,
  133. // and only if iPhone convert-to-rgb processing is on).
  134. //
  135. // ===========================================================================
  136. //
  137. // HDR image support (disable by defining STBI_NO_HDR)
  138. //
  139. // stb_image now supports loading HDR images in general, and currently
  140. // the Radiance .HDR file format, although the support is provided
  141. // generically. You can still load any file through the existing interface;
  142. // if you attempt to load an HDR file, it will be automatically remapped to
  143. // LDR, assuming gamma 2.2 and an arbitrary scale factor defaulting to 1;
  144. // both of these constants can be reconfigured through this interface:
  145. //
  146. // stbi_hdr_to_ldr_gamma(2.2f);
  147. // stbi_hdr_to_ldr_scale(1.0f);
  148. //
  149. // (note, do not use _inverse_ constants; stbi_image will invert them
  150. // appropriately).
  151. //
  152. // Additionally, there is a new, parallel interface for loading files as
  153. // (linear) floats to preserve the full dynamic range:
  154. //
  155. // float *data = stbi_loadf(filename, &x, &y, &n, 0);
  156. //
  157. // If you load LDR images through this interface, those images will
  158. // be promoted to floating point values, run through the inverse of
  159. // constants corresponding to the above:
  160. //
  161. // stbi_ldr_to_hdr_scale(1.0f);
  162. // stbi_ldr_to_hdr_gamma(2.2f);
  163. //
  164. // Finally, given a filename (or an open file or memory block--see header
  165. // file for details) containing image data, you can query for the "most
  166. // appropriate" interface to use (that is, whether the image is HDR or
  167. // not), using:
  168. //
  169. // stbi_is_hdr(char *filename);
  170. //
  171. // ===========================================================================
  172. //
  173. // I/O callbacks
  174. //
  175. // I/O callbacks allow you to read from arbitrary sources, like packaged
  176. // files or some other source. Data read from callbacks are processed
  177. // through a small internal buffer (currently 128 bytes) to try to reduce
  178. // overhead.
  179. //
  180. // The three functions you must define are "read" (reads some bytes of data),
  181. // "skip" (skips some bytes of data), "eof" (reports if the stream is at the end).
  182. #ifndef STBI_NO_STDIO
  183. #include <stdio.h>
  184. #endif // STBI_NO_STDIO
  185. #define STBI_VERSION 1
  186. enum
  187. {
  188. STBI_default = 0, // only used for req_comp
  189. STBI_grey = 1,
  190. STBI_grey_alpha = 2,
  191. STBI_rgb = 3,
  192. STBI_rgb_alpha = 4
  193. };
  194. typedef unsigned char stbi_uc;
  195. #ifdef __cplusplus
  196. extern "C" {
  197. #endif
  198. #ifdef STB_IMAGE_STATIC
  199. #define STBIDEF static
  200. #else
  201. #define STBIDEF extern
  202. #endif
  203. //////////////////////////////////////////////////////////////////////////////
  204. //
  205. // PRIMARY API - works on images of any type
  206. //
  207. //
  208. // load image by filename, open file, or memory buffer
  209. //
  210. STBIDEF stbi_uc *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  211. #ifndef STBI_NO_STDIO
  212. STBIDEF stbi_uc *stbi_load (char const *filename, int *x, int *y, int *comp, int req_comp);
  213. STBIDEF stbi_uc *stbi_load_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  214. // for stbi_load_from_file, file pointer is left pointing immediately after image
  215. #endif
  216. typedef struct
  217. {
  218. int (*read) (void *user,char *data,int size); // fill 'data' with 'size' bytes. return number of bytes actually read
  219. void (*skip) (void *user,int n); // skip the next 'n' bytes, or 'unget' the last -n bytes if negative
  220. int (*eof) (void *user); // returns nonzero if we are at end of file/data
  221. } stbi_io_callbacks;
  222. STBIDEF stbi_uc *stbi_load_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  223. #ifndef STBI_NO_HDR
  224. STBIDEF float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp);
  225. #ifndef STBI_NO_STDIO
  226. STBIDEF float *stbi_loadf (char const *filename, int *x, int *y, int *comp, int req_comp);
  227. STBIDEF float *stbi_loadf_from_file (FILE *f, int *x, int *y, int *comp, int req_comp);
  228. #endif
  229. STBIDEF float *stbi_loadf_from_callbacks (stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp);
  230. STBIDEF void stbi_hdr_to_ldr_gamma(float gamma);
  231. STBIDEF void stbi_hdr_to_ldr_scale(float scale);
  232. STBIDEF void stbi_ldr_to_hdr_gamma(float gamma);
  233. STBIDEF void stbi_ldr_to_hdr_scale(float scale);
  234. #endif // STBI_NO_HDR
  235. // stbi_is_hdr is always defined
  236. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user);
  237. STBIDEF int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len);
  238. #ifndef STBI_NO_STDIO
  239. STBIDEF int stbi_is_hdr (char const *filename);
  240. STBIDEF int stbi_is_hdr_from_file(FILE *f);
  241. #endif // STBI_NO_STDIO
  242. // get a VERY brief reason for failure
  243. // NOT THREADSAFE
  244. STBIDEF const char *stbi_failure_reason (void);
  245. // free the loaded image -- this is just free()
  246. STBIDEF void stbi_image_free (void *retval_from_stbi_load);
  247. // get image dimensions & components without fully decoding
  248. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp);
  249. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp);
  250. #ifndef STBI_NO_STDIO
  251. STBIDEF int stbi_info (char const *filename, int *x, int *y, int *comp);
  252. STBIDEF int stbi_info_from_file (FILE *f, int *x, int *y, int *comp);
  253. #endif
  254. // for image formats that explicitly notate that they have premultiplied alpha,
  255. // we just return the colors as stored in the file. set this flag to force
  256. // unpremultiplication. results are undefined if the unpremultiply overflow.
  257. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply);
  258. // indicate whether we should process iphone images back to canonical format,
  259. // or just pass them through "as-is"
  260. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert);
  261. // ZLIB client - used by PNG, available for other purposes
  262. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen);
  263. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header);
  264. STBIDEF char *stbi_zlib_decode_malloc(const char *buffer, int len, int *outlen);
  265. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  266. STBIDEF char *stbi_zlib_decode_noheader_malloc(const char *buffer, int len, int *outlen);
  267. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen);
  268. // define faster low-level operations (typically SIMD support)
  269. #ifdef STBI_SIMD
  270. typedef void (*stbi_idct_8x8)(stbi_uc *out, int out_stride, short data[64], unsigned short *dequantize);
  271. // compute an integer IDCT on "input"
  272. // input[x] = data[x] * dequantize[x]
  273. // write results to 'out': 64 samples, each run of 8 spaced by 'out_stride'
  274. // CLAMP results to 0..255
  275. typedef void (*stbi_YCbCr_to_RGB_run)(stbi_uc *output, stbi_uc const *y, stbi_uc const *cb, stbi_uc const *cr, int count, int step);
  276. // compute a conversion from YCbCr to RGB
  277. // 'count' pixels
  278. // write pixels to 'output'; each pixel is 'step' bytes (either 3 or 4; if 4, write '255' as 4th), order R,G,B
  279. // y: Y input channel
  280. // cb: Cb input channel; scale/biased to be 0..255
  281. // cr: Cr input channel; scale/biased to be 0..255
  282. STBIDEF void stbi_install_idct(stbi_idct_8x8 func);
  283. STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func);
  284. #endif // STBI_SIMD
  285. #ifdef __cplusplus
  286. }
  287. #endif
  288. //
  289. //
  290. //// end header file /////////////////////////////////////////////////////
  291. #endif // STBI_INCLUDE_STB_IMAGE_H
  292. #ifdef STB_IMAGE_IMPLEMENTATION
  293. #ifndef STBI_NO_HDR
  294. #include <math.h> // ldexp
  295. #include <string.h> // strcmp, strtok
  296. #endif
  297. #ifndef STBI_NO_STDIO
  298. #include <stdio.h>
  299. #endif
  300. #include <stdlib.h>
  301. #include <string.h>
  302. #ifndef STBI_ASSERT
  303. #include <assert.h>
  304. #define STBI_ASSERT(x) assert(x)
  305. #endif
  306. #include <stdarg.h>
  307. #include <stddef.h> // ptrdiff_t on osx
  308. #ifndef _MSC_VER
  309. #ifdef __cplusplus
  310. #define stbi_inline inline
  311. #else
  312. #define stbi_inline
  313. #endif
  314. #else
  315. #define stbi_inline __forceinline
  316. #endif
  317. #ifdef _MSC_VER
  318. typedef unsigned short stbi__uint16;
  319. typedef signed short stbi__int16;
  320. typedef unsigned int stbi__uint32;
  321. typedef signed int stbi__int32;
  322. #else
  323. #include <stdint.h>
  324. typedef uint16_t stbi__uint16;
  325. typedef int16_t stbi__int16;
  326. typedef uint32_t stbi__uint32;
  327. typedef int32_t stbi__int32;
  328. #endif
  329. // should produce compiler error if size is wrong
  330. typedef unsigned char validate_uint32[sizeof(stbi__uint32)==4 ? 1 : -1];
  331. #ifdef _MSC_VER
  332. #define STBI_NOTUSED(v) (void)(v)
  333. #else
  334. #define STBI_NOTUSED(v) (void)sizeof(v)
  335. #endif
  336. #ifdef _MSC_VER
  337. #define STBI_HAS_LROTL
  338. #endif
  339. #ifdef STBI_HAS_LROTL
  340. #define stbi_lrot(x,y) _lrotl(x,y)
  341. #else
  342. #define stbi_lrot(x,y) (((x) << (y)) | ((x) >> (32 - (y))))
  343. #endif
  344. ///////////////////////////////////////////////
  345. //
  346. // stbi__context struct and start_xxx functions
  347. // stbi__context structure is our basic context used by all images, so it
  348. // contains all the IO context, plus some basic image information
  349. typedef struct
  350. {
  351. stbi__uint32 img_x, img_y;
  352. int img_n, img_out_n;
  353. stbi_io_callbacks io;
  354. void *io_user_data;
  355. int read_from_callbacks;
  356. int buflen;
  357. stbi_uc buffer_start[128];
  358. stbi_uc *img_buffer, *img_buffer_end;
  359. stbi_uc *img_buffer_original;
  360. } stbi__context;
  361. static void stbi__refill_buffer(stbi__context *s);
  362. // initialize a memory-decode context
  363. static void stbi__start_mem(stbi__context *s, stbi_uc const *buffer, int len)
  364. {
  365. s->io.read = NULL;
  366. s->read_from_callbacks = 0;
  367. s->img_buffer = s->img_buffer_original = (stbi_uc *) buffer;
  368. s->img_buffer_end = (stbi_uc *) buffer+len;
  369. }
  370. // initialize a callback-based context
  371. static void stbi__start_callbacks(stbi__context *s, stbi_io_callbacks *c, void *user)
  372. {
  373. s->io = *c;
  374. s->io_user_data = user;
  375. s->buflen = sizeof(s->buffer_start);
  376. s->read_from_callbacks = 1;
  377. s->img_buffer_original = s->buffer_start;
  378. stbi__refill_buffer(s);
  379. }
  380. #ifndef STBI_NO_STDIO
  381. static int stbi__stdio_read(void *user, char *data, int size)
  382. {
  383. return (int) fread(data,1,size,(FILE*) user);
  384. }
  385. static void stbi__stdio_skip(void *user, int n)
  386. {
  387. fseek((FILE*) user, n, SEEK_CUR);
  388. }
  389. static int stbi__stdio_eof(void *user)
  390. {
  391. return feof((FILE*) user);
  392. }
  393. static stbi_io_callbacks stbi__stdio_callbacks =
  394. {
  395. stbi__stdio_read,
  396. stbi__stdio_skip,
  397. stbi__stdio_eof,
  398. };
  399. static void stbi__start_file(stbi__context *s, FILE *f)
  400. {
  401. stbi__start_callbacks(s, &stbi__stdio_callbacks, (void *) f);
  402. }
  403. //static void stop_file(stbi__context *s) { }
  404. #endif // !STBI_NO_STDIO
  405. static void stbi__rewind(stbi__context *s)
  406. {
  407. // conceptually rewind SHOULD rewind to the beginning of the stream,
  408. // but we just rewind to the beginning of the initial buffer, because
  409. // we only use it after doing 'test', which only ever looks at at most 92 bytes
  410. s->img_buffer = s->img_buffer_original;
  411. }
  412. static int stbi__jpeg_test(stbi__context *s);
  413. static stbi_uc *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  414. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp);
  415. static int stbi__png_test(stbi__context *s);
  416. static stbi_uc *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  417. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp);
  418. static int stbi__bmp_test(stbi__context *s);
  419. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  420. static int stbi__tga_test(stbi__context *s);
  421. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  422. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp);
  423. static int stbi__psd_test(stbi__context *s);
  424. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  425. #ifndef STBI_NO_HDR
  426. static int stbi__hdr_test(stbi__context *s);
  427. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  428. #endif
  429. static int stbi__pic_test(stbi__context *s);
  430. static stbi_uc *stbi__pic_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  431. static int stbi__gif_test(stbi__context *s);
  432. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp);
  433. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp);
  434. // this is not threadsafe
  435. static const char *stbi__g_failure_reason;
  436. STBIDEF const char *stbi_failure_reason(void)
  437. {
  438. return stbi__g_failure_reason;
  439. }
  440. static int stbi__err(const char *str)
  441. {
  442. stbi__g_failure_reason = str;
  443. return 0;
  444. }
  445. static void *stbi__malloc(size_t size)
  446. {
  447. return malloc(size);
  448. }
  449. // stbi__err - error
  450. // stbi__errpf - error returning pointer to float
  451. // stbi__errpuc - error returning pointer to unsigned char
  452. #ifdef STBI_NO_FAILURE_STRINGS
  453. #define stbi__err(x,y) 0
  454. #elif defined(STBI_FAILURE_USERMSG)
  455. #define stbi__err(x,y) stbi__err(y)
  456. #else
  457. #define stbi__err(x,y) stbi__err(x)
  458. #endif
  459. #define stbi__errpf(x,y) ((float *) (stbi__err(x,y)?NULL:NULL))
  460. #define stbi__errpuc(x,y) ((unsigned char *) (stbi__err(x,y)?NULL:NULL))
  461. STBIDEF void stbi_image_free(void *retval_from_stbi_load)
  462. {
  463. free(retval_from_stbi_load);
  464. }
  465. #ifndef STBI_NO_HDR
  466. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp);
  467. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp);
  468. #endif
  469. static unsigned char *stbi_load_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  470. {
  471. if (stbi__jpeg_test(s)) return stbi__jpeg_load(s,x,y,comp,req_comp);
  472. if (stbi__png_test(s)) return stbi__png_load(s,x,y,comp,req_comp);
  473. if (stbi__bmp_test(s)) return stbi__bmp_load(s,x,y,comp,req_comp);
  474. if (stbi__gif_test(s)) return stbi__gif_load(s,x,y,comp,req_comp);
  475. if (stbi__psd_test(s)) return stbi__psd_load(s,x,y,comp,req_comp);
  476. if (stbi__pic_test(s)) return stbi__pic_load(s,x,y,comp,req_comp);
  477. #ifndef STBI_NO_HDR
  478. if (stbi__hdr_test(s)) {
  479. float *hdr = stbi__hdr_load(s, x,y,comp,req_comp);
  480. return stbi__hdr_to_ldr(hdr, *x, *y, req_comp ? req_comp : *comp);
  481. }
  482. #endif
  483. // test tga last because it's a crappy test!
  484. if (stbi__tga_test(s))
  485. return stbi__tga_load(s,x,y,comp,req_comp);
  486. return stbi__errpuc("unknown image type", "Image not of any known type, or corrupt");
  487. }
  488. #ifndef STBI_NO_STDIO
  489. FILE *stbi__fopen(char const *filename, char const *mode)
  490. {
  491. FILE *f;
  492. #if defined(_MSC_VER) && _MSC_VER >= 1400
  493. if (0 != fopen_s(&f, filename, mode))
  494. f=0;
  495. #else
  496. f = fopen(filename, mode);
  497. #endif
  498. return f;
  499. }
  500. STBIDEF unsigned char *stbi_load(char const *filename, int *x, int *y, int *comp, int req_comp)
  501. {
  502. FILE *f = stbi__fopen(filename, "rb");
  503. unsigned char *result;
  504. if (!f) return stbi__errpuc("can't fopen", "Unable to open file");
  505. result = stbi_load_from_file(f,x,y,comp,req_comp);
  506. fclose(f);
  507. return result;
  508. }
  509. STBIDEF unsigned char *stbi_load_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  510. {
  511. unsigned char *result;
  512. stbi__context s;
  513. stbi__start_file(&s,f);
  514. result = stbi_load_main(&s,x,y,comp,req_comp);
  515. if (result) {
  516. // need to 'unget' all the characters in the IO buffer
  517. fseek(f, - (int) (s.img_buffer_end - s.img_buffer), SEEK_CUR);
  518. }
  519. return result;
  520. }
  521. #endif //!STBI_NO_STDIO
  522. STBIDEF unsigned char *stbi_load_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  523. {
  524. stbi__context s;
  525. stbi__start_mem(&s,buffer,len);
  526. return stbi_load_main(&s,x,y,comp,req_comp);
  527. }
  528. unsigned char *stbi_load_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  529. {
  530. stbi__context s;
  531. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  532. return stbi_load_main(&s,x,y,comp,req_comp);
  533. }
  534. #ifndef STBI_NO_HDR
  535. float *stbi_loadf_main(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  536. {
  537. unsigned char *data;
  538. #ifndef STBI_NO_HDR
  539. if (stbi__hdr_test(s))
  540. return stbi__hdr_load(s,x,y,comp,req_comp);
  541. #endif
  542. data = stbi_load_main(s, x, y, comp, req_comp);
  543. if (data)
  544. return stbi__ldr_to_hdr(data, *x, *y, req_comp ? req_comp : *comp);
  545. return stbi__errpf("unknown image type", "Image not of any known type, or corrupt");
  546. }
  547. float *stbi_loadf_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp, int req_comp)
  548. {
  549. stbi__context s;
  550. stbi__start_mem(&s,buffer,len);
  551. return stbi_loadf_main(&s,x,y,comp,req_comp);
  552. }
  553. float *stbi_loadf_from_callbacks(stbi_io_callbacks const *clbk, void *user, int *x, int *y, int *comp, int req_comp)
  554. {
  555. stbi__context s;
  556. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  557. return stbi_loadf_main(&s,x,y,comp,req_comp);
  558. }
  559. #ifndef STBI_NO_STDIO
  560. float *stbi_loadf(char const *filename, int *x, int *y, int *comp, int req_comp)
  561. {
  562. float *result;
  563. FILE *f = stbi__fopen(filename, "rb");
  564. if (!f) return stbi__errpf("can't fopen", "Unable to open file");
  565. result = stbi_loadf_from_file(f,x,y,comp,req_comp);
  566. fclose(f);
  567. return result;
  568. }
  569. float *stbi_loadf_from_file(FILE *f, int *x, int *y, int *comp, int req_comp)
  570. {
  571. stbi__context s;
  572. stbi__start_file(&s,f);
  573. return stbi_loadf_main(&s,x,y,comp,req_comp);
  574. }
  575. #endif // !STBI_NO_STDIO
  576. #endif // !STBI_NO_HDR
  577. // these is-hdr-or-not is defined independent of whether STBI_NO_HDR is
  578. // defined, for API simplicity; if STBI_NO_HDR is defined, it always
  579. // reports false!
  580. int stbi_is_hdr_from_memory(stbi_uc const *buffer, int len)
  581. {
  582. #ifndef STBI_NO_HDR
  583. stbi__context s;
  584. stbi__start_mem(&s,buffer,len);
  585. return stbi__hdr_test(&s);
  586. #else
  587. STBI_NOTUSED(buffer);
  588. STBI_NOTUSED(len);
  589. return 0;
  590. #endif
  591. }
  592. #ifndef STBI_NO_STDIO
  593. STBIDEF int stbi_is_hdr (char const *filename)
  594. {
  595. FILE *f = stbi__fopen(filename, "rb");
  596. int result=0;
  597. if (f) {
  598. result = stbi_is_hdr_from_file(f);
  599. fclose(f);
  600. }
  601. return result;
  602. }
  603. STBIDEF int stbi_is_hdr_from_file(FILE *f)
  604. {
  605. #ifndef STBI_NO_HDR
  606. stbi__context s;
  607. stbi__start_file(&s,f);
  608. return stbi__hdr_test(&s);
  609. #else
  610. return 0;
  611. #endif
  612. }
  613. #endif // !STBI_NO_STDIO
  614. STBIDEF int stbi_is_hdr_from_callbacks(stbi_io_callbacks const *clbk, void *user)
  615. {
  616. #ifndef STBI_NO_HDR
  617. stbi__context s;
  618. stbi__start_callbacks(&s, (stbi_io_callbacks *) clbk, user);
  619. return stbi__hdr_test(&s);
  620. #else
  621. return 0;
  622. #endif
  623. }
  624. #ifndef STBI_NO_HDR
  625. static float stbi__h2l_gamma_i=1.0f/2.2f, stbi__h2l_scale_i=1.0f;
  626. static float stbi__l2h_gamma=2.2f, stbi__l2h_scale=1.0f;
  627. void stbi_hdr_to_ldr_gamma(float gamma) { stbi__h2l_gamma_i = 1/gamma; }
  628. void stbi_hdr_to_ldr_scale(float scale) { stbi__h2l_scale_i = 1/scale; }
  629. void stbi_ldr_to_hdr_gamma(float gamma) { stbi__l2h_gamma = gamma; }
  630. void stbi_ldr_to_hdr_scale(float scale) { stbi__l2h_scale = scale; }
  631. #endif
  632. //////////////////////////////////////////////////////////////////////////////
  633. //
  634. // Common code used by all image loaders
  635. //
  636. enum
  637. {
  638. SCAN_load=0,
  639. SCAN_type,
  640. SCAN_header
  641. };
  642. static void stbi__refill_buffer(stbi__context *s)
  643. {
  644. int n = (s->io.read)(s->io_user_data,(char*)s->buffer_start,s->buflen);
  645. if (n == 0) {
  646. // at end of file, treat same as if from memory, but need to handle case
  647. // where s->img_buffer isn't pointing to safe memory, e.g. 0-byte file
  648. s->read_from_callbacks = 0;
  649. s->img_buffer = s->buffer_start;
  650. s->img_buffer_end = s->buffer_start+1;
  651. *s->img_buffer = 0;
  652. } else {
  653. s->img_buffer = s->buffer_start;
  654. s->img_buffer_end = s->buffer_start + n;
  655. }
  656. }
  657. stbi_inline static stbi_uc stbi__get8(stbi__context *s)
  658. {
  659. if (s->img_buffer < s->img_buffer_end)
  660. return *s->img_buffer++;
  661. if (s->read_from_callbacks) {
  662. stbi__refill_buffer(s);
  663. return *s->img_buffer++;
  664. }
  665. return 0;
  666. }
  667. stbi_inline static int stbi__at_eof(stbi__context *s)
  668. {
  669. if (s->io.read) {
  670. if (!(s->io.eof)(s->io_user_data)) return 0;
  671. // if feof() is true, check if buffer = end
  672. // special case: we've only got the special 0 character at the end
  673. if (s->read_from_callbacks == 0) return 1;
  674. }
  675. return s->img_buffer >= s->img_buffer_end;
  676. }
  677. static void stbi__skip(stbi__context *s, int n)
  678. {
  679. if (s->io.read) {
  680. int blen = (int) (s->img_buffer_end - s->img_buffer);
  681. if (blen < n) {
  682. s->img_buffer = s->img_buffer_end;
  683. (s->io.skip)(s->io_user_data, n - blen);
  684. return;
  685. }
  686. }
  687. s->img_buffer += n;
  688. }
  689. static int stbi__getn(stbi__context *s, stbi_uc *buffer, int n)
  690. {
  691. if (s->io.read) {
  692. int blen = (int) (s->img_buffer_end - s->img_buffer);
  693. if (blen < n) {
  694. int res, count;
  695. memcpy(buffer, s->img_buffer, blen);
  696. count = (s->io.read)(s->io_user_data, (char*) buffer + blen, n - blen);
  697. res = (count == (n-blen));
  698. s->img_buffer = s->img_buffer_end;
  699. return res;
  700. }
  701. }
  702. if (s->img_buffer+n <= s->img_buffer_end) {
  703. memcpy(buffer, s->img_buffer, n);
  704. s->img_buffer += n;
  705. return 1;
  706. } else
  707. return 0;
  708. }
  709. static int stbi__get16be(stbi__context *s)
  710. {
  711. int z = stbi__get8(s);
  712. return (z << 8) + stbi__get8(s);
  713. }
  714. static stbi__uint32 stbi__get32be(stbi__context *s)
  715. {
  716. stbi__uint32 z = stbi__get16be(s);
  717. return (z << 16) + stbi__get16be(s);
  718. }
  719. static int stbi__get16le(stbi__context *s)
  720. {
  721. int z = stbi__get8(s);
  722. return z + (stbi__get8(s) << 8);
  723. }
  724. static stbi__uint32 stbi__get32le(stbi__context *s)
  725. {
  726. stbi__uint32 z = stbi__get16le(s);
  727. return z + (stbi__get16le(s) << 16);
  728. }
  729. //////////////////////////////////////////////////////////////////////////////
  730. //
  731. // generic converter from built-in img_n to req_comp
  732. // individual types do this automatically as much as possible (e.g. jpeg
  733. // does all cases internally since it needs to colorspace convert anyway,
  734. // and it never has alpha, so very few cases ). png can automatically
  735. // interleave an alpha=255 channel, but falls back to this for other cases
  736. //
  737. // assume data buffer is malloced, so malloc a new one and free that one
  738. // only failure mode is malloc failing
  739. static stbi_uc stbi__compute_y(int r, int g, int b)
  740. {
  741. return (stbi_uc) (((r*77) + (g*150) + (29*b)) >> 8);
  742. }
  743. static unsigned char *stbi__convert_format(unsigned char *data, int img_n, int req_comp, unsigned int x, unsigned int y)
  744. {
  745. int i,j;
  746. unsigned char *good;
  747. if (req_comp == img_n) return data;
  748. STBI_ASSERT(req_comp >= 1 && req_comp <= 4);
  749. good = (unsigned char *) stbi__malloc(req_comp * x * y);
  750. if (good == NULL) {
  751. free(data);
  752. return stbi__errpuc("outofmem", "Out of memory");
  753. }
  754. for (j=0; j < (int) y; ++j) {
  755. unsigned char *src = data + j * x * img_n ;
  756. unsigned char *dest = good + j * x * req_comp;
  757. #define COMBO(a,b) ((a)*8+(b))
  758. #define CASE(a,b) case COMBO(a,b): for(i=x-1; i >= 0; --i, src += a, dest += b)
  759. // convert source image with img_n components to one with req_comp components;
  760. // avoid switch per pixel, so use switch per scanline and massive macros
  761. switch (COMBO(img_n, req_comp)) {
  762. CASE(1,2) dest[0]=src[0], dest[1]=255; break;
  763. CASE(1,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  764. CASE(1,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=255; break;
  765. CASE(2,1) dest[0]=src[0]; break;
  766. CASE(2,3) dest[0]=dest[1]=dest[2]=src[0]; break;
  767. CASE(2,4) dest[0]=dest[1]=dest[2]=src[0], dest[3]=src[1]; break;
  768. CASE(3,4) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2],dest[3]=255; break;
  769. CASE(3,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  770. CASE(3,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = 255; break;
  771. CASE(4,1) dest[0]=stbi__compute_y(src[0],src[1],src[2]); break;
  772. CASE(4,2) dest[0]=stbi__compute_y(src[0],src[1],src[2]), dest[1] = src[3]; break;
  773. CASE(4,3) dest[0]=src[0],dest[1]=src[1],dest[2]=src[2]; break;
  774. default: STBI_ASSERT(0);
  775. }
  776. #undef CASE
  777. }
  778. free(data);
  779. return good;
  780. }
  781. #ifndef STBI_NO_HDR
  782. static float *stbi__ldr_to_hdr(stbi_uc *data, int x, int y, int comp)
  783. {
  784. int i,k,n;
  785. float *output = (float *) stbi__malloc(x * y * comp * sizeof(float));
  786. if (output == NULL) { free(data); return stbi__errpf("outofmem", "Out of memory"); }
  787. // compute number of non-alpha components
  788. if (comp & 1) n = comp; else n = comp-1;
  789. for (i=0; i < x*y; ++i) {
  790. for (k=0; k < n; ++k) {
  791. output[i*comp + k] = (float) (pow(data[i*comp+k]/255.0f, stbi__l2h_gamma) * stbi__l2h_scale);
  792. }
  793. if (k < comp) output[i*comp + k] = data[i*comp+k]/255.0f;
  794. }
  795. free(data);
  796. return output;
  797. }
  798. #define stbi__float2int(x) ((int) (x))
  799. static stbi_uc *stbi__hdr_to_ldr(float *data, int x, int y, int comp)
  800. {
  801. int i,k,n;
  802. stbi_uc *output = (stbi_uc *) stbi__malloc(x * y * comp);
  803. if (output == NULL) { free(data); return stbi__errpuc("outofmem", "Out of memory"); }
  804. // compute number of non-alpha components
  805. if (comp & 1) n = comp; else n = comp-1;
  806. for (i=0; i < x*y; ++i) {
  807. for (k=0; k < n; ++k) {
  808. float z = (float) pow(data[i*comp+k]*stbi__h2l_scale_i, stbi__h2l_gamma_i) * 255 + 0.5f;
  809. if (z < 0) z = 0;
  810. if (z > 255) z = 255;
  811. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  812. }
  813. if (k < comp) {
  814. float z = data[i*comp+k] * 255 + 0.5f;
  815. if (z < 0) z = 0;
  816. if (z > 255) z = 255;
  817. output[i*comp + k] = (stbi_uc) stbi__float2int(z);
  818. }
  819. }
  820. free(data);
  821. return output;
  822. }
  823. #endif
  824. //////////////////////////////////////////////////////////////////////////////
  825. //
  826. // "baseline" JPEG/JFIF decoder (not actually fully baseline implementation)
  827. //
  828. // simple implementation
  829. // - channel subsampling of at most 2 in each dimension
  830. // - doesn't support delayed output of y-dimension
  831. // - simple interface (only one output format: 8-bit interleaved RGB)
  832. // - doesn't try to recover corrupt jpegs
  833. // - doesn't allow partial loading, loading multiple at once
  834. // - still fast on x86 (copying globals into locals doesn't help x86)
  835. // - allocates lots of intermediate memory (full size of all components)
  836. // - non-interleaved case requires this anyway
  837. // - allows good upsampling (see next)
  838. // high-quality
  839. // - upsampled channels are bilinearly interpolated, even across blocks
  840. // - quality integer IDCT derived from IJG's 'slow'
  841. // performance
  842. // - fast huffman; reasonable integer IDCT
  843. // - uses a lot of intermediate memory, could cache poorly
  844. // - load http://nothings.org/remote/anemones.jpg 3 times on 2.8Ghz P4
  845. // stb_jpeg: 1.34 seconds (MSVC6, default release build)
  846. // stb_jpeg: 1.06 seconds (MSVC6, processor = Pentium Pro)
  847. // IJL11.dll: 1.08 seconds (compiled by intel)
  848. // IJG 1998: 0.98 seconds (MSVC6, makefile provided by IJG)
  849. // IJG 1998: 0.95 seconds (MSVC6, makefile + proc=PPro)
  850. // huffman decoding acceleration
  851. #define FAST_BITS 9 // larger handles more cases; smaller stomps less cache
  852. typedef struct
  853. {
  854. stbi_uc fast[1 << FAST_BITS];
  855. // weirdly, repacking this into AoS is a 10% speed loss, instead of a win
  856. stbi__uint16 code[256];
  857. stbi_uc values[256];
  858. stbi_uc size[257];
  859. unsigned int maxcode[18];
  860. int delta[17]; // old 'firstsymbol' - old 'firstcode'
  861. } stbi__huffman;
  862. typedef struct
  863. {
  864. #ifdef STBI_SIMD
  865. unsigned short dequant2[4][64];
  866. #endif
  867. stbi__context *s;
  868. stbi__huffman huff_dc[4];
  869. stbi__huffman huff_ac[4];
  870. stbi_uc dequant[4][64];
  871. // sizes for components, interleaved MCUs
  872. int img_h_max, img_v_max;
  873. int img_mcu_x, img_mcu_y;
  874. int img_mcu_w, img_mcu_h;
  875. // definition of jpeg image component
  876. struct
  877. {
  878. int id;
  879. int h,v;
  880. int tq;
  881. int hd,ha;
  882. int dc_pred;
  883. int x,y,w2,h2;
  884. stbi_uc *data;
  885. void *raw_data;
  886. stbi_uc *linebuf;
  887. } img_comp[4];
  888. stbi__uint32 code_buffer; // jpeg entropy-coded buffer
  889. int code_bits; // number of valid bits
  890. unsigned char marker; // marker seen while filling entropy buffer
  891. int nomore; // flag if we saw a marker so must stop
  892. int scan_n, order[4];
  893. int restart_interval, todo;
  894. } stbi__jpeg;
  895. static int stbi__build_huffman(stbi__huffman *h, int *count)
  896. {
  897. int i,j,k=0,code;
  898. // build size list for each symbol (from JPEG spec)
  899. for (i=0; i < 16; ++i)
  900. for (j=0; j < count[i]; ++j)
  901. h->size[k++] = (stbi_uc) (i+1);
  902. h->size[k] = 0;
  903. // compute actual symbols (from jpeg spec)
  904. code = 0;
  905. k = 0;
  906. for(j=1; j <= 16; ++j) {
  907. // compute delta to add to code to compute symbol id
  908. h->delta[j] = k - code;
  909. if (h->size[k] == j) {
  910. while (h->size[k] == j)
  911. h->code[k++] = (stbi__uint16) (code++);
  912. if (code-1 >= (1 << j)) return stbi__err("bad code lengths","Corrupt JPEG");
  913. }
  914. // compute largest code + 1 for this size, preshifted as needed later
  915. h->maxcode[j] = code << (16-j);
  916. code <<= 1;
  917. }
  918. h->maxcode[j] = 0xffffffff;
  919. // build non-spec acceleration table; 255 is flag for not-accelerated
  920. memset(h->fast, 255, 1 << FAST_BITS);
  921. for (i=0; i < k; ++i) {
  922. int s = h->size[i];
  923. if (s <= FAST_BITS) {
  924. int c = h->code[i] << (FAST_BITS-s);
  925. int m = 1 << (FAST_BITS-s);
  926. for (j=0; j < m; ++j) {
  927. h->fast[c+j] = (stbi_uc) i;
  928. }
  929. }
  930. }
  931. return 1;
  932. }
  933. static void stbi__grow_buffer_unsafe(stbi__jpeg *j)
  934. {
  935. do {
  936. int b = j->nomore ? 0 : stbi__get8(j->s);
  937. if (b == 0xff) {
  938. int c = stbi__get8(j->s);
  939. if (c != 0) {
  940. j->marker = (unsigned char) c;
  941. j->nomore = 1;
  942. return;
  943. }
  944. }
  945. j->code_buffer |= b << (24 - j->code_bits);
  946. j->code_bits += 8;
  947. } while (j->code_bits <= 24);
  948. }
  949. // (1 << n) - 1
  950. static stbi__uint32 stbi__bmask[17]={0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535};
  951. // decode a jpeg huffman value from the bitstream
  952. stbi_inline static int stbi__jpeg_huff_decode(stbi__jpeg *j, stbi__huffman *h)
  953. {
  954. unsigned int temp;
  955. int c,k;
  956. if (j->code_bits < 16) stbi__grow_buffer_unsafe(j);
  957. // look at the top FAST_BITS and determine what symbol ID it is,
  958. // if the code is <= FAST_BITS
  959. c = (j->code_buffer >> (32 - FAST_BITS)) & ((1 << FAST_BITS)-1);
  960. k = h->fast[c];
  961. if (k < 255) {
  962. int s = h->size[k];
  963. if (s > j->code_bits)
  964. return -1;
  965. j->code_buffer <<= s;
  966. j->code_bits -= s;
  967. return h->values[k];
  968. }
  969. // naive test is to shift the code_buffer down so k bits are
  970. // valid, then test against maxcode. To speed this up, we've
  971. // preshifted maxcode left so that it has (16-k) 0s at the
  972. // end; in other words, regardless of the number of bits, it
  973. // wants to be compared against something shifted to have 16;
  974. // that way we don't need to shift inside the loop.
  975. temp = j->code_buffer >> 16;
  976. for (k=FAST_BITS+1 ; ; ++k)
  977. if (temp < h->maxcode[k])
  978. break;
  979. if (k == 17) {
  980. // error! code not found
  981. j->code_bits -= 16;
  982. return -1;
  983. }
  984. if (k > j->code_bits)
  985. return -1;
  986. // convert the huffman code to the symbol id
  987. c = ((j->code_buffer >> (32 - k)) & stbi__bmask[k]) + h->delta[k];
  988. STBI_ASSERT((((j->code_buffer) >> (32 - h->size[c])) & stbi__bmask[h->size[c]]) == h->code[c]);
  989. // convert the id to a symbol
  990. j->code_bits -= k;
  991. j->code_buffer <<= k;
  992. return h->values[c];
  993. }
  994. // combined JPEG 'receive' and JPEG 'extend', since baseline
  995. // always extends everything it receives.
  996. stbi_inline static int stbi__extend_receive(stbi__jpeg *j, int n)
  997. {
  998. unsigned int m = 1 << (n-1);
  999. unsigned int k;
  1000. if (j->code_bits < n) stbi__grow_buffer_unsafe(j);
  1001. #if 1
  1002. k = stbi_lrot(j->code_buffer, n);
  1003. j->code_buffer = k & ~stbi__bmask[n];
  1004. k &= stbi__bmask[n];
  1005. j->code_bits -= n;
  1006. #else
  1007. k = (j->code_buffer >> (32 - n)) & stbi__bmask[n];
  1008. j->code_bits -= n;
  1009. j->code_buffer <<= n;
  1010. #endif
  1011. // the following test is probably a random branch that won't
  1012. // predict well. I tried to table accelerate it but failed.
  1013. // maybe it's compiling as a conditional move?
  1014. if (k < m)
  1015. return (-1 << n) + k + 1;
  1016. else
  1017. return k;
  1018. }
  1019. // given a value that's at position X in the zigzag stream,
  1020. // where does it appear in the 8x8 matrix coded as row-major?
  1021. static stbi_uc stbi__jpeg_dezigzag[64+15] =
  1022. {
  1023. 0, 1, 8, 16, 9, 2, 3, 10,
  1024. 17, 24, 32, 25, 18, 11, 4, 5,
  1025. 12, 19, 26, 33, 40, 48, 41, 34,
  1026. 27, 20, 13, 6, 7, 14, 21, 28,
  1027. 35, 42, 49, 56, 57, 50, 43, 36,
  1028. 29, 22, 15, 23, 30, 37, 44, 51,
  1029. 58, 59, 52, 45, 38, 31, 39, 46,
  1030. 53, 60, 61, 54, 47, 55, 62, 63,
  1031. // let corrupt input sample past end
  1032. 63, 63, 63, 63, 63, 63, 63, 63,
  1033. 63, 63, 63, 63, 63, 63, 63
  1034. };
  1035. // decode one 64-entry block--
  1036. static int stbi__jpeg_decode_block(stbi__jpeg *j, short data[64], stbi__huffman *hdc, stbi__huffman *hac, int b)
  1037. {
  1038. int diff,dc,k;
  1039. int t = stbi__jpeg_huff_decode(j, hdc);
  1040. if (t < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1041. // 0 all the ac values now so we can do it 32-bits at a time
  1042. memset(data,0,64*sizeof(data[0]));
  1043. diff = t ? stbi__extend_receive(j, t) : 0;
  1044. dc = j->img_comp[b].dc_pred + diff;
  1045. j->img_comp[b].dc_pred = dc;
  1046. data[0] = (short) dc;
  1047. // decode AC components, see JPEG spec
  1048. k = 1;
  1049. do {
  1050. int r,s;
  1051. int rs = stbi__jpeg_huff_decode(j, hac);
  1052. if (rs < 0) return stbi__err("bad huffman code","Corrupt JPEG");
  1053. s = rs & 15;
  1054. r = rs >> 4;
  1055. if (s == 0) {
  1056. if (rs != 0xf0) break; // end block
  1057. k += 16;
  1058. } else {
  1059. k += r;
  1060. // decode into unzigzag'd location
  1061. data[stbi__jpeg_dezigzag[k++]] = (short) stbi__extend_receive(j,s);
  1062. }
  1063. } while (k < 64);
  1064. return 1;
  1065. }
  1066. // take a -128..127 value and stbi__clamp it and convert to 0..255
  1067. stbi_inline static stbi_uc stbi__clamp(int x)
  1068. {
  1069. // trick to use a single test to catch both cases
  1070. if ((unsigned int) x > 255) {
  1071. if (x < 0) return 0;
  1072. if (x > 255) return 255;
  1073. }
  1074. return (stbi_uc) x;
  1075. }
  1076. #define stbi__f2f(x) (int) (((x) * 4096 + 0.5))
  1077. #define stbi__fsh(x) ((x) << 12)
  1078. // derived from jidctint -- DCT_ISLOW
  1079. #define STBI__IDCT_1D(s0,s1,s2,s3,s4,s5,s6,s7) \
  1080. int t0,t1,t2,t3,p1,p2,p3,p4,p5,x0,x1,x2,x3; \
  1081. p2 = s2; \
  1082. p3 = s6; \
  1083. p1 = (p2+p3) * stbi__f2f(0.5411961f); \
  1084. t2 = p1 + p3*stbi__f2f(-1.847759065f); \
  1085. t3 = p1 + p2*stbi__f2f( 0.765366865f); \
  1086. p2 = s0; \
  1087. p3 = s4; \
  1088. t0 = stbi__fsh(p2+p3); \
  1089. t1 = stbi__fsh(p2-p3); \
  1090. x0 = t0+t3; \
  1091. x3 = t0-t3; \
  1092. x1 = t1+t2; \
  1093. x2 = t1-t2; \
  1094. t0 = s7; \
  1095. t1 = s5; \
  1096. t2 = s3; \
  1097. t3 = s1; \
  1098. p3 = t0+t2; \
  1099. p4 = t1+t3; \
  1100. p1 = t0+t3; \
  1101. p2 = t1+t2; \
  1102. p5 = (p3+p4)*stbi__f2f( 1.175875602f); \
  1103. t0 = t0*stbi__f2f( 0.298631336f); \
  1104. t1 = t1*stbi__f2f( 2.053119869f); \
  1105. t2 = t2*stbi__f2f( 3.072711026f); \
  1106. t3 = t3*stbi__f2f( 1.501321110f); \
  1107. p1 = p5 + p1*stbi__f2f(-0.899976223f); \
  1108. p2 = p5 + p2*stbi__f2f(-2.562915447f); \
  1109. p3 = p3*stbi__f2f(-1.961570560f); \
  1110. p4 = p4*stbi__f2f(-0.390180644f); \
  1111. t3 += p1+p4; \
  1112. t2 += p2+p3; \
  1113. t1 += p2+p4; \
  1114. t0 += p1+p3;
  1115. #ifdef STBI_SIMD
  1116. typedef unsigned short stbi_dequantize_t;
  1117. #else
  1118. typedef stbi_uc stbi_dequantize_t;
  1119. #endif
  1120. // .344 seconds on 3*anemones.jpg
  1121. static void stbi__idct_block(stbi_uc *out, int out_stride, short data[64], stbi_dequantize_t *dequantize)
  1122. {
  1123. int i,val[64],*v=val;
  1124. stbi_dequantize_t *dq = dequantize;
  1125. stbi_uc *o;
  1126. short *d = data;
  1127. // columns
  1128. for (i=0; i < 8; ++i,++d,++dq, ++v) {
  1129. // if all zeroes, shortcut -- this avoids dequantizing 0s and IDCTing
  1130. if (d[ 8]==0 && d[16]==0 && d[24]==0 && d[32]==0
  1131. && d[40]==0 && d[48]==0 && d[56]==0) {
  1132. // no shortcut 0 seconds
  1133. // (1|2|3|4|5|6|7)==0 0 seconds
  1134. // all separate -0.047 seconds
  1135. // 1 && 2|3 && 4|5 && 6|7: -0.047 seconds
  1136. int dcterm = d[0] * dq[0] << 2;
  1137. v[0] = v[8] = v[16] = v[24] = v[32] = v[40] = v[48] = v[56] = dcterm;
  1138. } else {
  1139. STBI__IDCT_1D(d[ 0]*dq[ 0],d[ 8]*dq[ 8],d[16]*dq[16],d[24]*dq[24],
  1140. d[32]*dq[32],d[40]*dq[40],d[48]*dq[48],d[56]*dq[56])
  1141. // constants scaled things up by 1<<12; let's bring them back
  1142. // down, but keep 2 extra bits of precision
  1143. x0 += 512; x1 += 512; x2 += 512; x3 += 512;
  1144. v[ 0] = (x0+t3) >> 10;
  1145. v[56] = (x0-t3) >> 10;
  1146. v[ 8] = (x1+t2) >> 10;
  1147. v[48] = (x1-t2) >> 10;
  1148. v[16] = (x2+t1) >> 10;
  1149. v[40] = (x2-t1) >> 10;
  1150. v[24] = (x3+t0) >> 10;
  1151. v[32] = (x3-t0) >> 10;
  1152. }
  1153. }
  1154. for (i=0, v=val, o=out; i < 8; ++i,v+=8,o+=out_stride) {
  1155. // no fast case since the first 1D IDCT spread components out
  1156. STBI__IDCT_1D(v[0],v[1],v[2],v[3],v[4],v[5],v[6],v[7])
  1157. // constants scaled things up by 1<<12, plus we had 1<<2 from first
  1158. // loop, plus horizontal and vertical each scale by sqrt(8) so together
  1159. // we've got an extra 1<<3, so 1<<17 total we need to remove.
  1160. // so we want to round that, which means adding 0.5 * 1<<17,
  1161. // aka 65536. Also, we'll end up with -128 to 127 that we want
  1162. // to encode as 0..255 by adding 128, so we'll add that before the shift
  1163. x0 += 65536 + (128<<17);
  1164. x1 += 65536 + (128<<17);
  1165. x2 += 65536 + (128<<17);
  1166. x3 += 65536 + (128<<17);
  1167. // tried computing the shifts into temps, or'ing the temps to see
  1168. // if any were out of range, but that was slower
  1169. o[0] = stbi__clamp((x0+t3) >> 17);
  1170. o[7] = stbi__clamp((x0-t3) >> 17);
  1171. o[1] = stbi__clamp((x1+t2) >> 17);
  1172. o[6] = stbi__clamp((x1-t2) >> 17);
  1173. o[2] = stbi__clamp((x2+t1) >> 17);
  1174. o[5] = stbi__clamp((x2-t1) >> 17);
  1175. o[3] = stbi__clamp((x3+t0) >> 17);
  1176. o[4] = stbi__clamp((x3-t0) >> 17);
  1177. }
  1178. }
  1179. #ifdef STBI_SIMD
  1180. static stbi_idct_8x8 stbi__idct_installed = stbi__idct_block;
  1181. STBIDEF void stbi_install_idct(stbi_idct_8x8 func)
  1182. {
  1183. stbi__idct_installed = func;
  1184. }
  1185. #endif
  1186. #define STBI__MARKER_none 0xff
  1187. // if there's a pending marker from the entropy stream, return that
  1188. // otherwise, fetch from the stream and get a marker. if there's no
  1189. // marker, return 0xff, which is never a valid marker value
  1190. static stbi_uc stbi__get_marker(stbi__jpeg *j)
  1191. {
  1192. stbi_uc x;
  1193. if (j->marker != STBI__MARKER_none) { x = j->marker; j->marker = STBI__MARKER_none; return x; }
  1194. x = stbi__get8(j->s);
  1195. if (x != 0xff) return STBI__MARKER_none;
  1196. while (x == 0xff)
  1197. x = stbi__get8(j->s);
  1198. return x;
  1199. }
  1200. // in each scan, we'll have scan_n components, and the order
  1201. // of the components is specified by order[]
  1202. #define STBI__RESTART(x) ((x) >= 0xd0 && (x) <= 0xd7)
  1203. // after a restart interval, stbi__jpeg_reset the entropy decoder and
  1204. // the dc prediction
  1205. static void stbi__jpeg_reset(stbi__jpeg *j)
  1206. {
  1207. j->code_bits = 0;
  1208. j->code_buffer = 0;
  1209. j->nomore = 0;
  1210. j->img_comp[0].dc_pred = j->img_comp[1].dc_pred = j->img_comp[2].dc_pred = 0;
  1211. j->marker = STBI__MARKER_none;
  1212. j->todo = j->restart_interval ? j->restart_interval : 0x7fffffff;
  1213. // no more than 1<<31 MCUs if no restart_interal? that's plenty safe,
  1214. // since we don't even allow 1<<30 pixels
  1215. }
  1216. static int stbi__parse_entropy_coded_data(stbi__jpeg *z)
  1217. {
  1218. stbi__jpeg_reset(z);
  1219. if (z->scan_n == 1) {
  1220. int i,j;
  1221. #ifdef STBI_SIMD
  1222. __declspec(align(16))
  1223. #endif
  1224. short data[64];
  1225. int n = z->order[0];
  1226. // non-interleaved data, we just need to process one block at a time,
  1227. // in trivial scanline order
  1228. // number of blocks to do just depends on how many actual "pixels" this
  1229. // component has, independent of interleaved MCU blocking and such
  1230. int w = (z->img_comp[n].x+7) >> 3;
  1231. int h = (z->img_comp[n].y+7) >> 3;
  1232. for (j=0; j < h; ++j) {
  1233. for (i=0; i < w; ++i) {
  1234. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
  1235. #ifdef STBI_SIMD
  1236. stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
  1237. #else
  1238. stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*j*8+i*8, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
  1239. #endif
  1240. // every data block is an MCU, so countdown the restart interval
  1241. if (--z->todo <= 0) {
  1242. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  1243. // if it's NOT a restart, then just bail, so we get corrupt data
  1244. // rather than no data
  1245. if (!STBI__RESTART(z->marker)) return 1;
  1246. stbi__jpeg_reset(z);
  1247. }
  1248. }
  1249. }
  1250. } else { // interleaved!
  1251. int i,j,k,x,y;
  1252. short data[64];
  1253. for (j=0; j < z->img_mcu_y; ++j) {
  1254. for (i=0; i < z->img_mcu_x; ++i) {
  1255. // scan an interleaved mcu... process scan_n components in order
  1256. for (k=0; k < z->scan_n; ++k) {
  1257. int n = z->order[k];
  1258. // scan out an mcu's worth of this component; that's just determined
  1259. // by the basic H and V specified for the component
  1260. for (y=0; y < z->img_comp[n].v; ++y) {
  1261. for (x=0; x < z->img_comp[n].h; ++x) {
  1262. int x2 = (i*z->img_comp[n].h + x)*8;
  1263. int y2 = (j*z->img_comp[n].v + y)*8;
  1264. if (!stbi__jpeg_decode_block(z, data, z->huff_dc+z->img_comp[n].hd, z->huff_ac+z->img_comp[n].ha, n)) return 0;
  1265. #ifdef STBI_SIMD
  1266. stbi__idct_installed(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant2[z->img_comp[n].tq]);
  1267. #else
  1268. stbi__idct_block(z->img_comp[n].data+z->img_comp[n].w2*y2+x2, z->img_comp[n].w2, data, z->dequant[z->img_comp[n].tq]);
  1269. #endif
  1270. }
  1271. }
  1272. }
  1273. // after all interleaved components, that's an interleaved MCU,
  1274. // so now count down the restart interval
  1275. if (--z->todo <= 0) {
  1276. if (z->code_bits < 24) stbi__grow_buffer_unsafe(z);
  1277. // if it's NOT a restart, then just bail, so we get corrupt data
  1278. // rather than no data
  1279. if (!STBI__RESTART(z->marker)) return 1;
  1280. stbi__jpeg_reset(z);
  1281. }
  1282. }
  1283. }
  1284. }
  1285. return 1;
  1286. }
  1287. static int stbi__process_marker(stbi__jpeg *z, int m)
  1288. {
  1289. int L;
  1290. switch (m) {
  1291. case STBI__MARKER_none: // no marker found
  1292. return stbi__err("expected marker","Corrupt JPEG");
  1293. case 0xC2: // stbi__SOF - progressive
  1294. return stbi__err("progressive jpeg","JPEG format not supported (progressive)");
  1295. case 0xDD: // DRI - specify restart interval
  1296. if (stbi__get16be(z->s) != 4) return stbi__err("bad DRI len","Corrupt JPEG");
  1297. z->restart_interval = stbi__get16be(z->s);
  1298. return 1;
  1299. case 0xDB: // DQT - define quantization table
  1300. L = stbi__get16be(z->s)-2;
  1301. while (L > 0) {
  1302. int q = stbi__get8(z->s);
  1303. int p = q >> 4;
  1304. int t = q & 15,i;
  1305. if (p != 0) return stbi__err("bad DQT type","Corrupt JPEG");
  1306. if (t > 3) return stbi__err("bad DQT table","Corrupt JPEG");
  1307. for (i=0; i < 64; ++i)
  1308. z->dequant[t][stbi__jpeg_dezigzag[i]] = stbi__get8(z->s);
  1309. #ifdef STBI_SIMD
  1310. for (i=0; i < 64; ++i)
  1311. z->dequant2[t][i] = z->dequant[t][i];
  1312. #endif
  1313. L -= 65;
  1314. }
  1315. return L==0;
  1316. case 0xC4: // DHT - define huffman table
  1317. L = stbi__get16be(z->s)-2;
  1318. while (L > 0) {
  1319. stbi_uc *v;
  1320. int sizes[16],i,n=0;
  1321. int q = stbi__get8(z->s);
  1322. int tc = q >> 4;
  1323. int th = q & 15;
  1324. if (tc > 1 || th > 3) return stbi__err("bad DHT header","Corrupt JPEG");
  1325. for (i=0; i < 16; ++i) {
  1326. sizes[i] = stbi__get8(z->s);
  1327. n += sizes[i];
  1328. }
  1329. L -= 17;
  1330. if (tc == 0) {
  1331. if (!stbi__build_huffman(z->huff_dc+th, sizes)) return 0;
  1332. v = z->huff_dc[th].values;
  1333. } else {
  1334. if (!stbi__build_huffman(z->huff_ac+th, sizes)) return 0;
  1335. v = z->huff_ac[th].values;
  1336. }
  1337. for (i=0; i < n; ++i)
  1338. v[i] = stbi__get8(z->s);
  1339. L -= n;
  1340. }
  1341. return L==0;
  1342. }
  1343. // check for comment block or APP blocks
  1344. if ((m >= 0xE0 && m <= 0xEF) || m == 0xFE) {
  1345. stbi__skip(z->s, stbi__get16be(z->s)-2);
  1346. return 1;
  1347. }
  1348. return 0;
  1349. }
  1350. // after we see stbi__SOS
  1351. static int stbi__process_scan_header(stbi__jpeg *z)
  1352. {
  1353. int i;
  1354. int Ls = stbi__get16be(z->s);
  1355. z->scan_n = stbi__get8(z->s);
  1356. if (z->scan_n < 1 || z->scan_n > 4 || z->scan_n > (int) z->s->img_n) return stbi__err("bad stbi__SOS component count","Corrupt JPEG");
  1357. if (Ls != 6+2*z->scan_n) return stbi__err("bad stbi__SOS len","Corrupt JPEG");
  1358. for (i=0; i < z->scan_n; ++i) {
  1359. int id = stbi__get8(z->s), which;
  1360. int q = stbi__get8(z->s);
  1361. for (which = 0; which < z->s->img_n; ++which)
  1362. if (z->img_comp[which].id == id)
  1363. break;
  1364. if (which == z->s->img_n) return 0;
  1365. z->img_comp[which].hd = q >> 4; if (z->img_comp[which].hd > 3) return stbi__err("bad DC huff","Corrupt JPEG");
  1366. z->img_comp[which].ha = q & 15; if (z->img_comp[which].ha > 3) return stbi__err("bad AC huff","Corrupt JPEG");
  1367. z->order[i] = which;
  1368. }
  1369. if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");
  1370. stbi__get8(z->s); // should be 63, but might be 0
  1371. if (stbi__get8(z->s) != 0) return stbi__err("bad stbi__SOS","Corrupt JPEG");
  1372. return 1;
  1373. }
  1374. static int stbi__process_frame_header(stbi__jpeg *z, int scan)
  1375. {
  1376. stbi__context *s = z->s;
  1377. int Lf,p,i,q, h_max=1,v_max=1,c;
  1378. Lf = stbi__get16be(s); if (Lf < 11) return stbi__err("bad stbi__SOF len","Corrupt JPEG"); // JPEG
  1379. p = stbi__get8(s); if (p != 8) return stbi__err("only 8-bit","JPEG format not supported: 8-bit only"); // JPEG baseline
  1380. 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
  1381. s->img_x = stbi__get16be(s); if (s->img_x == 0) return stbi__err("0 width","Corrupt JPEG"); // JPEG requires
  1382. c = stbi__get8(s);
  1383. if (c != 3 && c != 1) return stbi__err("bad component count","Corrupt JPEG"); // JFIF requires
  1384. s->img_n = c;
  1385. for (i=0; i < c; ++i) {
  1386. z->img_comp[i].data = NULL;
  1387. z->img_comp[i].linebuf = NULL;
  1388. }
  1389. if (Lf != 8+3*s->img_n) return stbi__err("bad stbi__SOF len","Corrupt JPEG");
  1390. for (i=0; i < s->img_n; ++i) {
  1391. z->img_comp[i].id = stbi__get8(s);
  1392. if (z->img_comp[i].id != i+1) // JFIF requires
  1393. if (z->img_comp[i].id != i) // some version of jpegtran outputs non-JFIF-compliant files!
  1394. return stbi__err("bad component ID","Corrupt JPEG");
  1395. q = stbi__get8(s);
  1396. 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");
  1397. 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");
  1398. z->img_comp[i].tq = stbi__get8(s); if (z->img_comp[i].tq > 3) return stbi__err("bad TQ","Corrupt JPEG");
  1399. }
  1400. if (scan != SCAN_load) return 1;
  1401. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  1402. for (i=0; i < s->img_n; ++i) {
  1403. if (z->img_comp[i].h > h_max) h_max = z->img_comp[i].h;
  1404. if (z->img_comp[i].v > v_max) v_max = z->img_comp[i].v;
  1405. }
  1406. // compute interleaved mcu info
  1407. z->img_h_max = h_max;
  1408. z->img_v_max = v_max;
  1409. z->img_mcu_w = h_max * 8;
  1410. z->img_mcu_h = v_max * 8;
  1411. z->img_mcu_x = (s->img_x + z->img_mcu_w-1) / z->img_mcu_w;
  1412. z->img_mcu_y = (s->img_y + z->img_mcu_h-1) / z->img_mcu_h;
  1413. for (i=0; i < s->img_n; ++i) {
  1414. // number of effective pixels (e.g. for non-interleaved MCU)
  1415. z->img_comp[i].x = (s->img_x * z->img_comp[i].h + h_max-1) / h_max;
  1416. z->img_comp[i].y = (s->img_y * z->img_comp[i].v + v_max-1) / v_max;
  1417. // to simplify generation, we'll allocate enough memory to decode
  1418. // the bogus oversized data from using interleaved MCUs and their
  1419. // big blocks (e.g. a 16x16 iMCU on an image of width 33); we won't
  1420. // discard the extra data until colorspace conversion
  1421. z->img_comp[i].w2 = z->img_mcu_x * z->img_comp[i].h * 8;
  1422. z->img_comp[i].h2 = z->img_mcu_y * z->img_comp[i].v * 8;
  1423. z->img_comp[i].raw_data = stbi__malloc(z->img_comp[i].w2 * z->img_comp[i].h2+15);
  1424. if (z->img_comp[i].raw_data == NULL) {
  1425. for(--i; i >= 0; --i) {
  1426. free(z->img_comp[i].raw_data);
  1427. z->img_comp[i].data = NULL;
  1428. }
  1429. return stbi__err("outofmem", "Out of memory");
  1430. }
  1431. // align blocks for installable-idct using mmx/sse
  1432. z->img_comp[i].data = (stbi_uc*) (((size_t) z->img_comp[i].raw_data + 15) & ~15);
  1433. z->img_comp[i].linebuf = NULL;
  1434. }
  1435. return 1;
  1436. }
  1437. // use comparisons since in some cases we handle more than one case (e.g. stbi__SOF)
  1438. #define stbi__DNL(x) ((x) == 0xdc)
  1439. #define stbi__SOI(x) ((x) == 0xd8)
  1440. #define stbi__EOI(x) ((x) == 0xd9)
  1441. #define stbi__SOF(x) ((x) == 0xc0 || (x) == 0xc1)
  1442. #define stbi__SOS(x) ((x) == 0xda)
  1443. static int decode_jpeg_header(stbi__jpeg *z, int scan)
  1444. {
  1445. int m;
  1446. z->marker = STBI__MARKER_none; // initialize cached marker to empty
  1447. m = stbi__get_marker(z);
  1448. if (!stbi__SOI(m)) return stbi__err("no stbi__SOI","Corrupt JPEG");
  1449. if (scan == SCAN_type) return 1;
  1450. m = stbi__get_marker(z);
  1451. while (!stbi__SOF(m)) {
  1452. if (!stbi__process_marker(z,m)) return 0;
  1453. m = stbi__get_marker(z);
  1454. while (m == STBI__MARKER_none) {
  1455. // some files have extra padding after their blocks, so ok, we'll scan
  1456. if (stbi__at_eof(z->s)) return stbi__err("no stbi__SOF", "Corrupt JPEG");
  1457. m = stbi__get_marker(z);
  1458. }
  1459. }
  1460. if (!stbi__process_frame_header(z, scan)) return 0;
  1461. return 1;
  1462. }
  1463. static int decode_jpeg_image(stbi__jpeg *j)
  1464. {
  1465. int m;
  1466. j->restart_interval = 0;
  1467. if (!decode_jpeg_header(j, SCAN_load)) return 0;
  1468. m = stbi__get_marker(j);
  1469. while (!stbi__EOI(m)) {
  1470. if (stbi__SOS(m)) {
  1471. if (!stbi__process_scan_header(j)) return 0;
  1472. if (!stbi__parse_entropy_coded_data(j)) return 0;
  1473. if (j->marker == STBI__MARKER_none ) {
  1474. // handle 0s at the end of image data from IP Kamera 9060
  1475. while (!stbi__at_eof(j->s)) {
  1476. int x = stbi__get8(j->s);
  1477. if (x == 255) {
  1478. j->marker = stbi__get8(j->s);
  1479. break;
  1480. } else if (x != 0) {
  1481. return 0;
  1482. }
  1483. }
  1484. // if we reach eof without hitting a marker, stbi__get_marker() below will fail and we'll eventually return 0
  1485. }
  1486. } else {
  1487. if (!stbi__process_marker(j, m)) return 0;
  1488. }
  1489. m = stbi__get_marker(j);
  1490. }
  1491. return 1;
  1492. }
  1493. // static jfif-centered resampling (across block boundaries)
  1494. typedef stbi_uc *(*resample_row_func)(stbi_uc *out, stbi_uc *in0, stbi_uc *in1,
  1495. int w, int hs);
  1496. #define stbi__div4(x) ((stbi_uc) ((x) >> 2))
  1497. static stbi_uc *resample_row_1(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  1498. {
  1499. STBI_NOTUSED(out);
  1500. STBI_NOTUSED(in_far);
  1501. STBI_NOTUSED(w);
  1502. STBI_NOTUSED(hs);
  1503. return in_near;
  1504. }
  1505. static stbi_uc* stbi__resample_row_v_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  1506. {
  1507. // need to generate two samples vertically for every one in input
  1508. int i;
  1509. STBI_NOTUSED(hs);
  1510. for (i=0; i < w; ++i)
  1511. out[i] = stbi__div4(3*in_near[i] + in_far[i] + 2);
  1512. return out;
  1513. }
  1514. static stbi_uc* stbi__resample_row_h_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  1515. {
  1516. // need to generate two samples horizontally for every one in input
  1517. int i;
  1518. stbi_uc *input = in_near;
  1519. if (w == 1) {
  1520. // if only one sample, can't do any interpolation
  1521. out[0] = out[1] = input[0];
  1522. return out;
  1523. }
  1524. out[0] = input[0];
  1525. out[1] = stbi__div4(input[0]*3 + input[1] + 2);
  1526. for (i=1; i < w-1; ++i) {
  1527. int n = 3*input[i]+2;
  1528. out[i*2+0] = stbi__div4(n+input[i-1]);
  1529. out[i*2+1] = stbi__div4(n+input[i+1]);
  1530. }
  1531. out[i*2+0] = stbi__div4(input[w-2]*3 + input[w-1] + 2);
  1532. out[i*2+1] = input[w-1];
  1533. STBI_NOTUSED(in_far);
  1534. STBI_NOTUSED(hs);
  1535. return out;
  1536. }
  1537. #define stbi__div16(x) ((stbi_uc) ((x) >> 4))
  1538. static stbi_uc *stbi__resample_row_hv_2(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  1539. {
  1540. // need to generate 2x2 samples for every one in input
  1541. int i,t0,t1;
  1542. if (w == 1) {
  1543. out[0] = out[1] = stbi__div4(3*in_near[0] + in_far[0] + 2);
  1544. return out;
  1545. }
  1546. t1 = 3*in_near[0] + in_far[0];
  1547. out[0] = stbi__div4(t1+2);
  1548. for (i=1; i < w; ++i) {
  1549. t0 = t1;
  1550. t1 = 3*in_near[i]+in_far[i];
  1551. out[i*2-1] = stbi__div16(3*t0 + t1 + 8);
  1552. out[i*2 ] = stbi__div16(3*t1 + t0 + 8);
  1553. }
  1554. out[w*2-1] = stbi__div4(t1+2);
  1555. STBI_NOTUSED(hs);
  1556. return out;
  1557. }
  1558. static stbi_uc *stbi__resample_row_generic(stbi_uc *out, stbi_uc *in_near, stbi_uc *in_far, int w, int hs)
  1559. {
  1560. // resample with nearest-neighbor
  1561. int i,j;
  1562. STBI_NOTUSED(in_far);
  1563. for (i=0; i < w; ++i)
  1564. for (j=0; j < hs; ++j)
  1565. out[i*hs+j] = in_near[i];
  1566. return out;
  1567. }
  1568. #define float2fixed(x) ((int) ((x) * 65536 + 0.5))
  1569. // 0.38 seconds on 3*anemones.jpg (0.25 with processor = Pro)
  1570. // VC6 without processor=Pro is generating multiple LEAs per multiply!
  1571. 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)
  1572. {
  1573. int i;
  1574. for (i=0; i < count; ++i) {
  1575. int y_fixed = (y[i] << 16) + 32768; // rounding
  1576. int r,g,b;
  1577. int cr = pcr[i] - 128;
  1578. int cb = pcb[i] - 128;
  1579. r = y_fixed + cr*float2fixed(1.40200f);
  1580. g = y_fixed - cr*float2fixed(0.71414f) - cb*float2fixed(0.34414f);
  1581. b = y_fixed + cb*float2fixed(1.77200f);
  1582. r >>= 16;
  1583. g >>= 16;
  1584. b >>= 16;
  1585. if ((unsigned) r > 255) { if (r < 0) r = 0; else r = 255; }
  1586. if ((unsigned) g > 255) { if (g < 0) g = 0; else g = 255; }
  1587. if ((unsigned) b > 255) { if (b < 0) b = 0; else b = 255; }
  1588. out[0] = (stbi_uc)r;
  1589. out[1] = (stbi_uc)g;
  1590. out[2] = (stbi_uc)b;
  1591. out[3] = 255;
  1592. out += step;
  1593. }
  1594. }
  1595. #ifdef STBI_SIMD
  1596. static stbi_YCbCr_to_RGB_run stbi__YCbCr_installed = stbi__YCbCr_to_RGB_row;
  1597. STBIDEF void stbi_install_YCbCr_to_RGB(stbi_YCbCr_to_RGB_run func)
  1598. {
  1599. stbi__YCbCr_installed = func;
  1600. }
  1601. #endif
  1602. // clean up the temporary component buffers
  1603. static void stbi__cleanup_jpeg(stbi__jpeg *j)
  1604. {
  1605. int i;
  1606. for (i=0; i < j->s->img_n; ++i) {
  1607. if (j->img_comp[i].raw_data) {
  1608. free(j->img_comp[i].raw_data);
  1609. j->img_comp[i].raw_data = NULL;
  1610. j->img_comp[i].data = NULL;
  1611. }
  1612. if (j->img_comp[i].linebuf) {
  1613. free(j->img_comp[i].linebuf);
  1614. j->img_comp[i].linebuf = NULL;
  1615. }
  1616. }
  1617. }
  1618. typedef struct
  1619. {
  1620. resample_row_func resample;
  1621. stbi_uc *line0,*line1;
  1622. int hs,vs; // expansion factor in each axis
  1623. int w_lores; // horizontal pixels pre-expansion
  1624. int ystep; // how far through vertical expansion we are
  1625. int ypos; // which pre-expansion row we're on
  1626. } stbi__resample;
  1627. static stbi_uc *load_jpeg_image(stbi__jpeg *z, int *out_x, int *out_y, int *comp, int req_comp)
  1628. {
  1629. int n, decode_n;
  1630. z->s->img_n = 0; // make stbi__cleanup_jpeg safe
  1631. // validate req_comp
  1632. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  1633. // load a jpeg image from whichever source
  1634. if (!decode_jpeg_image(z)) { stbi__cleanup_jpeg(z); return NULL; }
  1635. // determine actual number of components to generate
  1636. n = req_comp ? req_comp : z->s->img_n;
  1637. if (z->s->img_n == 3 && n < 3)
  1638. decode_n = 1;
  1639. else
  1640. decode_n = z->s->img_n;
  1641. // resample and color-convert
  1642. {
  1643. int k;
  1644. unsigned int i,j;
  1645. stbi_uc *output;
  1646. stbi_uc *coutput[4];
  1647. stbi__resample res_comp[4];
  1648. for (k=0; k < decode_n; ++k) {
  1649. stbi__resample *r = &res_comp[k];
  1650. // allocate line buffer big enough for upsampling off the edges
  1651. // with upsample factor of 4
  1652. z->img_comp[k].linebuf = (stbi_uc *) stbi__malloc(z->s->img_x + 3);
  1653. if (!z->img_comp[k].linebuf) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  1654. r->hs = z->img_h_max / z->img_comp[k].h;
  1655. r->vs = z->img_v_max / z->img_comp[k].v;
  1656. r->ystep = r->vs >> 1;
  1657. r->w_lores = (z->s->img_x + r->hs-1) / r->hs;
  1658. r->ypos = 0;
  1659. r->line0 = r->line1 = z->img_comp[k].data;
  1660. if (r->hs == 1 && r->vs == 1) r->resample = resample_row_1;
  1661. else if (r->hs == 1 && r->vs == 2) r->resample = stbi__resample_row_v_2;
  1662. else if (r->hs == 2 && r->vs == 1) r->resample = stbi__resample_row_h_2;
  1663. else if (r->hs == 2 && r->vs == 2) r->resample = stbi__resample_row_hv_2;
  1664. else r->resample = stbi__resample_row_generic;
  1665. }
  1666. // can't error after this so, this is safe
  1667. output = (stbi_uc *) stbi__malloc(n * z->s->img_x * z->s->img_y + 1);
  1668. if (!output) { stbi__cleanup_jpeg(z); return stbi__errpuc("outofmem", "Out of memory"); }
  1669. // now go ahead and resample
  1670. for (j=0; j < z->s->img_y; ++j) {
  1671. stbi_uc *out = output + n * z->s->img_x * j;
  1672. for (k=0; k < decode_n; ++k) {
  1673. stbi__resample *r = &res_comp[k];
  1674. int y_bot = r->ystep >= (r->vs >> 1);
  1675. coutput[k] = r->resample(z->img_comp[k].linebuf,
  1676. y_bot ? r->line1 : r->line0,
  1677. y_bot ? r->line0 : r->line1,
  1678. r->w_lores, r->hs);
  1679. if (++r->ystep >= r->vs) {
  1680. r->ystep = 0;
  1681. r->line0 = r->line1;
  1682. if (++r->ypos < z->img_comp[k].y)
  1683. r->line1 += z->img_comp[k].w2;
  1684. }
  1685. }
  1686. if (n >= 3) {
  1687. stbi_uc *y = coutput[0];
  1688. if (z->s->img_n == 3) {
  1689. #ifdef STBI_SIMD
  1690. stbi__YCbCr_installed(out, y, coutput[1], coutput[2], z->s->img_x, n);
  1691. #else
  1692. stbi__YCbCr_to_RGB_row(out, y, coutput[1], coutput[2], z->s->img_x, n);
  1693. #endif
  1694. } else
  1695. for (i=0; i < z->s->img_x; ++i) {
  1696. out[0] = out[1] = out[2] = y[i];
  1697. out[3] = 255; // not used if n==3
  1698. out += n;
  1699. }
  1700. } else {
  1701. stbi_uc *y = coutput[0];
  1702. if (n == 1)
  1703. for (i=0; i < z->s->img_x; ++i) out[i] = y[i];
  1704. else
  1705. for (i=0; i < z->s->img_x; ++i) *out++ = y[i], *out++ = 255;
  1706. }
  1707. }
  1708. stbi__cleanup_jpeg(z);
  1709. *out_x = z->s->img_x;
  1710. *out_y = z->s->img_y;
  1711. if (comp) *comp = z->s->img_n; // report original components, not output
  1712. return output;
  1713. }
  1714. }
  1715. static unsigned char *stbi__jpeg_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  1716. {
  1717. stbi__jpeg j;
  1718. j.s = s;
  1719. return load_jpeg_image(&j, x,y,comp,req_comp);
  1720. }
  1721. static int stbi__jpeg_test(stbi__context *s)
  1722. {
  1723. int r;
  1724. stbi__jpeg j;
  1725. j.s = s;
  1726. r = decode_jpeg_header(&j, SCAN_type);
  1727. stbi__rewind(s);
  1728. return r;
  1729. }
  1730. static int stbi__jpeg_info_raw(stbi__jpeg *j, int *x, int *y, int *comp)
  1731. {
  1732. if (!decode_jpeg_header(j, SCAN_header)) {
  1733. stbi__rewind( j->s );
  1734. return 0;
  1735. }
  1736. if (x) *x = j->s->img_x;
  1737. if (y) *y = j->s->img_y;
  1738. if (comp) *comp = j->s->img_n;
  1739. return 1;
  1740. }
  1741. static int stbi__jpeg_info(stbi__context *s, int *x, int *y, int *comp)
  1742. {
  1743. stbi__jpeg j;
  1744. j.s = s;
  1745. return stbi__jpeg_info_raw(&j, x, y, comp);
  1746. }
  1747. // public domain zlib decode v0.2 Sean Barrett 2006-11-18
  1748. // simple implementation
  1749. // - all input must be provided in an upfront buffer
  1750. // - all output is written to a single output buffer (can malloc/realloc)
  1751. // performance
  1752. // - fast huffman
  1753. // fast-way is faster to check than jpeg huffman, but slow way is slower
  1754. #define STBI__ZFAST_BITS 9 // accelerate all cases in default tables
  1755. #define STBI__ZFAST_MASK ((1 << STBI__ZFAST_BITS) - 1)
  1756. // zlib-style huffman encoding
  1757. // (jpegs packs from left, zlib from right, so can't share code)
  1758. typedef struct
  1759. {
  1760. stbi__uint16 fast[1 << STBI__ZFAST_BITS];
  1761. stbi__uint16 firstcode[16];
  1762. int maxcode[17];
  1763. stbi__uint16 firstsymbol[16];
  1764. stbi_uc size[288];
  1765. stbi__uint16 value[288];
  1766. } stbi__zhuffman;
  1767. stbi_inline static int stbi__bitreverse16(int n)
  1768. {
  1769. n = ((n & 0xAAAA) >> 1) | ((n & 0x5555) << 1);
  1770. n = ((n & 0xCCCC) >> 2) | ((n & 0x3333) << 2);
  1771. n = ((n & 0xF0F0) >> 4) | ((n & 0x0F0F) << 4);
  1772. n = ((n & 0xFF00) >> 8) | ((n & 0x00FF) << 8);
  1773. return n;
  1774. }
  1775. stbi_inline static int stbi__bit_reverse(int v, int bits)
  1776. {
  1777. STBI_ASSERT(bits <= 16);
  1778. // to bit reverse n bits, reverse 16 and shift
  1779. // e.g. 11 bits, bit reverse and shift away 5
  1780. return stbi__bitreverse16(v) >> (16-bits);
  1781. }
  1782. static int stbi__zbuild_huffman(stbi__zhuffman *z, stbi_uc *sizelist, int num)
  1783. {
  1784. int i,k=0;
  1785. int code, next_code[16], sizes[17];
  1786. // DEFLATE spec for generating codes
  1787. memset(sizes, 0, sizeof(sizes));
  1788. memset(z->fast, 255, sizeof(z->fast));
  1789. for (i=0; i < num; ++i)
  1790. ++sizes[sizelist[i]];
  1791. sizes[0] = 0;
  1792. for (i=1; i < 16; ++i)
  1793. STBI_ASSERT(sizes[i] <= (1 << i));
  1794. code = 0;
  1795. for (i=1; i < 16; ++i) {
  1796. next_code[i] = code;
  1797. z->firstcode[i] = (stbi__uint16) code;
  1798. z->firstsymbol[i] = (stbi__uint16) k;
  1799. code = (code + sizes[i]);
  1800. if (sizes[i])
  1801. if (code-1 >= (1 << i)) return stbi__err("bad codelengths","Corrupt JPEG");
  1802. z->maxcode[i] = code << (16-i); // preshift for inner loop
  1803. code <<= 1;
  1804. k += sizes[i];
  1805. }
  1806. z->maxcode[16] = 0x10000; // sentinel
  1807. for (i=0; i < num; ++i) {
  1808. int s = sizelist[i];
  1809. if (s) {
  1810. int c = next_code[s] - z->firstcode[s] + z->firstsymbol[s];
  1811. z->size [c] = (stbi_uc ) s;
  1812. z->value[c] = (stbi__uint16) i;
  1813. if (s <= STBI__ZFAST_BITS) {
  1814. int k = stbi__bit_reverse(next_code[s],s);
  1815. while (k < (1 << STBI__ZFAST_BITS)) {
  1816. z->fast[k] = (stbi__uint16) c;
  1817. k += (1 << s);
  1818. }
  1819. }
  1820. ++next_code[s];
  1821. }
  1822. }
  1823. return 1;
  1824. }
  1825. // zlib-from-memory implementation for PNG reading
  1826. // because PNG allows splitting the zlib stream arbitrarily,
  1827. // and it's annoying structurally to have PNG call ZLIB call PNG,
  1828. // we require PNG read all the IDATs and combine them into a single
  1829. // memory buffer
  1830. typedef struct
  1831. {
  1832. stbi_uc *zbuffer, *zbuffer_end;
  1833. int num_bits;
  1834. stbi__uint32 code_buffer;
  1835. char *zout;
  1836. char *zout_start;
  1837. char *zout_end;
  1838. int z_expandable;
  1839. stbi__zhuffman z_length, z_distance;
  1840. } stbi__zbuf;
  1841. stbi_inline static stbi_uc stbi__zget8(stbi__zbuf *z)
  1842. {
  1843. if (z->zbuffer >= z->zbuffer_end) return 0;
  1844. return *z->zbuffer++;
  1845. }
  1846. static void stbi__fill_bits(stbi__zbuf *z)
  1847. {
  1848. do {
  1849. STBI_ASSERT(z->code_buffer < (1U << z->num_bits));
  1850. z->code_buffer |= stbi__zget8(z) << z->num_bits;
  1851. z->num_bits += 8;
  1852. } while (z->num_bits <= 24);
  1853. }
  1854. stbi_inline static unsigned int stbi__zreceive(stbi__zbuf *z, int n)
  1855. {
  1856. unsigned int k;
  1857. if (z->num_bits < n) stbi__fill_bits(z);
  1858. k = z->code_buffer & ((1 << n) - 1);
  1859. z->code_buffer >>= n;
  1860. z->num_bits -= n;
  1861. return k;
  1862. }
  1863. stbi_inline static int stbi__zhuffman_decode(stbi__zbuf *a, stbi__zhuffman *z)
  1864. {
  1865. int b,s,k;
  1866. if (a->num_bits < 16) stbi__fill_bits(a);
  1867. b = z->fast[a->code_buffer & STBI__ZFAST_MASK];
  1868. if (b < 0xffff) {
  1869. s = z->size[b];
  1870. a->code_buffer >>= s;
  1871. a->num_bits -= s;
  1872. return z->value[b];
  1873. }
  1874. // not resolved by fast table, so compute it the slow way
  1875. // use jpeg approach, which requires MSbits at top
  1876. k = stbi__bit_reverse(a->code_buffer, 16);
  1877. for (s=STBI__ZFAST_BITS+1; ; ++s)
  1878. if (k < z->maxcode[s])
  1879. break;
  1880. if (s == 16) return -1; // invalid code!
  1881. // code size is s, so:
  1882. b = (k >> (16-s)) - z->firstcode[s] + z->firstsymbol[s];
  1883. STBI_ASSERT(z->size[b] == s);
  1884. a->code_buffer >>= s;
  1885. a->num_bits -= s;
  1886. return z->value[b];
  1887. }
  1888. static int stbi__zexpand(stbi__zbuf *z, int n) // need to make room for n bytes
  1889. {
  1890. char *q;
  1891. int cur, limit;
  1892. if (!z->z_expandable) return stbi__err("output buffer limit","Corrupt PNG");
  1893. cur = (int) (z->zout - z->zout_start);
  1894. limit = (int) (z->zout_end - z->zout_start);
  1895. while (cur + n > limit)
  1896. limit *= 2;
  1897. q = (char *) realloc(z->zout_start, limit);
  1898. if (q == NULL) return stbi__err("outofmem", "Out of memory");
  1899. z->zout_start = q;
  1900. z->zout = q + cur;
  1901. z->zout_end = q + limit;
  1902. return 1;
  1903. }
  1904. static int stbi__zlength_base[31] = {
  1905. 3,4,5,6,7,8,9,10,11,13,
  1906. 15,17,19,23,27,31,35,43,51,59,
  1907. 67,83,99,115,131,163,195,227,258,0,0 };
  1908. static int stbi__zlength_extra[31]=
  1909. { 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 };
  1910. static int stbi__zdist_base[32] = { 1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,
  1911. 257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0};
  1912. static int stbi__zdist_extra[32] =
  1913. { 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};
  1914. static int stbi__parse_huffman_block(stbi__zbuf *a)
  1915. {
  1916. for(;;) {
  1917. int z = stbi__zhuffman_decode(a, &a->z_length);
  1918. if (z < 256) {
  1919. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG"); // error in huffman codes
  1920. if (a->zout >= a->zout_end) if (!stbi__zexpand(a, 1)) return 0;
  1921. *a->zout++ = (char) z;
  1922. } else {
  1923. stbi_uc *p;
  1924. int len,dist;
  1925. if (z == 256) return 1;
  1926. z -= 257;
  1927. len = stbi__zlength_base[z];
  1928. if (stbi__zlength_extra[z]) len += stbi__zreceive(a, stbi__zlength_extra[z]);
  1929. z = stbi__zhuffman_decode(a, &a->z_distance);
  1930. if (z < 0) return stbi__err("bad huffman code","Corrupt PNG");
  1931. dist = stbi__zdist_base[z];
  1932. if (stbi__zdist_extra[z]) dist += stbi__zreceive(a, stbi__zdist_extra[z]);
  1933. if (a->zout - a->zout_start < dist) return stbi__err("bad dist","Corrupt PNG");
  1934. if (a->zout + len > a->zout_end) if (!stbi__zexpand(a, len)) return 0;
  1935. p = (stbi_uc *) (a->zout - dist);
  1936. while (len--)
  1937. *a->zout++ = *p++;
  1938. }
  1939. }
  1940. }
  1941. static int stbi__compute_huffman_codes(stbi__zbuf *a)
  1942. {
  1943. 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 };
  1944. stbi__zhuffman z_codelength;
  1945. stbi_uc lencodes[286+32+137];//padding for maximum single op
  1946. stbi_uc codelength_sizes[19];
  1947. int i,n;
  1948. int hlit = stbi__zreceive(a,5) + 257;
  1949. int hdist = stbi__zreceive(a,5) + 1;
  1950. int hclen = stbi__zreceive(a,4) + 4;
  1951. memset(codelength_sizes, 0, sizeof(codelength_sizes));
  1952. for (i=0; i < hclen; ++i) {
  1953. int s = stbi__zreceive(a,3);
  1954. codelength_sizes[length_dezigzag[i]] = (stbi_uc) s;
  1955. }
  1956. if (!stbi__zbuild_huffman(&z_codelength, codelength_sizes, 19)) return 0;
  1957. n = 0;
  1958. while (n < hlit + hdist) {
  1959. int c = stbi__zhuffman_decode(a, &z_codelength);
  1960. STBI_ASSERT(c >= 0 && c < 19);
  1961. if (c < 16)
  1962. lencodes[n++] = (stbi_uc) c;
  1963. else if (c == 16) {
  1964. c = stbi__zreceive(a,2)+3;
  1965. memset(lencodes+n, lencodes[n-1], c);
  1966. n += c;
  1967. } else if (c == 17) {
  1968. c = stbi__zreceive(a,3)+3;
  1969. memset(lencodes+n, 0, c);
  1970. n += c;
  1971. } else {
  1972. STBI_ASSERT(c == 18);
  1973. c = stbi__zreceive(a,7)+11;
  1974. memset(lencodes+n, 0, c);
  1975. n += c;
  1976. }
  1977. }
  1978. if (n != hlit+hdist) return stbi__err("bad codelengths","Corrupt PNG");
  1979. if (!stbi__zbuild_huffman(&a->z_length, lencodes, hlit)) return 0;
  1980. if (!stbi__zbuild_huffman(&a->z_distance, lencodes+hlit, hdist)) return 0;
  1981. return 1;
  1982. }
  1983. static int stbi__parse_uncomperssed_block(stbi__zbuf *a)
  1984. {
  1985. stbi_uc header[4];
  1986. int len,nlen,k;
  1987. if (a->num_bits & 7)
  1988. stbi__zreceive(a, a->num_bits & 7); // discard
  1989. // drain the bit-packed data into header
  1990. k = 0;
  1991. while (a->num_bits > 0) {
  1992. header[k++] = (stbi_uc) (a->code_buffer & 255); // suppress MSVC run-time check
  1993. a->code_buffer >>= 8;
  1994. a->num_bits -= 8;
  1995. }
  1996. STBI_ASSERT(a->num_bits == 0);
  1997. // now fill header the normal way
  1998. while (k < 4)
  1999. header[k++] = stbi__zget8(a);
  2000. len = header[1] * 256 + header[0];
  2001. nlen = header[3] * 256 + header[2];
  2002. if (nlen != (len ^ 0xffff)) return stbi__err("zlib corrupt","Corrupt PNG");
  2003. if (a->zbuffer + len > a->zbuffer_end) return stbi__err("read past buffer","Corrupt PNG");
  2004. if (a->zout + len > a->zout_end)
  2005. if (!stbi__zexpand(a, len)) return 0;
  2006. memcpy(a->zout, a->zbuffer, len);
  2007. a->zbuffer += len;
  2008. a->zout += len;
  2009. return 1;
  2010. }
  2011. static int stbi__parse_zlib_header(stbi__zbuf *a)
  2012. {
  2013. int cmf = stbi__zget8(a);
  2014. int cm = cmf & 15;
  2015. /* int cinfo = cmf >> 4; */
  2016. int flg = stbi__zget8(a);
  2017. if ((cmf*256+flg) % 31 != 0) return stbi__err("bad zlib header","Corrupt PNG"); // zlib spec
  2018. if (flg & 32) return stbi__err("no preset dict","Corrupt PNG"); // preset dictionary not allowed in png
  2019. if (cm != 8) return stbi__err("bad compression","Corrupt PNG"); // DEFLATE required for png
  2020. // window = 1 << (8 + cinfo)... but who cares, we fully buffer output
  2021. return 1;
  2022. }
  2023. // @TODO: should statically initialize these for optimal thread safety
  2024. static stbi_uc stbi__zdefault_length[288], stbi__zdefault_distance[32];
  2025. static void stbi__init_zdefaults(void)
  2026. {
  2027. int i; // use <= to match clearly with spec
  2028. for (i=0; i <= 143; ++i) stbi__zdefault_length[i] = 8;
  2029. for ( ; i <= 255; ++i) stbi__zdefault_length[i] = 9;
  2030. for ( ; i <= 279; ++i) stbi__zdefault_length[i] = 7;
  2031. for ( ; i <= 287; ++i) stbi__zdefault_length[i] = 8;
  2032. for (i=0; i <= 31; ++i) stbi__zdefault_distance[i] = 5;
  2033. }
  2034. static int stbi__parse_zlib(stbi__zbuf *a, int parse_header)
  2035. {
  2036. int final, type;
  2037. if (parse_header)
  2038. if (!stbi__parse_zlib_header(a)) return 0;
  2039. a->num_bits = 0;
  2040. a->code_buffer = 0;
  2041. do {
  2042. final = stbi__zreceive(a,1);
  2043. type = stbi__zreceive(a,2);
  2044. if (type == 0) {
  2045. if (!stbi__parse_uncomperssed_block(a)) return 0;
  2046. } else if (type == 3) {
  2047. return 0;
  2048. } else {
  2049. if (type == 1) {
  2050. // use fixed code lengths
  2051. if (!stbi__zdefault_distance[31]) stbi__init_zdefaults();
  2052. if (!stbi__zbuild_huffman(&a->z_length , stbi__zdefault_length , 288)) return 0;
  2053. if (!stbi__zbuild_huffman(&a->z_distance, stbi__zdefault_distance, 32)) return 0;
  2054. } else {
  2055. if (!stbi__compute_huffman_codes(a)) return 0;
  2056. }
  2057. if (!stbi__parse_huffman_block(a)) return 0;
  2058. }
  2059. } while (!final);
  2060. return 1;
  2061. }
  2062. static int stbi__do_zlib(stbi__zbuf *a, char *obuf, int olen, int exp, int parse_header)
  2063. {
  2064. a->zout_start = obuf;
  2065. a->zout = obuf;
  2066. a->zout_end = obuf + olen;
  2067. a->z_expandable = exp;
  2068. return stbi__parse_zlib(a, parse_header);
  2069. }
  2070. STBIDEF char *stbi_zlib_decode_malloc_guesssize(const char *buffer, int len, int initial_size, int *outlen)
  2071. {
  2072. stbi__zbuf a;
  2073. char *p = (char *) stbi__malloc(initial_size);
  2074. if (p == NULL) return NULL;
  2075. a.zbuffer = (stbi_uc *) buffer;
  2076. a.zbuffer_end = (stbi_uc *) buffer + len;
  2077. if (stbi__do_zlib(&a, p, initial_size, 1, 1)) {
  2078. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2079. return a.zout_start;
  2080. } else {
  2081. free(a.zout_start);
  2082. return NULL;
  2083. }
  2084. }
  2085. STBIDEF char *stbi_zlib_decode_malloc(char const *buffer, int len, int *outlen)
  2086. {
  2087. return stbi_zlib_decode_malloc_guesssize(buffer, len, 16384, outlen);
  2088. }
  2089. STBIDEF char *stbi_zlib_decode_malloc_guesssize_headerflag(const char *buffer, int len, int initial_size, int *outlen, int parse_header)
  2090. {
  2091. stbi__zbuf a;
  2092. char *p = (char *) stbi__malloc(initial_size);
  2093. if (p == NULL) return NULL;
  2094. a.zbuffer = (stbi_uc *) buffer;
  2095. a.zbuffer_end = (stbi_uc *) buffer + len;
  2096. if (stbi__do_zlib(&a, p, initial_size, 1, parse_header)) {
  2097. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2098. return a.zout_start;
  2099. } else {
  2100. free(a.zout_start);
  2101. return NULL;
  2102. }
  2103. }
  2104. STBIDEF int stbi_zlib_decode_buffer(char *obuffer, int olen, char const *ibuffer, int ilen)
  2105. {
  2106. stbi__zbuf a;
  2107. a.zbuffer = (stbi_uc *) ibuffer;
  2108. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  2109. if (stbi__do_zlib(&a, obuffer, olen, 0, 1))
  2110. return (int) (a.zout - a.zout_start);
  2111. else
  2112. return -1;
  2113. }
  2114. STBIDEF char *stbi_zlib_decode_noheader_malloc(char const *buffer, int len, int *outlen)
  2115. {
  2116. stbi__zbuf a;
  2117. char *p = (char *) stbi__malloc(16384);
  2118. if (p == NULL) return NULL;
  2119. a.zbuffer = (stbi_uc *) buffer;
  2120. a.zbuffer_end = (stbi_uc *) buffer+len;
  2121. if (stbi__do_zlib(&a, p, 16384, 1, 0)) {
  2122. if (outlen) *outlen = (int) (a.zout - a.zout_start);
  2123. return a.zout_start;
  2124. } else {
  2125. free(a.zout_start);
  2126. return NULL;
  2127. }
  2128. }
  2129. STBIDEF int stbi_zlib_decode_noheader_buffer(char *obuffer, int olen, const char *ibuffer, int ilen)
  2130. {
  2131. stbi__zbuf a;
  2132. a.zbuffer = (stbi_uc *) ibuffer;
  2133. a.zbuffer_end = (stbi_uc *) ibuffer + ilen;
  2134. if (stbi__do_zlib(&a, obuffer, olen, 0, 0))
  2135. return (int) (a.zout - a.zout_start);
  2136. else
  2137. return -1;
  2138. }
  2139. // public domain "baseline" PNG decoder v0.10 Sean Barrett 2006-11-18
  2140. // simple implementation
  2141. // - only 8-bit samples
  2142. // - no CRC checking
  2143. // - allocates lots of intermediate memory
  2144. // - avoids problem of streaming data between subsystems
  2145. // - avoids explicit window management
  2146. // performance
  2147. // - uses stb_zlib, a PD zlib implementation with fast huffman decoding
  2148. typedef struct
  2149. {
  2150. stbi__uint32 length;
  2151. stbi__uint32 type;
  2152. } stbi__pngchunk;
  2153. #define PNG_TYPE(a,b,c,d) (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
  2154. static stbi__pngchunk stbi__get_chunk_header(stbi__context *s)
  2155. {
  2156. stbi__pngchunk c;
  2157. c.length = stbi__get32be(s);
  2158. c.type = stbi__get32be(s);
  2159. return c;
  2160. }
  2161. static int stbi__check_png_header(stbi__context *s)
  2162. {
  2163. static stbi_uc png_sig[8] = { 137,80,78,71,13,10,26,10 };
  2164. int i;
  2165. for (i=0; i < 8; ++i)
  2166. if (stbi__get8(s) != png_sig[i]) return stbi__err("bad png sig","Not a PNG");
  2167. return 1;
  2168. }
  2169. typedef struct
  2170. {
  2171. stbi__context *s;
  2172. stbi_uc *idata, *expanded, *out;
  2173. } stbi__png;
  2174. enum {
  2175. STBI__F_none=0, STBI__F_sub=1, STBI__F_up=2, STBI__F_avg=3, STBI__F_paeth=4,
  2176. STBI__F_avg_first, STBI__F_paeth_first
  2177. };
  2178. static stbi_uc first_row_filter[5] =
  2179. {
  2180. STBI__F_none, STBI__F_sub, STBI__F_none, STBI__F_avg_first, STBI__F_paeth_first
  2181. };
  2182. static int stbi__paeth(int a, int b, int c)
  2183. {
  2184. int p = a + b - c;
  2185. int pa = abs(p-a);
  2186. int pb = abs(p-b);
  2187. int pc = abs(p-c);
  2188. if (pa <= pb && pa <= pc) return a;
  2189. if (pb <= pc) return b;
  2190. return c;
  2191. }
  2192. #define STBI__BYTECAST(x) ((stbi_uc) ((x) & 255)) // truncate int to byte without warnings
  2193. // create the png data from post-deflated data
  2194. 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)
  2195. {
  2196. stbi__context *s = a->s;
  2197. stbi__uint32 i,j,stride = x*out_n;
  2198. stbi__uint32 img_len;
  2199. int k;
  2200. int img_n = s->img_n; // copy it into a local for later
  2201. stbi_uc* line8 = NULL; // point into raw when depth==8 else temporary local buffer
  2202. STBI_ASSERT(out_n == s->img_n || out_n == s->img_n+1);
  2203. a->out = (stbi_uc *) stbi__malloc(x * y * out_n);
  2204. if (!a->out) return stbi__err("outofmem", "Out of memory");
  2205. img_len = ((((img_n * x * depth) + 7) >> 3) + 1) * y;
  2206. if (s->img_x == x && s->img_y == y) {
  2207. if (raw_len != img_len) return stbi__err("not enough pixels","Corrupt PNG");
  2208. } else { // interlaced:
  2209. if (raw_len < img_len) return stbi__err("not enough pixels","Corrupt PNG");
  2210. }
  2211. if (depth != 8) {
  2212. line8 = (stbi_uc *) stbi__malloc((x+7) * out_n); // allocate buffer for one scanline
  2213. if (!line8) return stbi__err("outofmem", "Out of memory");
  2214. }
  2215. for (j=0; j < y; ++j) {
  2216. stbi_uc *in;
  2217. stbi_uc *cur = a->out + stride*j;
  2218. stbi_uc *prior = cur - stride;
  2219. int filter = *raw++;
  2220. if (filter > 4) {
  2221. if (depth != 8) free(line8);
  2222. return stbi__err("invalid filter","Corrupt PNG");
  2223. }
  2224. if (depth == 8) {
  2225. in = raw;
  2226. raw += x*img_n;
  2227. }
  2228. else {
  2229. // 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
  2230. // 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
  2231. in = line8;
  2232. stbi_uc* decode_out = line8;
  2233. stbi_uc scale = (color == 0) ? 0xFF/((1<<depth)-1) : 1; // scale grayscale values to 0..255 range
  2234. if (depth == 4) {
  2235. for (k=x*img_n; k >= 1; k-=2, raw++) {
  2236. *decode_out++ = scale * ((*raw >> 4) );
  2237. *decode_out++ = scale * ((*raw ) & 0x0f);
  2238. }
  2239. } else if (depth == 2) {
  2240. for (k=x*img_n; k >= 1; k-=4, raw++) {
  2241. *decode_out++ = scale * ((*raw >> 6) );
  2242. *decode_out++ = scale * ((*raw >> 4) & 0x03);
  2243. *decode_out++ = scale * ((*raw >> 2) & 0x03);
  2244. *decode_out++ = scale * ((*raw ) & 0x03);
  2245. }
  2246. } else if (depth == 1) {
  2247. for (k=x*img_n; k >= 1; k-=8, raw++) {
  2248. *decode_out++ = scale * ((*raw >> 7) );
  2249. *decode_out++ = scale * ((*raw >> 6) & 0x01);
  2250. *decode_out++ = scale * ((*raw >> 5) & 0x01);
  2251. *decode_out++ = scale * ((*raw >> 4) & 0x01);
  2252. *decode_out++ = scale * ((*raw >> 3) & 0x01);
  2253. *decode_out++ = scale * ((*raw >> 2) & 0x01);
  2254. *decode_out++ = scale * ((*raw >> 1) & 0x01);
  2255. *decode_out++ = scale * ((*raw ) & 0x01);
  2256. }
  2257. }
  2258. }
  2259. // if first row, use special filter that doesn't sample previous row
  2260. if (j == 0) filter = first_row_filter[filter];
  2261. // handle first pixel explicitly
  2262. for (k=0; k < img_n; ++k) {
  2263. switch (filter) {
  2264. case STBI__F_none : cur[k] = in[k]; break;
  2265. case STBI__F_sub : cur[k] = in[k]; break;
  2266. case STBI__F_up : cur[k] = STBI__BYTECAST(in[k] + prior[k]); break;
  2267. case STBI__F_avg : cur[k] = STBI__BYTECAST(in[k] + (prior[k]>>1)); break;
  2268. case STBI__F_paeth : cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(0,prior[k],0)); break;
  2269. case STBI__F_avg_first : cur[k] = in[k]; break;
  2270. case STBI__F_paeth_first: cur[k] = in[k]; break;
  2271. }
  2272. }
  2273. if (img_n != out_n) cur[img_n] = 255;
  2274. in += img_n;
  2275. cur += out_n;
  2276. prior += out_n;
  2277. // this is a little gross, so that we don't switch per-pixel or per-component
  2278. if (img_n == out_n) {
  2279. #define CASE(f) \
  2280. case f: \
  2281. for (i=x-1; i >= 1; --i, in+=img_n,cur+=img_n,prior+=img_n) \
  2282. for (k=0; k < img_n; ++k)
  2283. switch (filter) {
  2284. CASE(STBI__F_none) cur[k] = in[k]; break;
  2285. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(in[k] + cur[k-img_n]); break;
  2286. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(in[k] + prior[k]); break;
  2287. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(in[k] + ((prior[k] + cur[k-img_n])>>1)); break;
  2288. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-img_n],prior[k],prior[k-img_n])); break;
  2289. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(in[k] + (cur[k-img_n] >> 1)); break;
  2290. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-img_n],0,0)); break;
  2291. }
  2292. #undef CASE
  2293. } else {
  2294. STBI_ASSERT(img_n+1 == out_n);
  2295. #define CASE(f) \
  2296. case f: \
  2297. for (i=x-1; i >= 1; --i, cur[img_n]=255,in+=img_n,cur+=out_n,prior+=out_n) \
  2298. for (k=0; k < img_n; ++k)
  2299. switch (filter) {
  2300. CASE(STBI__F_none) cur[k] = in[k]; break;
  2301. CASE(STBI__F_sub) cur[k] = STBI__BYTECAST(in[k] + cur[k-out_n]); break;
  2302. CASE(STBI__F_up) cur[k] = STBI__BYTECAST(in[k] + prior[k]); break;
  2303. CASE(STBI__F_avg) cur[k] = STBI__BYTECAST(in[k] + ((prior[k] + cur[k-out_n])>>1)); break;
  2304. CASE(STBI__F_paeth) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-out_n],prior[k],prior[k-out_n])); break;
  2305. CASE(STBI__F_avg_first) cur[k] = STBI__BYTECAST(in[k] + (cur[k-out_n] >> 1)); break;
  2306. CASE(STBI__F_paeth_first) cur[k] = STBI__BYTECAST(in[k] + stbi__paeth(cur[k-out_n],0,0)); break;
  2307. }
  2308. #undef CASE
  2309. }
  2310. }
  2311. if (depth != 8) free(line8);
  2312. return 1;
  2313. }
  2314. static int stbi__create_png_image(stbi__png *a, stbi_uc *raw, stbi__uint32 raw_len, int out_n, int depth, int color, int interlaced)
  2315. {
  2316. stbi_uc *final;
  2317. int p;
  2318. if (!interlaced)
  2319. return stbi__create_png_image_raw(a, raw, raw_len, out_n, a->s->img_x, a->s->img_y, depth, color);
  2320. // de-interlacing
  2321. final = (stbi_uc *) stbi__malloc(a->s->img_x * a->s->img_y * out_n);
  2322. for (p=0; p < 7; ++p) {
  2323. int xorig[] = { 0,4,0,2,0,1,0 };
  2324. int yorig[] = { 0,0,4,0,2,0,1 };
  2325. int xspc[] = { 8,8,4,4,2,2,1 };
  2326. int yspc[] = { 8,8,8,4,4,2,2 };
  2327. int i,j,x,y;
  2328. // pass1_x[4] = 0, pass1_x[5] = 1, pass1_x[12] = 1
  2329. x = (a->s->img_x - xorig[p] + xspc[p]-1) / xspc[p];
  2330. y = (a->s->img_y - yorig[p] + yspc[p]-1) / yspc[p];
  2331. if (x && y) {
  2332. stbi__uint32 img_len = ((((out_n * x * depth) + 7) >> 3) + 1) * y;
  2333. if (!stbi__create_png_image_raw(a, raw, raw_len, out_n, x, y, depth, color)) {
  2334. free(final);
  2335. return 0;
  2336. }
  2337. for (j=0; j < y; ++j)
  2338. for (i=0; i < x; ++i)
  2339. memcpy(final + (j*yspc[p]+yorig[p])*a->s->img_x*out_n + (i*xspc[p]+xorig[p])*out_n,
  2340. a->out + (j*x+i)*out_n, out_n);
  2341. free(a->out);
  2342. raw += img_len;
  2343. raw_len -= img_len;
  2344. }
  2345. }
  2346. a->out = final;
  2347. return 1;
  2348. }
  2349. static int stbi__compute_transparency(stbi__png *z, stbi_uc tc[3], int out_n)
  2350. {
  2351. stbi__context *s = z->s;
  2352. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  2353. stbi_uc *p = z->out;
  2354. // compute color-based transparency, assuming we've
  2355. // already got 255 as the alpha value in the output
  2356. STBI_ASSERT(out_n == 2 || out_n == 4);
  2357. if (out_n == 2) {
  2358. for (i=0; i < pixel_count; ++i) {
  2359. p[1] = (p[0] == tc[0] ? 0 : 255);
  2360. p += 2;
  2361. }
  2362. } else {
  2363. for (i=0; i < pixel_count; ++i) {
  2364. if (p[0] == tc[0] && p[1] == tc[1] && p[2] == tc[2])
  2365. p[3] = 0;
  2366. p += 4;
  2367. }
  2368. }
  2369. return 1;
  2370. }
  2371. static int stbi__expand_png_palette(stbi__png *a, stbi_uc *palette, int len, int pal_img_n)
  2372. {
  2373. stbi__uint32 i, pixel_count = a->s->img_x * a->s->img_y;
  2374. stbi_uc *p, *temp_out, *orig = a->out;
  2375. p = (stbi_uc *) stbi__malloc(pixel_count * pal_img_n);
  2376. if (p == NULL) return stbi__err("outofmem", "Out of memory");
  2377. // between here and free(out) below, exitting would leak
  2378. temp_out = p;
  2379. if (pal_img_n == 3) {
  2380. for (i=0; i < pixel_count; ++i) {
  2381. int n = orig[i]*4;
  2382. p[0] = palette[n ];
  2383. p[1] = palette[n+1];
  2384. p[2] = palette[n+2];
  2385. p += 3;
  2386. }
  2387. } else {
  2388. for (i=0; i < pixel_count; ++i) {
  2389. int n = orig[i]*4;
  2390. p[0] = palette[n ];
  2391. p[1] = palette[n+1];
  2392. p[2] = palette[n+2];
  2393. p[3] = palette[n+3];
  2394. p += 4;
  2395. }
  2396. }
  2397. free(a->out);
  2398. a->out = temp_out;
  2399. STBI_NOTUSED(len);
  2400. return 1;
  2401. }
  2402. static int stbi__unpremultiply_on_load = 0;
  2403. static int stbi__de_iphone_flag = 0;
  2404. STBIDEF void stbi_set_unpremultiply_on_load(int flag_true_if_should_unpremultiply)
  2405. {
  2406. stbi__unpremultiply_on_load = flag_true_if_should_unpremultiply;
  2407. }
  2408. STBIDEF void stbi_convert_iphone_png_to_rgb(int flag_true_if_should_convert)
  2409. {
  2410. stbi__de_iphone_flag = flag_true_if_should_convert;
  2411. }
  2412. static void stbi__de_iphone(stbi__png *z)
  2413. {
  2414. stbi__context *s = z->s;
  2415. stbi__uint32 i, pixel_count = s->img_x * s->img_y;
  2416. stbi_uc *p = z->out;
  2417. if (s->img_out_n == 3) { // convert bgr to rgb
  2418. for (i=0; i < pixel_count; ++i) {
  2419. stbi_uc t = p[0];
  2420. p[0] = p[2];
  2421. p[2] = t;
  2422. p += 3;
  2423. }
  2424. } else {
  2425. STBI_ASSERT(s->img_out_n == 4);
  2426. if (stbi__unpremultiply_on_load) {
  2427. // convert bgr to rgb and unpremultiply
  2428. for (i=0; i < pixel_count; ++i) {
  2429. stbi_uc a = p[3];
  2430. stbi_uc t = p[0];
  2431. if (a) {
  2432. p[0] = p[2] * 255 / a;
  2433. p[1] = p[1] * 255 / a;
  2434. p[2] = t * 255 / a;
  2435. } else {
  2436. p[0] = p[2];
  2437. p[2] = t;
  2438. }
  2439. p += 4;
  2440. }
  2441. } else {
  2442. // convert bgr to rgb
  2443. for (i=0; i < pixel_count; ++i) {
  2444. stbi_uc t = p[0];
  2445. p[0] = p[2];
  2446. p[2] = t;
  2447. p += 4;
  2448. }
  2449. }
  2450. }
  2451. }
  2452. static int stbi__parse_png_file(stbi__png *z, int scan, int req_comp)
  2453. {
  2454. stbi_uc palette[1024], pal_img_n=0;
  2455. stbi_uc has_trans=0, tc[3];
  2456. stbi__uint32 ioff=0, idata_limit=0, i, pal_len=0;
  2457. int first=1,k,interlace=0, color=0, depth=0, is_iphone=0;
  2458. stbi__context *s = z->s;
  2459. z->expanded = NULL;
  2460. z->idata = NULL;
  2461. z->out = NULL;
  2462. if (!stbi__check_png_header(s)) return 0;
  2463. if (scan == SCAN_type) return 1;
  2464. for (;;) {
  2465. stbi__pngchunk c = stbi__get_chunk_header(s);
  2466. switch (c.type) {
  2467. case PNG_TYPE('C','g','B','I'):
  2468. is_iphone = 1;
  2469. stbi__skip(s, c.length);
  2470. break;
  2471. case PNG_TYPE('I','H','D','R'): {
  2472. int comp,filter;
  2473. if (!first) return stbi__err("multiple IHDR","Corrupt PNG");
  2474. first = 0;
  2475. if (c.length != 13) return stbi__err("bad IHDR len","Corrupt PNG");
  2476. s->img_x = stbi__get32be(s); if (s->img_x > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  2477. s->img_y = stbi__get32be(s); if (s->img_y > (1 << 24)) return stbi__err("too large","Very large image (corrupt?)");
  2478. 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");
  2479. color = stbi__get8(s); if (color > 6) return stbi__err("bad ctype","Corrupt PNG");
  2480. if (color == 3) pal_img_n = 3; else if (color & 1) return stbi__err("bad ctype","Corrupt PNG");
  2481. comp = stbi__get8(s); if (comp) return stbi__err("bad comp method","Corrupt PNG");
  2482. filter= stbi__get8(s); if (filter) return stbi__err("bad filter method","Corrupt PNG");
  2483. interlace = stbi__get8(s); if (interlace>1) return stbi__err("bad interlace method","Corrupt PNG");
  2484. if (!s->img_x || !s->img_y) return stbi__err("0-pixel image","Corrupt PNG");
  2485. if (!pal_img_n) {
  2486. s->img_n = (color & 2 ? 3 : 1) + (color & 4 ? 1 : 0);
  2487. if ((1 << 30) / s->img_x / s->img_n < s->img_y) return stbi__err("too large", "Image too large to decode");
  2488. if (scan == SCAN_header) return 1;
  2489. } else {
  2490. // if paletted, then pal_n is our final components, and
  2491. // img_n is # components to decompress/filter.
  2492. s->img_n = 1;
  2493. if ((1 << 30) / s->img_x / 4 < s->img_y) return stbi__err("too large","Corrupt PNG");
  2494. // if SCAN_header, have to scan to see if we have a tRNS
  2495. }
  2496. break;
  2497. }
  2498. case PNG_TYPE('P','L','T','E'): {
  2499. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2500. if (c.length > 256*3) return stbi__err("invalid PLTE","Corrupt PNG");
  2501. pal_len = c.length / 3;
  2502. if (pal_len * 3 != c.length) return stbi__err("invalid PLTE","Corrupt PNG");
  2503. for (i=0; i < pal_len; ++i) {
  2504. palette[i*4+0] = stbi__get8(s);
  2505. palette[i*4+1] = stbi__get8(s);
  2506. palette[i*4+2] = stbi__get8(s);
  2507. palette[i*4+3] = 255;
  2508. }
  2509. break;
  2510. }
  2511. case PNG_TYPE('t','R','N','S'): {
  2512. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2513. if (z->idata) return stbi__err("tRNS after IDAT","Corrupt PNG");
  2514. if (pal_img_n) {
  2515. if (scan == SCAN_header) { s->img_n = 4; return 1; }
  2516. if (pal_len == 0) return stbi__err("tRNS before PLTE","Corrupt PNG");
  2517. if (c.length > pal_len) return stbi__err("bad tRNS len","Corrupt PNG");
  2518. pal_img_n = 4;
  2519. for (i=0; i < c.length; ++i)
  2520. palette[i*4+3] = stbi__get8(s);
  2521. } else {
  2522. if (!(s->img_n & 1)) return stbi__err("tRNS with alpha","Corrupt PNG");
  2523. if (c.length != (stbi__uint32) s->img_n*2) return stbi__err("bad tRNS len","Corrupt PNG");
  2524. has_trans = 1;
  2525. for (k=0; k < s->img_n; ++k)
  2526. tc[k] = (stbi_uc) (stbi__get16be(s) & 255); // non 8-bit images will be larger
  2527. }
  2528. break;
  2529. }
  2530. case PNG_TYPE('I','D','A','T'): {
  2531. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2532. if (pal_img_n && !pal_len) return stbi__err("no PLTE","Corrupt PNG");
  2533. if (scan == SCAN_header) { s->img_n = pal_img_n; return 1; }
  2534. if (ioff + c.length > idata_limit) {
  2535. stbi_uc *p;
  2536. if (idata_limit == 0) idata_limit = c.length > 4096 ? c.length : 4096;
  2537. while (ioff + c.length > idata_limit)
  2538. idata_limit *= 2;
  2539. p = (stbi_uc *) realloc(z->idata, idata_limit); if (p == NULL) return stbi__err("outofmem", "Out of memory");
  2540. z->idata = p;
  2541. }
  2542. if (!stbi__getn(s, z->idata+ioff,c.length)) return stbi__err("outofdata","Corrupt PNG");
  2543. ioff += c.length;
  2544. break;
  2545. }
  2546. case PNG_TYPE('I','E','N','D'): {
  2547. stbi__uint32 raw_len;
  2548. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2549. if (scan != SCAN_load) return 1;
  2550. if (z->idata == NULL) return stbi__err("no IDAT","Corrupt PNG");
  2551. z->expanded = (stbi_uc *) stbi_zlib_decode_malloc_guesssize_headerflag((char *) z->idata, ioff, 16384, (int *) &raw_len, !is_iphone);
  2552. if (z->expanded == NULL) return 0; // zlib should set error
  2553. free(z->idata); z->idata = NULL;
  2554. if ((req_comp == s->img_n+1 && req_comp != 3 && !pal_img_n) || has_trans)
  2555. s->img_out_n = s->img_n+1;
  2556. else
  2557. s->img_out_n = s->img_n;
  2558. if (!stbi__create_png_image(z, z->expanded, raw_len, s->img_out_n, depth, color, interlace)) return 0;
  2559. if (has_trans)
  2560. if (!stbi__compute_transparency(z, tc, s->img_out_n)) return 0;
  2561. if (is_iphone && stbi__de_iphone_flag && s->img_out_n > 2)
  2562. stbi__de_iphone(z);
  2563. if (pal_img_n) {
  2564. // pal_img_n == 3 or 4
  2565. s->img_n = pal_img_n; // record the actual colors we had
  2566. s->img_out_n = pal_img_n;
  2567. if (req_comp >= 3) s->img_out_n = req_comp;
  2568. if (!stbi__expand_png_palette(z, palette, pal_len, s->img_out_n))
  2569. return 0;
  2570. }
  2571. free(z->expanded); z->expanded = NULL;
  2572. return 1;
  2573. }
  2574. default:
  2575. // if critical, fail
  2576. if (first) return stbi__err("first not IHDR", "Corrupt PNG");
  2577. if ((c.type & (1 << 29)) == 0) {
  2578. #ifndef STBI_NO_FAILURE_STRINGS
  2579. // not threadsafe
  2580. static char invalid_chunk[] = "XXXX PNG chunk not known";
  2581. invalid_chunk[0] = STBI__BYTECAST(c.type >> 24);
  2582. invalid_chunk[1] = STBI__BYTECAST(c.type >> 16);
  2583. invalid_chunk[2] = STBI__BYTECAST(c.type >> 8);
  2584. invalid_chunk[3] = STBI__BYTECAST(c.type >> 0);
  2585. #endif
  2586. return stbi__err(invalid_chunk, "PNG not supported: unknown PNG chunk type");
  2587. }
  2588. stbi__skip(s, c.length);
  2589. break;
  2590. }
  2591. // end of PNG chunk, read and skip CRC
  2592. stbi__get32be(s);
  2593. }
  2594. }
  2595. static unsigned char *stbi__do_png(stbi__png *p, int *x, int *y, int *n, int req_comp)
  2596. {
  2597. unsigned char *result=NULL;
  2598. if (req_comp < 0 || req_comp > 4) return stbi__errpuc("bad req_comp", "Internal error");
  2599. if (stbi__parse_png_file(p, SCAN_load, req_comp)) {
  2600. result = p->out;
  2601. p->out = NULL;
  2602. if (req_comp && req_comp != p->s->img_out_n) {
  2603. result = stbi__convert_format(result, p->s->img_out_n, req_comp, p->s->img_x, p->s->img_y);
  2604. p->s->img_out_n = req_comp;
  2605. if (result == NULL) return result;
  2606. }
  2607. *x = p->s->img_x;
  2608. *y = p->s->img_y;
  2609. if (n) *n = p->s->img_out_n;
  2610. }
  2611. free(p->out); p->out = NULL;
  2612. free(p->expanded); p->expanded = NULL;
  2613. free(p->idata); p->idata = NULL;
  2614. return result;
  2615. }
  2616. static unsigned char *stbi__png_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  2617. {
  2618. stbi__png p;
  2619. p.s = s;
  2620. return stbi__do_png(&p, x,y,comp,req_comp);
  2621. }
  2622. static int stbi__png_test(stbi__context *s)
  2623. {
  2624. int r;
  2625. r = stbi__check_png_header(s);
  2626. stbi__rewind(s);
  2627. return r;
  2628. }
  2629. static int stbi__png_info_raw(stbi__png *p, int *x, int *y, int *comp)
  2630. {
  2631. if (!stbi__parse_png_file(p, SCAN_header, 0)) {
  2632. stbi__rewind( p->s );
  2633. return 0;
  2634. }
  2635. if (x) *x = p->s->img_x;
  2636. if (y) *y = p->s->img_y;
  2637. if (comp) *comp = p->s->img_n;
  2638. return 1;
  2639. }
  2640. static int stbi__png_info(stbi__context *s, int *x, int *y, int *comp)
  2641. {
  2642. stbi__png p;
  2643. p.s = s;
  2644. return stbi__png_info_raw(&p, x, y, comp);
  2645. }
  2646. // Microsoft/Windows BMP image
  2647. static int stbi__bmp_test_raw(stbi__context *s)
  2648. {
  2649. int r;
  2650. int sz;
  2651. if (stbi__get8(s) != 'B') return 0;
  2652. if (stbi__get8(s) != 'M') return 0;
  2653. stbi__get32le(s); // discard filesize
  2654. stbi__get16le(s); // discard reserved
  2655. stbi__get16le(s); // discard reserved
  2656. stbi__get32le(s); // discard data offset
  2657. sz = stbi__get32le(s);
  2658. r = (sz == 12 || sz == 40 || sz == 56 || sz == 108 || sz == 124);
  2659. return r;
  2660. }
  2661. static int stbi__bmp_test(stbi__context *s)
  2662. {
  2663. int r = stbi__bmp_test_raw(s);
  2664. stbi__rewind(s);
  2665. return r;
  2666. }
  2667. // returns 0..31 for the highest set bit
  2668. static int stbi__high_bit(unsigned int z)
  2669. {
  2670. int n=0;
  2671. if (z == 0) return -1;
  2672. if (z >= 0x10000) n += 16, z >>= 16;
  2673. if (z >= 0x00100) n += 8, z >>= 8;
  2674. if (z >= 0x00010) n += 4, z >>= 4;
  2675. if (z >= 0x00004) n += 2, z >>= 2;
  2676. if (z >= 0x00002) n += 1, z >>= 1;
  2677. return n;
  2678. }
  2679. static int stbi__bitcount(unsigned int a)
  2680. {
  2681. a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2
  2682. a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4
  2683. a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits
  2684. a = (a + (a >> 8)); // max 16 per 8 bits
  2685. a = (a + (a >> 16)); // max 32 per 8 bits
  2686. return a & 0xff;
  2687. }
  2688. static int stbi__shiftsigned(int v, int shift, int bits)
  2689. {
  2690. int result;
  2691. int z=0;
  2692. if (shift < 0) v <<= -shift;
  2693. else v >>= shift;
  2694. result = v;
  2695. z = bits;
  2696. while (z < 8) {
  2697. result += v >> z;
  2698. z += bits;
  2699. }
  2700. return result;
  2701. }
  2702. static stbi_uc *stbi__bmp_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  2703. {
  2704. stbi_uc *out;
  2705. unsigned int mr=0,mg=0,mb=0,ma=0, fake_a=0;
  2706. stbi_uc pal[256][4];
  2707. int psize=0,i,j,compress=0,width;
  2708. int bpp, flip_vertically, pad, target, offset, hsz;
  2709. if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') return stbi__errpuc("not BMP", "Corrupt BMP");
  2710. stbi__get32le(s); // discard filesize
  2711. stbi__get16le(s); // discard reserved
  2712. stbi__get16le(s); // discard reserved
  2713. offset = stbi__get32le(s);
  2714. hsz = stbi__get32le(s);
  2715. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) return stbi__errpuc("unknown BMP", "BMP type not supported: unknown");
  2716. if (hsz == 12) {
  2717. s->img_x = stbi__get16le(s);
  2718. s->img_y = stbi__get16le(s);
  2719. } else {
  2720. s->img_x = stbi__get32le(s);
  2721. s->img_y = stbi__get32le(s);
  2722. }
  2723. if (stbi__get16le(s) != 1) return stbi__errpuc("bad BMP", "bad BMP");
  2724. bpp = stbi__get16le(s);
  2725. if (bpp == 1) return stbi__errpuc("monochrome", "BMP type not supported: 1-bit");
  2726. flip_vertically = ((int) s->img_y) > 0;
  2727. s->img_y = abs((int) s->img_y);
  2728. if (hsz == 12) {
  2729. if (bpp < 24)
  2730. psize = (offset - 14 - 24) / 3;
  2731. } else {
  2732. compress = stbi__get32le(s);
  2733. if (compress == 1 || compress == 2) return stbi__errpuc("BMP RLE", "BMP type not supported: RLE");
  2734. stbi__get32le(s); // discard sizeof
  2735. stbi__get32le(s); // discard hres
  2736. stbi__get32le(s); // discard vres
  2737. stbi__get32le(s); // discard colorsused
  2738. stbi__get32le(s); // discard max important
  2739. if (hsz == 40 || hsz == 56) {
  2740. if (hsz == 56) {
  2741. stbi__get32le(s);
  2742. stbi__get32le(s);
  2743. stbi__get32le(s);
  2744. stbi__get32le(s);
  2745. }
  2746. if (bpp == 16 || bpp == 32) {
  2747. mr = mg = mb = 0;
  2748. if (compress == 0) {
  2749. if (bpp == 32) {
  2750. mr = 0xffu << 16;
  2751. mg = 0xffu << 8;
  2752. mb = 0xffu << 0;
  2753. ma = 0xffu << 24;
  2754. fake_a = 1; // @TODO: check for cases like alpha value is all 0 and switch it to 255
  2755. STBI_NOTUSED(fake_a);
  2756. } else {
  2757. mr = 31u << 10;
  2758. mg = 31u << 5;
  2759. mb = 31u << 0;
  2760. }
  2761. } else if (compress == 3) {
  2762. mr = stbi__get32le(s);
  2763. mg = stbi__get32le(s);
  2764. mb = stbi__get32le(s);
  2765. // not documented, but generated by photoshop and handled by mspaint
  2766. if (mr == mg && mg == mb) {
  2767. // ?!?!?
  2768. return stbi__errpuc("bad BMP", "bad BMP");
  2769. }
  2770. } else
  2771. return stbi__errpuc("bad BMP", "bad BMP");
  2772. }
  2773. } else {
  2774. STBI_ASSERT(hsz == 108 || hsz == 124);
  2775. mr = stbi__get32le(s);
  2776. mg = stbi__get32le(s);
  2777. mb = stbi__get32le(s);
  2778. ma = stbi__get32le(s);
  2779. stbi__get32le(s); // discard color space
  2780. for (i=0; i < 12; ++i)
  2781. stbi__get32le(s); // discard color space parameters
  2782. if (hsz == 124) {
  2783. stbi__get32le(s); // discard rendering intent
  2784. stbi__get32le(s); // discard offset of profile data
  2785. stbi__get32le(s); // discard size of profile data
  2786. stbi__get32le(s); // discard reserved
  2787. }
  2788. }
  2789. if (bpp < 16)
  2790. psize = (offset - 14 - hsz) >> 2;
  2791. }
  2792. s->img_n = ma ? 4 : 3;
  2793. if (req_comp && req_comp >= 3) // we can directly decode 3 or 4
  2794. target = req_comp;
  2795. else
  2796. target = s->img_n; // if they want monochrome, we'll post-convert
  2797. out = (stbi_uc *) stbi__malloc(target * s->img_x * s->img_y);
  2798. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  2799. if (bpp < 16) {
  2800. int z=0;
  2801. if (psize == 0 || psize > 256) { free(out); return stbi__errpuc("invalid", "Corrupt BMP"); }
  2802. for (i=0; i < psize; ++i) {
  2803. pal[i][2] = stbi__get8(s);
  2804. pal[i][1] = stbi__get8(s);
  2805. pal[i][0] = stbi__get8(s);
  2806. if (hsz != 12) stbi__get8(s);
  2807. pal[i][3] = 255;
  2808. }
  2809. stbi__skip(s, offset - 14 - hsz - psize * (hsz == 12 ? 3 : 4));
  2810. if (bpp == 4) width = (s->img_x + 1) >> 1;
  2811. else if (bpp == 8) width = s->img_x;
  2812. else { free(out); return stbi__errpuc("bad bpp", "Corrupt BMP"); }
  2813. pad = (-width)&3;
  2814. for (j=0; j < (int) s->img_y; ++j) {
  2815. for (i=0; i < (int) s->img_x; i += 2) {
  2816. int v=stbi__get8(s),v2=0;
  2817. if (bpp == 4) {
  2818. v2 = v & 15;
  2819. v >>= 4;
  2820. }
  2821. out[z++] = pal[v][0];
  2822. out[z++] = pal[v][1];
  2823. out[z++] = pal[v][2];
  2824. if (target == 4) out[z++] = 255;
  2825. if (i+1 == (int) s->img_x) break;
  2826. v = (bpp == 8) ? stbi__get8(s) : v2;
  2827. out[z++] = pal[v][0];
  2828. out[z++] = pal[v][1];
  2829. out[z++] = pal[v][2];
  2830. if (target == 4) out[z++] = 255;
  2831. }
  2832. stbi__skip(s, pad);
  2833. }
  2834. } else {
  2835. int rshift=0,gshift=0,bshift=0,ashift=0,rcount=0,gcount=0,bcount=0,acount=0;
  2836. int z = 0;
  2837. int easy=0;
  2838. stbi__skip(s, offset - 14 - hsz);
  2839. if (bpp == 24) width = 3 * s->img_x;
  2840. else if (bpp == 16) width = 2*s->img_x;
  2841. else /* bpp = 32 and pad = 0 */ width=0;
  2842. pad = (-width) & 3;
  2843. if (bpp == 24) {
  2844. easy = 1;
  2845. } else if (bpp == 32) {
  2846. if (mb == 0xff && mg == 0xff00 && mr == 0x00ff0000 && ma == 0xff000000)
  2847. easy = 2;
  2848. }
  2849. if (!easy) {
  2850. if (!mr || !mg || !mb) { free(out); return stbi__errpuc("bad masks", "Corrupt BMP"); }
  2851. // right shift amt to put high bit in position #7
  2852. rshift = stbi__high_bit(mr)-7; rcount = stbi__bitcount(mr);
  2853. gshift = stbi__high_bit(mg)-7; gcount = stbi__bitcount(mg);
  2854. bshift = stbi__high_bit(mb)-7; bcount = stbi__bitcount(mb);
  2855. ashift = stbi__high_bit(ma)-7; acount = stbi__bitcount(ma);
  2856. }
  2857. for (j=0; j < (int) s->img_y; ++j) {
  2858. if (easy) {
  2859. for (i=0; i < (int) s->img_x; ++i) {
  2860. unsigned char a;
  2861. out[z+2] = stbi__get8(s);
  2862. out[z+1] = stbi__get8(s);
  2863. out[z+0] = stbi__get8(s);
  2864. z += 3;
  2865. a = (easy == 2 ? stbi__get8(s) : 255);
  2866. if (target == 4) out[z++] = a;
  2867. }
  2868. } else {
  2869. for (i=0; i < (int) s->img_x; ++i) {
  2870. stbi__uint32 v = (stbi__uint32) (bpp == 16 ? stbi__get16le(s) : stbi__get32le(s));
  2871. int a;
  2872. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mr, rshift, rcount));
  2873. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mg, gshift, gcount));
  2874. out[z++] = STBI__BYTECAST(stbi__shiftsigned(v & mb, bshift, bcount));
  2875. a = (ma ? stbi__shiftsigned(v & ma, ashift, acount) : 255);
  2876. if (target == 4) out[z++] = STBI__BYTECAST(a);
  2877. }
  2878. }
  2879. stbi__skip(s, pad);
  2880. }
  2881. }
  2882. if (flip_vertically) {
  2883. stbi_uc t;
  2884. for (j=0; j < (int) s->img_y>>1; ++j) {
  2885. stbi_uc *p1 = out + j *s->img_x*target;
  2886. stbi_uc *p2 = out + (s->img_y-1-j)*s->img_x*target;
  2887. for (i=0; i < (int) s->img_x*target; ++i) {
  2888. t = p1[i], p1[i] = p2[i], p2[i] = t;
  2889. }
  2890. }
  2891. }
  2892. if (req_comp && req_comp != target) {
  2893. out = stbi__convert_format(out, target, req_comp, s->img_x, s->img_y);
  2894. if (out == NULL) return out; // stbi__convert_format frees input on failure
  2895. }
  2896. *x = s->img_x;
  2897. *y = s->img_y;
  2898. if (comp) *comp = s->img_n;
  2899. return out;
  2900. }
  2901. // Targa Truevision - TGA
  2902. // by Jonathan Dummer
  2903. static int stbi__tga_info(stbi__context *s, int *x, int *y, int *comp)
  2904. {
  2905. int tga_w, tga_h, tga_comp;
  2906. int sz;
  2907. stbi__get8(s); // discard Offset
  2908. sz = stbi__get8(s); // color type
  2909. if( sz > 1 ) {
  2910. stbi__rewind(s);
  2911. return 0; // only RGB or indexed allowed
  2912. }
  2913. sz = stbi__get8(s); // image type
  2914. // only RGB or grey allowed, +/- RLE
  2915. if ((sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11)) return 0;
  2916. stbi__skip(s,9);
  2917. tga_w = stbi__get16le(s);
  2918. if( tga_w < 1 ) {
  2919. stbi__rewind(s);
  2920. return 0; // test width
  2921. }
  2922. tga_h = stbi__get16le(s);
  2923. if( tga_h < 1 ) {
  2924. stbi__rewind(s);
  2925. return 0; // test height
  2926. }
  2927. sz = stbi__get8(s); // bits per pixel
  2928. // only RGB or RGBA or grey allowed
  2929. if ((sz != 8) && (sz != 16) && (sz != 24) && (sz != 32)) {
  2930. stbi__rewind(s);
  2931. return 0;
  2932. }
  2933. tga_comp = sz;
  2934. if (x) *x = tga_w;
  2935. if (y) *y = tga_h;
  2936. if (comp) *comp = tga_comp / 8;
  2937. return 1; // seems to have passed everything
  2938. }
  2939. static int stbi__tga_test(stbi__context *s)
  2940. {
  2941. int res;
  2942. int sz;
  2943. stbi__get8(s); // discard Offset
  2944. sz = stbi__get8(s); // color type
  2945. if ( sz > 1 ) return 0; // only RGB or indexed allowed
  2946. sz = stbi__get8(s); // image type
  2947. if ( (sz != 1) && (sz != 2) && (sz != 3) && (sz != 9) && (sz != 10) && (sz != 11) ) return 0; // only RGB or grey allowed, +/- RLE
  2948. stbi__get16be(s); // discard palette start
  2949. stbi__get16be(s); // discard palette length
  2950. stbi__get8(s); // discard bits per palette color entry
  2951. stbi__get16be(s); // discard x origin
  2952. stbi__get16be(s); // discard y origin
  2953. if ( stbi__get16be(s) < 1 ) return 0; // test width
  2954. if ( stbi__get16be(s) < 1 ) return 0; // test height
  2955. sz = stbi__get8(s); // bits per pixel
  2956. if ( (sz != 8) && (sz != 16) && (sz != 24) && (sz != 32) )
  2957. res = 0;
  2958. else
  2959. res = 1;
  2960. stbi__rewind(s);
  2961. return res;
  2962. }
  2963. static stbi_uc *stbi__tga_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  2964. {
  2965. // read in the TGA header stuff
  2966. int tga_offset = stbi__get8(s);
  2967. int tga_indexed = stbi__get8(s);
  2968. int tga_image_type = stbi__get8(s);
  2969. int tga_is_RLE = 0;
  2970. int tga_palette_start = stbi__get16le(s);
  2971. int tga_palette_len = stbi__get16le(s);
  2972. int tga_palette_bits = stbi__get8(s);
  2973. int tga_x_origin = stbi__get16le(s);
  2974. int tga_y_origin = stbi__get16le(s);
  2975. int tga_width = stbi__get16le(s);
  2976. int tga_height = stbi__get16le(s);
  2977. int tga_bits_per_pixel = stbi__get8(s);
  2978. int tga_comp = tga_bits_per_pixel / 8;
  2979. int tga_inverted = stbi__get8(s);
  2980. // image data
  2981. unsigned char *tga_data;
  2982. unsigned char *tga_palette = NULL;
  2983. int i, j;
  2984. unsigned char raw_data[4];
  2985. int RLE_count = 0;
  2986. int RLE_repeating = 0;
  2987. int read_next_pixel = 1;
  2988. // do a tiny bit of precessing
  2989. if ( tga_image_type >= 8 )
  2990. {
  2991. tga_image_type -= 8;
  2992. tga_is_RLE = 1;
  2993. }
  2994. /* int tga_alpha_bits = tga_inverted & 15; */
  2995. tga_inverted = 1 - ((tga_inverted >> 5) & 1);
  2996. // error check
  2997. if ( //(tga_indexed) ||
  2998. (tga_width < 1) || (tga_height < 1) ||
  2999. (tga_image_type < 1) || (tga_image_type > 3) ||
  3000. ((tga_bits_per_pixel != 8) && (tga_bits_per_pixel != 16) &&
  3001. (tga_bits_per_pixel != 24) && (tga_bits_per_pixel != 32))
  3002. )
  3003. {
  3004. return NULL; // we don't report this as a bad TGA because we don't even know if it's TGA
  3005. }
  3006. // If I'm paletted, then I'll use the number of bits from the palette
  3007. if ( tga_indexed )
  3008. {
  3009. tga_comp = tga_palette_bits / 8;
  3010. }
  3011. // tga info
  3012. *x = tga_width;
  3013. *y = tga_height;
  3014. if (comp) *comp = tga_comp;
  3015. tga_data = (unsigned char*)stbi__malloc( tga_width * tga_height * tga_comp );
  3016. if (!tga_data) return stbi__errpuc("outofmem", "Out of memory");
  3017. // skip to the data's starting position (offset usually = 0)
  3018. stbi__skip(s, tga_offset );
  3019. if ( !tga_indexed && !tga_is_RLE) {
  3020. for (i=0; i < tga_height; ++i) {
  3021. int y = tga_inverted ? tga_height -i - 1 : i;
  3022. stbi_uc *tga_row = tga_data + y*tga_width*tga_comp;
  3023. stbi__getn(s, tga_row, tga_width * tga_comp);
  3024. }
  3025. } else {
  3026. // do I need to load a palette?
  3027. if ( tga_indexed)
  3028. {
  3029. // any data to skip? (offset usually = 0)
  3030. stbi__skip(s, tga_palette_start );
  3031. // load the palette
  3032. tga_palette = (unsigned char*)stbi__malloc( tga_palette_len * tga_palette_bits / 8 );
  3033. if (!tga_palette) {
  3034. free(tga_data);
  3035. return stbi__errpuc("outofmem", "Out of memory");
  3036. }
  3037. if (!stbi__getn(s, tga_palette, tga_palette_len * tga_palette_bits / 8 )) {
  3038. free(tga_data);
  3039. free(tga_palette);
  3040. return stbi__errpuc("bad palette", "Corrupt TGA");
  3041. }
  3042. }
  3043. // load the data
  3044. for (i=0; i < tga_width * tga_height; ++i)
  3045. {
  3046. // if I'm in RLE mode, do I need to get a RLE stbi__pngchunk?
  3047. if ( tga_is_RLE )
  3048. {
  3049. if ( RLE_count == 0 )
  3050. {
  3051. // yep, get the next byte as a RLE command
  3052. int RLE_cmd = stbi__get8(s);
  3053. RLE_count = 1 + (RLE_cmd & 127);
  3054. RLE_repeating = RLE_cmd >> 7;
  3055. read_next_pixel = 1;
  3056. } else if ( !RLE_repeating )
  3057. {
  3058. read_next_pixel = 1;
  3059. }
  3060. } else
  3061. {
  3062. read_next_pixel = 1;
  3063. }
  3064. // OK, if I need to read a pixel, do it now
  3065. if ( read_next_pixel )
  3066. {
  3067. // load however much data we did have
  3068. if ( tga_indexed )
  3069. {
  3070. // read in 1 byte, then perform the lookup
  3071. int pal_idx = stbi__get8(s);
  3072. if ( pal_idx >= tga_palette_len )
  3073. {
  3074. // invalid index
  3075. pal_idx = 0;
  3076. }
  3077. pal_idx *= tga_bits_per_pixel / 8;
  3078. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  3079. {
  3080. raw_data[j] = tga_palette[pal_idx+j];
  3081. }
  3082. } else
  3083. {
  3084. // read in the data raw
  3085. for (j = 0; j*8 < tga_bits_per_pixel; ++j)
  3086. {
  3087. raw_data[j] = stbi__get8(s);
  3088. }
  3089. }
  3090. // clear the reading flag for the next pixel
  3091. read_next_pixel = 0;
  3092. } // end of reading a pixel
  3093. // copy data
  3094. for (j = 0; j < tga_comp; ++j)
  3095. tga_data[i*tga_comp+j] = raw_data[j];
  3096. // in case we're in RLE mode, keep counting down
  3097. --RLE_count;
  3098. }
  3099. // do I need to invert the image?
  3100. if ( tga_inverted )
  3101. {
  3102. for (j = 0; j*2 < tga_height; ++j)
  3103. {
  3104. int index1 = j * tga_width * tga_comp;
  3105. int index2 = (tga_height - 1 - j) * tga_width * tga_comp;
  3106. for (i = tga_width * tga_comp; i > 0; --i)
  3107. {
  3108. unsigned char temp = tga_data[index1];
  3109. tga_data[index1] = tga_data[index2];
  3110. tga_data[index2] = temp;
  3111. ++index1;
  3112. ++index2;
  3113. }
  3114. }
  3115. }
  3116. // clear my palette, if I had one
  3117. if ( tga_palette != NULL )
  3118. {
  3119. free( tga_palette );
  3120. }
  3121. }
  3122. // swap RGB
  3123. if (tga_comp >= 3)
  3124. {
  3125. unsigned char* tga_pixel = tga_data;
  3126. for (i=0; i < tga_width * tga_height; ++i)
  3127. {
  3128. unsigned char temp = tga_pixel[0];
  3129. tga_pixel[0] = tga_pixel[2];
  3130. tga_pixel[2] = temp;
  3131. tga_pixel += tga_comp;
  3132. }
  3133. }
  3134. // convert to target component count
  3135. if (req_comp && req_comp != tga_comp)
  3136. tga_data = stbi__convert_format(tga_data, tga_comp, req_comp, tga_width, tga_height);
  3137. // the things I do to get rid of an error message, and yet keep
  3138. // Microsoft's C compilers happy... [8^(
  3139. tga_palette_start = tga_palette_len = tga_palette_bits =
  3140. tga_x_origin = tga_y_origin = 0;
  3141. // OK, done
  3142. return tga_data;
  3143. }
  3144. // *************************************************************************************************
  3145. // Photoshop PSD loader -- PD by Thatcher Ulrich, integration by Nicolas Schulz, tweaked by STB
  3146. static int stbi__psd_test(stbi__context *s)
  3147. {
  3148. int r = (stbi__get32be(s) == 0x38425053);
  3149. stbi__rewind(s);
  3150. return r;
  3151. }
  3152. static stbi_uc *stbi__psd_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  3153. {
  3154. int pixelCount;
  3155. int channelCount, compression;
  3156. int channel, i, count, len;
  3157. int w,h;
  3158. stbi_uc *out;
  3159. // Check identifier
  3160. if (stbi__get32be(s) != 0x38425053) // "8BPS"
  3161. return stbi__errpuc("not PSD", "Corrupt PSD image");
  3162. // Check file type version.
  3163. if (stbi__get16be(s) != 1)
  3164. return stbi__errpuc("wrong version", "Unsupported version of PSD image");
  3165. // Skip 6 reserved bytes.
  3166. stbi__skip(s, 6 );
  3167. // Read the number of channels (R, G, B, A, etc).
  3168. channelCount = stbi__get16be(s);
  3169. if (channelCount < 0 || channelCount > 16)
  3170. return stbi__errpuc("wrong channel count", "Unsupported number of channels in PSD image");
  3171. // Read the rows and columns of the image.
  3172. h = stbi__get32be(s);
  3173. w = stbi__get32be(s);
  3174. // Make sure the depth is 8 bits.
  3175. if (stbi__get16be(s) != 8)
  3176. return stbi__errpuc("unsupported bit depth", "PSD bit depth is not 8 bit");
  3177. // Make sure the color mode is RGB.
  3178. // Valid options are:
  3179. // 0: Bitmap
  3180. // 1: Grayscale
  3181. // 2: Indexed color
  3182. // 3: RGB color
  3183. // 4: CMYK color
  3184. // 7: Multichannel
  3185. // 8: Duotone
  3186. // 9: Lab color
  3187. if (stbi__get16be(s) != 3)
  3188. return stbi__errpuc("wrong color format", "PSD is not in RGB color format");
  3189. // Skip the Mode Data. (It's the palette for indexed color; other info for other modes.)
  3190. stbi__skip(s,stbi__get32be(s) );
  3191. // Skip the image resources. (resolution, pen tool paths, etc)
  3192. stbi__skip(s, stbi__get32be(s) );
  3193. // Skip the reserved data.
  3194. stbi__skip(s, stbi__get32be(s) );
  3195. // Find out if the data is compressed.
  3196. // Known values:
  3197. // 0: no compression
  3198. // 1: RLE compressed
  3199. compression = stbi__get16be(s);
  3200. if (compression > 1)
  3201. return stbi__errpuc("bad compression", "PSD has an unknown compression format");
  3202. // Create the destination image.
  3203. out = (stbi_uc *) stbi__malloc(4 * w*h);
  3204. if (!out) return stbi__errpuc("outofmem", "Out of memory");
  3205. pixelCount = w*h;
  3206. // Initialize the data to zero.
  3207. //memset( out, 0, pixelCount * 4 );
  3208. // Finally, the image data.
  3209. if (compression) {
  3210. // RLE as used by .PSD and .TIFF
  3211. // Loop until you get the number of unpacked bytes you are expecting:
  3212. // Read the next source byte into n.
  3213. // If n is between 0 and 127 inclusive, copy the next n+1 bytes literally.
  3214. // Else if n is between -127 and -1 inclusive, copy the next byte -n+1 times.
  3215. // Else if n is 128, noop.
  3216. // Endloop
  3217. // The RLE-compressed data is preceeded by a 2-byte data count for each row in the data,
  3218. // which we're going to just skip.
  3219. stbi__skip(s, h * channelCount * 2 );
  3220. // Read the RLE data by channel.
  3221. for (channel = 0; channel < 4; channel++) {
  3222. stbi_uc *p;
  3223. p = out+channel;
  3224. if (channel >= channelCount) {
  3225. // Fill this channel with default data.
  3226. for (i = 0; i < pixelCount; i++) *p = (channel == 3 ? 255 : 0), p += 4;
  3227. } else {
  3228. // Read the RLE data.
  3229. count = 0;
  3230. while (count < pixelCount) {
  3231. len = stbi__get8(s);
  3232. if (len == 128) {
  3233. // No-op.
  3234. } else if (len < 128) {
  3235. // Copy next len+1 bytes literally.
  3236. len++;
  3237. count += len;
  3238. while (len) {
  3239. *p = stbi__get8(s);
  3240. p += 4;
  3241. len--;
  3242. }
  3243. } else if (len > 128) {
  3244. stbi_uc val;
  3245. // Next -len+1 bytes in the dest are replicated from next source byte.
  3246. // (Interpret len as a negative 8-bit int.)
  3247. len ^= 0x0FF;
  3248. len += 2;
  3249. val = stbi__get8(s);
  3250. count += len;
  3251. while (len) {
  3252. *p = val;
  3253. p += 4;
  3254. len--;
  3255. }
  3256. }
  3257. }
  3258. }
  3259. }
  3260. } else {
  3261. // We're at the raw image data. It's each channel in order (Red, Green, Blue, Alpha, ...)
  3262. // where each channel consists of an 8-bit value for each pixel in the image.
  3263. // Read the data by channel.
  3264. for (channel = 0; channel < 4; channel++) {
  3265. stbi_uc *p;
  3266. p = out + channel;
  3267. if (channel > channelCount) {
  3268. // Fill this channel with default data.
  3269. for (i = 0; i < pixelCount; i++) *p = channel == 3 ? 255 : 0, p += 4;
  3270. } else {
  3271. // Read the data.
  3272. for (i = 0; i < pixelCount; i++)
  3273. *p = stbi__get8(s), p += 4;
  3274. }
  3275. }
  3276. }
  3277. if (req_comp && req_comp != 4) {
  3278. out = stbi__convert_format(out, 4, req_comp, w, h);
  3279. if (out == NULL) return out; // stbi__convert_format frees input on failure
  3280. }
  3281. if (comp) *comp = channelCount;
  3282. *y = h;
  3283. *x = w;
  3284. return out;
  3285. }
  3286. // *************************************************************************************************
  3287. // Softimage PIC loader
  3288. // by Tom Seddon
  3289. //
  3290. // See http://softimage.wiki.softimage.com/index.php/INFO:_PIC_file_format
  3291. // See http://ozviz.wasp.uwa.edu.au/~pbourke/dataformats/softimagepic/
  3292. static int stbi__pic_is4(stbi__context *s,const char *str)
  3293. {
  3294. int i;
  3295. for (i=0; i<4; ++i)
  3296. if (stbi__get8(s) != (stbi_uc)str[i])
  3297. return 0;
  3298. return 1;
  3299. }
  3300. static int stbi__pic_test_core(stbi__context *s)
  3301. {
  3302. int i;
  3303. if (!stbi__pic_is4(s,"\x53\x80\xF6\x34"))
  3304. return 0;
  3305. for(i=0;i<84;++i)
  3306. stbi__get8(s);
  3307. if (!stbi__pic_is4(s,"PICT"))
  3308. return 0;
  3309. return 1;
  3310. }
  3311. typedef struct
  3312. {
  3313. stbi_uc size,type,channel;
  3314. } stbi__pic_packet;
  3315. static stbi_uc *stbi__readval(stbi__context *s, int channel, stbi_uc *dest)
  3316. {
  3317. int mask=0x80, i;
  3318. for (i=0; i<4; ++i, mask>>=1) {
  3319. if (channel & mask) {
  3320. if (stbi__at_eof(s)) return stbi__errpuc("bad file","PIC file too short");
  3321. dest[i]=stbi__get8(s);
  3322. }
  3323. }
  3324. return dest;
  3325. }
  3326. static void stbi__copyval(int channel,stbi_uc *dest,const stbi_uc *src)
  3327. {
  3328. int mask=0x80,i;
  3329. for (i=0;i<4; ++i, mask>>=1)
  3330. if (channel&mask)
  3331. dest[i]=src[i];
  3332. }
  3333. static stbi_uc *stbi__pic_load_core(stbi__context *s,int width,int height,int *comp, stbi_uc *result)
  3334. {
  3335. int act_comp=0,num_packets=0,y,chained;
  3336. stbi__pic_packet packets[10];
  3337. // this will (should...) cater for even some bizarre stuff like having data
  3338. // for the same channel in multiple packets.
  3339. do {
  3340. stbi__pic_packet *packet;
  3341. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  3342. return stbi__errpuc("bad format","too many packets");
  3343. packet = &packets[num_packets++];
  3344. chained = stbi__get8(s);
  3345. packet->size = stbi__get8(s);
  3346. packet->type = stbi__get8(s);
  3347. packet->channel = stbi__get8(s);
  3348. act_comp |= packet->channel;
  3349. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (reading packets)");
  3350. if (packet->size != 8) return stbi__errpuc("bad format","packet isn't 8bpp");
  3351. } while (chained);
  3352. *comp = (act_comp & 0x10 ? 4 : 3); // has alpha channel?
  3353. for(y=0; y<height; ++y) {
  3354. int packet_idx;
  3355. for(packet_idx=0; packet_idx < num_packets; ++packet_idx) {
  3356. stbi__pic_packet *packet = &packets[packet_idx];
  3357. stbi_uc *dest = result+y*width*4;
  3358. switch (packet->type) {
  3359. default:
  3360. return stbi__errpuc("bad format","packet has bad compression type");
  3361. case 0: {//uncompressed
  3362. int x;
  3363. for(x=0;x<width;++x, dest+=4)
  3364. if (!stbi__readval(s,packet->channel,dest))
  3365. return 0;
  3366. break;
  3367. }
  3368. case 1://Pure RLE
  3369. {
  3370. int left=width, i;
  3371. while (left>0) {
  3372. stbi_uc count,value[4];
  3373. count=stbi__get8(s);
  3374. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pure read count)");
  3375. if (count > left)
  3376. count = (stbi_uc) left;
  3377. if (!stbi__readval(s,packet->channel,value)) return 0;
  3378. for(i=0; i<count; ++i,dest+=4)
  3379. stbi__copyval(packet->channel,dest,value);
  3380. left -= count;
  3381. }
  3382. }
  3383. break;
  3384. case 2: {//Mixed RLE
  3385. int left=width;
  3386. while (left>0) {
  3387. int count = stbi__get8(s), i;
  3388. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (mixed read count)");
  3389. if (count >= 128) { // Repeated
  3390. stbi_uc value[4];
  3391. int i;
  3392. if (count==128)
  3393. count = stbi__get16be(s);
  3394. else
  3395. count -= 127;
  3396. if (count > left)
  3397. return stbi__errpuc("bad file","scanline overrun");
  3398. if (!stbi__readval(s,packet->channel,value))
  3399. return 0;
  3400. for(i=0;i<count;++i, dest += 4)
  3401. stbi__copyval(packet->channel,dest,value);
  3402. } else { // Raw
  3403. ++count;
  3404. if (count>left) return stbi__errpuc("bad file","scanline overrun");
  3405. for(i=0;i<count;++i, dest+=4)
  3406. if (!stbi__readval(s,packet->channel,dest))
  3407. return 0;
  3408. }
  3409. left-=count;
  3410. }
  3411. break;
  3412. }
  3413. }
  3414. }
  3415. }
  3416. return result;
  3417. }
  3418. static stbi_uc *stbi__pic_load(stbi__context *s,int *px,int *py,int *comp,int req_comp)
  3419. {
  3420. stbi_uc *result;
  3421. int i, x,y;
  3422. for (i=0; i<92; ++i)
  3423. stbi__get8(s);
  3424. x = stbi__get16be(s);
  3425. y = stbi__get16be(s);
  3426. if (stbi__at_eof(s)) return stbi__errpuc("bad file","file too short (pic header)");
  3427. if ((1 << 28) / x < y) return stbi__errpuc("too large", "Image too large to decode");
  3428. stbi__get32be(s); //skip `ratio'
  3429. stbi__get16be(s); //skip `fields'
  3430. stbi__get16be(s); //skip `pad'
  3431. // intermediate buffer is RGBA
  3432. result = (stbi_uc *) stbi__malloc(x*y*4);
  3433. memset(result, 0xff, x*y*4);
  3434. if (!stbi__pic_load_core(s,x,y,comp, result)) {
  3435. free(result);
  3436. result=0;
  3437. }
  3438. *px = x;
  3439. *py = y;
  3440. if (req_comp == 0) req_comp = *comp;
  3441. result=stbi__convert_format(result,4,req_comp,x,y);
  3442. return result;
  3443. }
  3444. static int stbi__pic_test(stbi__context *s)
  3445. {
  3446. int r = stbi__pic_test_core(s);
  3447. stbi__rewind(s);
  3448. return r;
  3449. }
  3450. // *************************************************************************************************
  3451. // GIF loader -- public domain by Jean-Marc Lienher -- simplified/shrunk by stb
  3452. typedef struct
  3453. {
  3454. stbi__int16 prefix;
  3455. stbi_uc first;
  3456. stbi_uc suffix;
  3457. } stbi__gif_lzw;
  3458. typedef struct
  3459. {
  3460. int w,h;
  3461. stbi_uc *out; // output buffer (always 4 components)
  3462. int flags, bgindex, ratio, transparent, eflags;
  3463. stbi_uc pal[256][4];
  3464. stbi_uc lpal[256][4];
  3465. stbi__gif_lzw codes[4096];
  3466. stbi_uc *color_table;
  3467. int parse, step;
  3468. int lflags;
  3469. int start_x, start_y;
  3470. int max_x, max_y;
  3471. int cur_x, cur_y;
  3472. int line_size;
  3473. } stbi__gif;
  3474. static int stbi__gif_test_raw(stbi__context *s)
  3475. {
  3476. int sz;
  3477. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8') return 0;
  3478. sz = stbi__get8(s);
  3479. if (sz != '9' && sz != '7') return 0;
  3480. if (stbi__get8(s) != 'a') return 0;
  3481. return 1;
  3482. }
  3483. static int stbi__gif_test(stbi__context *s)
  3484. {
  3485. int r = stbi__gif_test_raw(s);
  3486. stbi__rewind(s);
  3487. return r;
  3488. }
  3489. static void stbi__gif_parse_colortable(stbi__context *s, stbi_uc pal[256][4], int num_entries, int transp)
  3490. {
  3491. int i;
  3492. for (i=0; i < num_entries; ++i) {
  3493. pal[i][2] = stbi__get8(s);
  3494. pal[i][1] = stbi__get8(s);
  3495. pal[i][0] = stbi__get8(s);
  3496. pal[i][3] = transp ? 0 : 255;
  3497. }
  3498. }
  3499. static int stbi__gif_header(stbi__context *s, stbi__gif *g, int *comp, int is_info)
  3500. {
  3501. stbi_uc version;
  3502. if (stbi__get8(s) != 'G' || stbi__get8(s) != 'I' || stbi__get8(s) != 'F' || stbi__get8(s) != '8')
  3503. return stbi__err("not GIF", "Corrupt GIF");
  3504. version = stbi__get8(s);
  3505. if (version != '7' && version != '9') return stbi__err("not GIF", "Corrupt GIF");
  3506. if (stbi__get8(s) != 'a') return stbi__err("not GIF", "Corrupt GIF");
  3507. stbi__g_failure_reason = "";
  3508. g->w = stbi__get16le(s);
  3509. g->h = stbi__get16le(s);
  3510. g->flags = stbi__get8(s);
  3511. g->bgindex = stbi__get8(s);
  3512. g->ratio = stbi__get8(s);
  3513. g->transparent = -1;
  3514. if (comp != 0) *comp = 4; // can't actually tell whether it's 3 or 4 until we parse the comments
  3515. if (is_info) return 1;
  3516. if (g->flags & 0x80)
  3517. stbi__gif_parse_colortable(s,g->pal, 2 << (g->flags & 7), -1);
  3518. return 1;
  3519. }
  3520. static int stbi__gif_info_raw(stbi__context *s, int *x, int *y, int *comp)
  3521. {
  3522. stbi__gif g;
  3523. if (!stbi__gif_header(s, &g, comp, 1)) {
  3524. stbi__rewind( s );
  3525. return 0;
  3526. }
  3527. if (x) *x = g.w;
  3528. if (y) *y = g.h;
  3529. return 1;
  3530. }
  3531. static void stbi__out_gif_code(stbi__gif *g, stbi__uint16 code)
  3532. {
  3533. stbi_uc *p, *c;
  3534. // recurse to decode the prefixes, since the linked-list is backwards,
  3535. // and working backwards through an interleaved image would be nasty
  3536. if (g->codes[code].prefix >= 0)
  3537. stbi__out_gif_code(g, g->codes[code].prefix);
  3538. if (g->cur_y >= g->max_y) return;
  3539. p = &g->out[g->cur_x + g->cur_y];
  3540. c = &g->color_table[g->codes[code].suffix * 4];
  3541. if (c[3] >= 128) {
  3542. p[0] = c[2];
  3543. p[1] = c[1];
  3544. p[2] = c[0];
  3545. p[3] = c[3];
  3546. }
  3547. g->cur_x += 4;
  3548. if (g->cur_x >= g->max_x) {
  3549. g->cur_x = g->start_x;
  3550. g->cur_y += g->step;
  3551. while (g->cur_y >= g->max_y && g->parse > 0) {
  3552. g->step = (1 << g->parse) * g->line_size;
  3553. g->cur_y = g->start_y + (g->step >> 1);
  3554. --g->parse;
  3555. }
  3556. }
  3557. }
  3558. static stbi_uc *stbi__process_gif_raster(stbi__context *s, stbi__gif *g)
  3559. {
  3560. stbi_uc lzw_cs;
  3561. stbi__int32 len, code;
  3562. stbi__uint32 first;
  3563. stbi__int32 codesize, codemask, avail, oldcode, bits, valid_bits, clear;
  3564. stbi__gif_lzw *p;
  3565. lzw_cs = stbi__get8(s);
  3566. clear = 1 << lzw_cs;
  3567. first = 1;
  3568. codesize = lzw_cs + 1;
  3569. codemask = (1 << codesize) - 1;
  3570. bits = 0;
  3571. valid_bits = 0;
  3572. for (code = 0; code < clear; code++) {
  3573. g->codes[code].prefix = -1;
  3574. g->codes[code].first = (stbi_uc) code;
  3575. g->codes[code].suffix = (stbi_uc) code;
  3576. }
  3577. // support no starting clear code
  3578. avail = clear+2;
  3579. oldcode = -1;
  3580. len = 0;
  3581. for(;;) {
  3582. if (valid_bits < codesize) {
  3583. if (len == 0) {
  3584. len = stbi__get8(s); // start new block
  3585. if (len == 0)
  3586. return g->out;
  3587. }
  3588. --len;
  3589. bits |= (stbi__int32) stbi__get8(s) << valid_bits;
  3590. valid_bits += 8;
  3591. } else {
  3592. stbi__int32 code = bits & codemask;
  3593. bits >>= codesize;
  3594. valid_bits -= codesize;
  3595. // @OPTIMIZE: is there some way we can accelerate the non-clear path?
  3596. if (code == clear) { // clear code
  3597. codesize = lzw_cs + 1;
  3598. codemask = (1 << codesize) - 1;
  3599. avail = clear + 2;
  3600. oldcode = -1;
  3601. first = 0;
  3602. } else if (code == clear + 1) { // end of stream code
  3603. stbi__skip(s, len);
  3604. while ((len = stbi__get8(s)) > 0)
  3605. stbi__skip(s,len);
  3606. return g->out;
  3607. } else if (code <= avail) {
  3608. if (first) return stbi__errpuc("no clear code", "Corrupt GIF");
  3609. if (oldcode >= 0) {
  3610. p = &g->codes[avail++];
  3611. if (avail > 4096) return stbi__errpuc("too many codes", "Corrupt GIF");
  3612. p->prefix = (stbi__int16) oldcode;
  3613. p->first = g->codes[oldcode].first;
  3614. p->suffix = (code == avail) ? p->first : g->codes[code].first;
  3615. } else if (code == avail)
  3616. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  3617. stbi__out_gif_code(g, (stbi__uint16) code);
  3618. if ((avail & codemask) == 0 && avail <= 0x0FFF) {
  3619. codesize++;
  3620. codemask = (1 << codesize) - 1;
  3621. }
  3622. oldcode = code;
  3623. } else {
  3624. return stbi__errpuc("illegal code in raster", "Corrupt GIF");
  3625. }
  3626. }
  3627. }
  3628. }
  3629. static void stbi__fill_gif_background(stbi__gif *g)
  3630. {
  3631. int i;
  3632. stbi_uc *c = g->pal[g->bgindex];
  3633. // @OPTIMIZE: write a dword at a time
  3634. for (i = 0; i < g->w * g->h * 4; i += 4) {
  3635. stbi_uc *p = &g->out[i];
  3636. p[0] = c[2];
  3637. p[1] = c[1];
  3638. p[2] = c[0];
  3639. p[3] = c[3];
  3640. }
  3641. }
  3642. // this function is designed to support animated gifs, although stb_image doesn't support it
  3643. static stbi_uc *stbi__gif_load_next(stbi__context *s, stbi__gif *g, int *comp, int req_comp)
  3644. {
  3645. int i;
  3646. stbi_uc *old_out = 0;
  3647. if (g->out == 0) {
  3648. if (!stbi__gif_header(s, g, comp,0)) return 0; // stbi__g_failure_reason set by stbi__gif_header
  3649. g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);
  3650. if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
  3651. stbi__fill_gif_background(g);
  3652. } else {
  3653. // animated-gif-only path
  3654. if (((g->eflags & 0x1C) >> 2) == 3) {
  3655. old_out = g->out;
  3656. g->out = (stbi_uc *) stbi__malloc(4 * g->w * g->h);
  3657. if (g->out == 0) return stbi__errpuc("outofmem", "Out of memory");
  3658. memcpy(g->out, old_out, g->w*g->h*4);
  3659. }
  3660. }
  3661. for (;;) {
  3662. switch (stbi__get8(s)) {
  3663. case 0x2C: /* Image Descriptor */
  3664. {
  3665. stbi__int32 x, y, w, h;
  3666. stbi_uc *o;
  3667. x = stbi__get16le(s);
  3668. y = stbi__get16le(s);
  3669. w = stbi__get16le(s);
  3670. h = stbi__get16le(s);
  3671. if (((x + w) > (g->w)) || ((y + h) > (g->h)))
  3672. return stbi__errpuc("bad Image Descriptor", "Corrupt GIF");
  3673. g->line_size = g->w * 4;
  3674. g->start_x = x * 4;
  3675. g->start_y = y * g->line_size;
  3676. g->max_x = g->start_x + w * 4;
  3677. g->max_y = g->start_y + h * g->line_size;
  3678. g->cur_x = g->start_x;
  3679. g->cur_y = g->start_y;
  3680. g->lflags = stbi__get8(s);
  3681. if (g->lflags & 0x40) {
  3682. g->step = 8 * g->line_size; // first interlaced spacing
  3683. g->parse = 3;
  3684. } else {
  3685. g->step = g->line_size;
  3686. g->parse = 0;
  3687. }
  3688. if (g->lflags & 0x80) {
  3689. stbi__gif_parse_colortable(s,g->lpal, 2 << (g->lflags & 7), g->eflags & 0x01 ? g->transparent : -1);
  3690. g->color_table = (stbi_uc *) g->lpal;
  3691. } else if (g->flags & 0x80) {
  3692. for (i=0; i < 256; ++i) // @OPTIMIZE: stbi__jpeg_reset only the previous transparent
  3693. g->pal[i][3] = 255;
  3694. if (g->transparent >= 0 && (g->eflags & 0x01))
  3695. g->pal[g->transparent][3] = 0;
  3696. g->color_table = (stbi_uc *) g->pal;
  3697. } else
  3698. return stbi__errpuc("missing color table", "Corrupt GIF");
  3699. o = stbi__process_gif_raster(s, g);
  3700. if (o == NULL) return NULL;
  3701. if (req_comp && req_comp != 4)
  3702. o = stbi__convert_format(o, 4, req_comp, g->w, g->h);
  3703. return o;
  3704. }
  3705. case 0x21: // Comment Extension.
  3706. {
  3707. int len;
  3708. if (stbi__get8(s) == 0xF9) { // Graphic Control Extension.
  3709. len = stbi__get8(s);
  3710. if (len == 4) {
  3711. g->eflags = stbi__get8(s);
  3712. stbi__get16le(s); // delay
  3713. g->transparent = stbi__get8(s);
  3714. } else {
  3715. stbi__skip(s, len);
  3716. break;
  3717. }
  3718. }
  3719. while ((len = stbi__get8(s)) != 0)
  3720. stbi__skip(s, len);
  3721. break;
  3722. }
  3723. case 0x3B: // gif stream termination code
  3724. return (stbi_uc *) s; // using '1' causes warning on some compilers
  3725. default:
  3726. return stbi__errpuc("unknown code", "Corrupt GIF");
  3727. }
  3728. }
  3729. }
  3730. static stbi_uc *stbi__gif_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  3731. {
  3732. stbi_uc *u = 0;
  3733. stbi__gif g;
  3734. memset(&g, 0, sizeof(g));
  3735. u = stbi__gif_load_next(s, &g, comp, req_comp);
  3736. if (u == (stbi_uc *) s) u = 0; // end of animated gif marker
  3737. if (u) {
  3738. *x = g.w;
  3739. *y = g.h;
  3740. }
  3741. return u;
  3742. }
  3743. static int stbi__gif_info(stbi__context *s, int *x, int *y, int *comp)
  3744. {
  3745. return stbi__gif_info_raw(s,x,y,comp);
  3746. }
  3747. // *************************************************************************************************
  3748. // Radiance RGBE HDR loader
  3749. // originally by Nicolas Schulz
  3750. #ifndef STBI_NO_HDR
  3751. static int stbi__hdr_test_core(stbi__context *s)
  3752. {
  3753. const char *signature = "#?RADIANCE\n";
  3754. int i;
  3755. for (i=0; signature[i]; ++i)
  3756. if (stbi__get8(s) != signature[i])
  3757. return 0;
  3758. return 1;
  3759. }
  3760. static int stbi__hdr_test(stbi__context* s)
  3761. {
  3762. int r = stbi__hdr_test_core(s);
  3763. stbi__rewind(s);
  3764. return r;
  3765. }
  3766. #define STBI__HDR_BUFLEN 1024
  3767. static char *stbi__hdr_gettoken(stbi__context *z, char *buffer)
  3768. {
  3769. int len=0;
  3770. char c = '\0';
  3771. c = (char) stbi__get8(z);
  3772. while (!stbi__at_eof(z) && c != '\n') {
  3773. buffer[len++] = c;
  3774. if (len == STBI__HDR_BUFLEN-1) {
  3775. // flush to end of line
  3776. while (!stbi__at_eof(z) && stbi__get8(z) != '\n')
  3777. ;
  3778. break;
  3779. }
  3780. c = (char) stbi__get8(z);
  3781. }
  3782. buffer[len] = 0;
  3783. return buffer;
  3784. }
  3785. static void stbi__hdr_convert(float *output, stbi_uc *input, int req_comp)
  3786. {
  3787. if ( input[3] != 0 ) {
  3788. float f1;
  3789. // Exponent
  3790. f1 = (float) ldexp(1.0f, input[3] - (int)(128 + 8));
  3791. if (req_comp <= 2)
  3792. output[0] = (input[0] + input[1] + input[2]) * f1 / 3;
  3793. else {
  3794. output[0] = input[0] * f1;
  3795. output[1] = input[1] * f1;
  3796. output[2] = input[2] * f1;
  3797. }
  3798. if (req_comp == 2) output[1] = 1;
  3799. if (req_comp == 4) output[3] = 1;
  3800. } else {
  3801. switch (req_comp) {
  3802. case 4: output[3] = 1; /* fallthrough */
  3803. case 3: output[0] = output[1] = output[2] = 0;
  3804. break;
  3805. case 2: output[1] = 1; /* fallthrough */
  3806. case 1: output[0] = 0;
  3807. break;
  3808. }
  3809. }
  3810. }
  3811. static float *stbi__hdr_load(stbi__context *s, int *x, int *y, int *comp, int req_comp)
  3812. {
  3813. char buffer[STBI__HDR_BUFLEN];
  3814. char *token;
  3815. int valid = 0;
  3816. int width, height;
  3817. stbi_uc *scanline;
  3818. float *hdr_data;
  3819. int len;
  3820. unsigned char count, value;
  3821. int i, j, k, c1,c2, z;
  3822. // Check identifier
  3823. if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0)
  3824. return stbi__errpf("not HDR", "Corrupt HDR image");
  3825. // Parse header
  3826. for(;;) {
  3827. token = stbi__hdr_gettoken(s,buffer);
  3828. if (token[0] == 0) break;
  3829. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  3830. }
  3831. if (!valid) return stbi__errpf("unsupported format", "Unsupported HDR format");
  3832. // Parse width and height
  3833. // can't use sscanf() if we're not using stdio!
  3834. token = stbi__hdr_gettoken(s,buffer);
  3835. if (strncmp(token, "-Y ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  3836. token += 3;
  3837. height = (int) strtol(token, &token, 10);
  3838. while (*token == ' ') ++token;
  3839. if (strncmp(token, "+X ", 3)) return stbi__errpf("unsupported data layout", "Unsupported HDR format");
  3840. token += 3;
  3841. width = (int) strtol(token, NULL, 10);
  3842. *x = width;
  3843. *y = height;
  3844. if (comp) *comp = 3;
  3845. if (req_comp == 0) req_comp = 3;
  3846. // Read data
  3847. hdr_data = (float *) stbi__malloc(height * width * req_comp * sizeof(float));
  3848. // Load image data
  3849. // image data is stored as some number of sca
  3850. if ( width < 8 || width >= 32768) {
  3851. // Read flat data
  3852. for (j=0; j < height; ++j) {
  3853. for (i=0; i < width; ++i) {
  3854. stbi_uc rgbe[4];
  3855. main_decode_loop:
  3856. stbi__getn(s, rgbe, 4);
  3857. stbi__hdr_convert(hdr_data + j * width * req_comp + i * req_comp, rgbe, req_comp);
  3858. }
  3859. }
  3860. } else {
  3861. // Read RLE-encoded data
  3862. scanline = NULL;
  3863. for (j = 0; j < height; ++j) {
  3864. c1 = stbi__get8(s);
  3865. c2 = stbi__get8(s);
  3866. len = stbi__get8(s);
  3867. if (c1 != 2 || c2 != 2 || (len & 0x80)) {
  3868. // not run-length encoded, so we have to actually use THIS data as a decoded
  3869. // pixel (note this can't be a valid pixel--one of RGB must be >= 128)
  3870. stbi_uc rgbe[4];
  3871. rgbe[0] = (stbi_uc) c1;
  3872. rgbe[1] = (stbi_uc) c2;
  3873. rgbe[2] = (stbi_uc) len;
  3874. rgbe[3] = (stbi_uc) stbi__get8(s);
  3875. stbi__hdr_convert(hdr_data, rgbe, req_comp);
  3876. i = 1;
  3877. j = 0;
  3878. free(scanline);
  3879. goto main_decode_loop; // yes, this makes no sense
  3880. }
  3881. len <<= 8;
  3882. len |= stbi__get8(s);
  3883. if (len != width) { free(hdr_data); free(scanline); return stbi__errpf("invalid decoded scanline length", "corrupt HDR"); }
  3884. if (scanline == NULL) scanline = (stbi_uc *) stbi__malloc(width * 4);
  3885. for (k = 0; k < 4; ++k) {
  3886. i = 0;
  3887. while (i < width) {
  3888. count = stbi__get8(s);
  3889. if (count > 128) {
  3890. // Run
  3891. value = stbi__get8(s);
  3892. count -= 128;
  3893. for (z = 0; z < count; ++z)
  3894. scanline[i++ * 4 + k] = value;
  3895. } else {
  3896. // Dump
  3897. for (z = 0; z < count; ++z)
  3898. scanline[i++ * 4 + k] = stbi__get8(s);
  3899. }
  3900. }
  3901. }
  3902. for (i=0; i < width; ++i)
  3903. stbi__hdr_convert(hdr_data+(j*width + i)*req_comp, scanline + i*4, req_comp);
  3904. }
  3905. free(scanline);
  3906. }
  3907. return hdr_data;
  3908. }
  3909. static int stbi__hdr_info(stbi__context *s, int *x, int *y, int *comp)
  3910. {
  3911. char buffer[STBI__HDR_BUFLEN];
  3912. char *token;
  3913. int valid = 0;
  3914. if (strcmp(stbi__hdr_gettoken(s,buffer), "#?RADIANCE") != 0) {
  3915. stbi__rewind( s );
  3916. return 0;
  3917. }
  3918. for(;;) {
  3919. token = stbi__hdr_gettoken(s,buffer);
  3920. if (token[0] == 0) break;
  3921. if (strcmp(token, "FORMAT=32-bit_rle_rgbe") == 0) valid = 1;
  3922. }
  3923. if (!valid) {
  3924. stbi__rewind( s );
  3925. return 0;
  3926. }
  3927. token = stbi__hdr_gettoken(s,buffer);
  3928. if (strncmp(token, "-Y ", 3)) {
  3929. stbi__rewind( s );
  3930. return 0;
  3931. }
  3932. token += 3;
  3933. *y = (int) strtol(token, &token, 10);
  3934. while (*token == ' ') ++token;
  3935. if (strncmp(token, "+X ", 3)) {
  3936. stbi__rewind( s );
  3937. return 0;
  3938. }
  3939. token += 3;
  3940. *x = (int) strtol(token, NULL, 10);
  3941. *comp = 3;
  3942. return 1;
  3943. }
  3944. #endif // STBI_NO_HDR
  3945. static int stbi__bmp_info(stbi__context *s, int *x, int *y, int *comp)
  3946. {
  3947. int hsz;
  3948. if (stbi__get8(s) != 'B' || stbi__get8(s) != 'M') {
  3949. stbi__rewind( s );
  3950. return 0;
  3951. }
  3952. stbi__skip(s,12);
  3953. hsz = stbi__get32le(s);
  3954. if (hsz != 12 && hsz != 40 && hsz != 56 && hsz != 108 && hsz != 124) {
  3955. stbi__rewind( s );
  3956. return 0;
  3957. }
  3958. if (hsz == 12) {
  3959. *x = stbi__get16le(s);
  3960. *y = stbi__get16le(s);
  3961. } else {
  3962. *x = stbi__get32le(s);
  3963. *y = stbi__get32le(s);
  3964. }
  3965. if (stbi__get16le(s) != 1) {
  3966. stbi__rewind( s );
  3967. return 0;
  3968. }
  3969. *comp = stbi__get16le(s) / 8;
  3970. return 1;
  3971. }
  3972. static int stbi__psd_info(stbi__context *s, int *x, int *y, int *comp)
  3973. {
  3974. int channelCount;
  3975. if (stbi__get32be(s) != 0x38425053) {
  3976. stbi__rewind( s );
  3977. return 0;
  3978. }
  3979. if (stbi__get16be(s) != 1) {
  3980. stbi__rewind( s );
  3981. return 0;
  3982. }
  3983. stbi__skip(s, 6);
  3984. channelCount = stbi__get16be(s);
  3985. if (channelCount < 0 || channelCount > 16) {
  3986. stbi__rewind( s );
  3987. return 0;
  3988. }
  3989. *y = stbi__get32be(s);
  3990. *x = stbi__get32be(s);
  3991. if (stbi__get16be(s) != 8) {
  3992. stbi__rewind( s );
  3993. return 0;
  3994. }
  3995. if (stbi__get16be(s) != 3) {
  3996. stbi__rewind( s );
  3997. return 0;
  3998. }
  3999. *comp = 4;
  4000. return 1;
  4001. }
  4002. static int stbi__pic_info(stbi__context *s, int *x, int *y, int *comp)
  4003. {
  4004. int act_comp=0,num_packets=0,chained;
  4005. stbi__pic_packet packets[10];
  4006. stbi__skip(s, 92);
  4007. *x = stbi__get16be(s);
  4008. *y = stbi__get16be(s);
  4009. if (stbi__at_eof(s)) return 0;
  4010. if ( (*x) != 0 && (1 << 28) / (*x) < (*y)) {
  4011. stbi__rewind( s );
  4012. return 0;
  4013. }
  4014. stbi__skip(s, 8);
  4015. do {
  4016. stbi__pic_packet *packet;
  4017. if (num_packets==sizeof(packets)/sizeof(packets[0]))
  4018. return 0;
  4019. packet = &packets[num_packets++];
  4020. chained = stbi__get8(s);
  4021. packet->size = stbi__get8(s);
  4022. packet->type = stbi__get8(s);
  4023. packet->channel = stbi__get8(s);
  4024. act_comp |= packet->channel;
  4025. if (stbi__at_eof(s)) {
  4026. stbi__rewind( s );
  4027. return 0;
  4028. }
  4029. if (packet->size != 8) {
  4030. stbi__rewind( s );
  4031. return 0;
  4032. }
  4033. } while (chained);
  4034. *comp = (act_comp & 0x10 ? 4 : 3);
  4035. return 1;
  4036. }
  4037. static int stbi__info_main(stbi__context *s, int *x, int *y, int *comp)
  4038. {
  4039. if (stbi__jpeg_info(s, x, y, comp))
  4040. return 1;
  4041. if (stbi__png_info(s, x, y, comp))
  4042. return 1;
  4043. if (stbi__gif_info(s, x, y, comp))
  4044. return 1;
  4045. if (stbi__bmp_info(s, x, y, comp))
  4046. return 1;
  4047. if (stbi__psd_info(s, x, y, comp))
  4048. return 1;
  4049. if (stbi__pic_info(s, x, y, comp))
  4050. return 1;
  4051. #ifndef STBI_NO_HDR
  4052. if (stbi__hdr_info(s, x, y, comp))
  4053. return 1;
  4054. #endif
  4055. // test tga last because it's a crappy test!
  4056. if (stbi__tga_info(s, x, y, comp))
  4057. return 1;
  4058. return stbi__err("unknown image type", "Image not of any known type, or corrupt");
  4059. }
  4060. #ifndef STBI_NO_STDIO
  4061. STBIDEF int stbi_info(char const *filename, int *x, int *y, int *comp)
  4062. {
  4063. FILE *f = stbi__fopen(filename, "rb");
  4064. int result;
  4065. if (!f) return stbi__err("can't fopen", "Unable to open file");
  4066. result = stbi_info_from_file(f, x, y, comp);
  4067. fclose(f);
  4068. return result;
  4069. }
  4070. STBIDEF int stbi_info_from_file(FILE *f, int *x, int *y, int *comp)
  4071. {
  4072. int r;
  4073. stbi__context s;
  4074. long pos = ftell(f);
  4075. stbi__start_file(&s, f);
  4076. r = stbi__info_main(&s,x,y,comp);
  4077. fseek(f,pos,SEEK_SET);
  4078. return r;
  4079. }
  4080. #endif // !STBI_NO_STDIO
  4081. STBIDEF int stbi_info_from_memory(stbi_uc const *buffer, int len, int *x, int *y, int *comp)
  4082. {
  4083. stbi__context s;
  4084. stbi__start_mem(&s,buffer,len);
  4085. return stbi__info_main(&s,x,y,comp);
  4086. }
  4087. STBIDEF int stbi_info_from_callbacks(stbi_io_callbacks const *c, void *user, int *x, int *y, int *comp)
  4088. {
  4089. stbi__context s;
  4090. stbi__start_callbacks(&s, (stbi_io_callbacks *) c, user);
  4091. return stbi__info_main(&s,x,y,comp);
  4092. }
  4093. #endif // STB_IMAGE_IMPLEMENTATION
  4094. /*
  4095. revision history:
  4096. 1.46 (2014-08-26)
  4097. fix broken tRNS chunk (colorkey-style transparency) in non-paletted PNG
  4098. 1.45 (2014-08-16)
  4099. fix MSVC-ARM internal compiler error by wrapping malloc
  4100. 1.44 (2014-08-07)
  4101. various warning fixes from Ronny Chevalier
  4102. 1.43 (2014-07-15)
  4103. fix MSVC-only compiler problem in code changed in 1.42
  4104. 1.42 (2014-07-09)
  4105. don't define _CRT_SECURE_NO_WARNINGS (affects user code)
  4106. fixes to stbi__cleanup_jpeg path
  4107. added STBI_ASSERT to avoid requiring assert.h
  4108. 1.41 (2014-06-25)
  4109. fix search&replace from 1.36 that messed up comments/error messages
  4110. 1.40 (2014-06-22)
  4111. fix gcc struct-initialization warning
  4112. 1.39 (2014-06-15)
  4113. fix to TGA optimization when req_comp != number of components in TGA;
  4114. fix to GIF loading because BMP wasn't rewinding (whoops, no GIFs in my test suite)
  4115. add support for BMP version 5 (more ignored fields)
  4116. 1.38 (2014-06-06)
  4117. suppress MSVC warnings on integer casts truncating values
  4118. fix accidental rename of 'skip' field of I/O
  4119. 1.37 (2014-06-04)
  4120. remove duplicate typedef
  4121. 1.36 (2014-06-03)
  4122. convert to header file single-file library
  4123. if de-iphone isn't set, load iphone images color-swapped instead of returning NULL
  4124. 1.35 (2014-05-27)
  4125. various warnings
  4126. fix broken STBI_SIMD path
  4127. fix bug where stbi_load_from_file no longer left file pointer in correct place
  4128. fix broken non-easy path for 32-bit BMP (possibly never used)
  4129. TGA optimization by Arseny Kapoulkine
  4130. 1.34 (unknown)
  4131. use STBI_NOTUSED in stbi__resample_row_generic(), fix one more leak in tga failure case
  4132. 1.33 (2011-07-14)
  4133. make stbi_is_hdr work in STBI_NO_HDR (as specified), minor compiler-friendly improvements
  4134. 1.32 (2011-07-13)
  4135. support for "info" function for all supported filetypes (SpartanJ)
  4136. 1.31 (2011-06-20)
  4137. a few more leak fixes, bug in PNG handling (SpartanJ)
  4138. 1.30 (2011-06-11)
  4139. added ability to load files via callbacks to accomidate custom input streams (Ben Wenger)
  4140. removed deprecated format-specific test/load functions
  4141. removed support for installable file formats (stbi_loader) -- would have been broken for IO callbacks anyway
  4142. error cases in bmp and tga give messages and don't leak (Raymond Barbiero, grisha)
  4143. fix inefficiency in decoding 32-bit BMP (David Woo)
  4144. 1.29 (2010-08-16)
  4145. various warning fixes from Aurelien Pocheville
  4146. 1.28 (2010-08-01)
  4147. fix bug in GIF palette transparency (SpartanJ)
  4148. 1.27 (2010-08-01)
  4149. cast-to-stbi_uc to fix warnings
  4150. 1.26 (2010-07-24)
  4151. fix bug in file buffering for PNG reported by SpartanJ
  4152. 1.25 (2010-07-17)
  4153. refix trans_data warning (Won Chun)
  4154. 1.24 (2010-07-12)
  4155. perf improvements reading from files on platforms with lock-heavy fgetc()
  4156. minor perf improvements for jpeg
  4157. deprecated type-specific functions so we'll get feedback if they're needed
  4158. attempt to fix trans_data warning (Won Chun)
  4159. 1.23 fixed bug in iPhone support
  4160. 1.22 (2010-07-10)
  4161. removed image *writing* support
  4162. stbi_info support from Jetro Lauha
  4163. GIF support from Jean-Marc Lienher
  4164. iPhone PNG-extensions from James Brown
  4165. warning-fixes from Nicolas Schulz and Janez Zemva (i.stbi__err. Janez (U+017D)emva)
  4166. 1.21 fix use of 'stbi_uc' in header (reported by jon blow)
  4167. 1.20 added support for Softimage PIC, by Tom Seddon
  4168. 1.19 bug in interlaced PNG corruption check (found by ryg)
  4169. 1.18 2008-08-02
  4170. fix a threading bug (local mutable static)
  4171. 1.17 support interlaced PNG
  4172. 1.16 major bugfix - stbi__convert_format converted one too many pixels
  4173. 1.15 initialize some fields for thread safety
  4174. 1.14 fix threadsafe conversion bug
  4175. header-file-only version (#define STBI_HEADER_FILE_ONLY before including)
  4176. 1.13 threadsafe
  4177. 1.12 const qualifiers in the API
  4178. 1.11 Support installable IDCT, colorspace conversion routines
  4179. 1.10 Fixes for 64-bit (don't use "unsigned long")
  4180. optimized upsampling by Fabian "ryg" Giesen
  4181. 1.09 Fix format-conversion for PSD code (bad global variables!)
  4182. 1.08 Thatcher Ulrich's PSD code integrated by Nicolas Schulz
  4183. 1.07 attempt to fix C++ warning/errors again
  4184. 1.06 attempt to fix C++ warning/errors again
  4185. 1.05 fix TGA loading to return correct *comp and use good luminance calc
  4186. 1.04 default float alpha is 1, not 255; use 'void *' for stbi_image_free
  4187. 1.03 bugfixes to STBI_NO_STDIO, STBI_NO_HDR
  4188. 1.02 support for (subset of) HDR files, float interface for preferred access to them
  4189. 1.01 fix bug: possible bug in handling right-side up bmps... not sure
  4190. fix bug: the stbi__bmp_load() and stbi__tga_load() functions didn't work at all
  4191. 1.00 interface to zlib that skips zlib header
  4192. 0.99 correct handling of alpha in palette
  4193. 0.98 TGA loader by lonesock; dynamically add loaders (untested)
  4194. 0.97 jpeg errors on too large a file; also catch another malloc failure
  4195. 0.96 fix detection of invalid v value - particleman@mollyrocket forum
  4196. 0.95 during header scan, seek to markers in case of padding
  4197. 0.94 STBI_NO_STDIO to disable stdio usage; rename all #defines the same
  4198. 0.93 handle jpegtran output; verbose errors
  4199. 0.92 read 4,8,16,24,32-bit BMP files of several formats
  4200. 0.91 output 24-bit Windows 3.0 BMP files
  4201. 0.90 fix a few more warnings; bump version number to approach 1.0
  4202. 0.61 bugfixes due to Marc LeBlanc, Christopher Lloyd
  4203. 0.60 fix compiling as c++
  4204. 0.59 fix warnings: merge Dave Moore's -Wall fixes
  4205. 0.58 fix bug: zlib uncompressed mode len/nlen was wrong endian
  4206. 0.57 fix bug: jpg last huffman symbol before marker was >9 bits but less than 16 available
  4207. 0.56 fix bug: zlib uncompressed mode len vs. nlen
  4208. 0.55 fix bug: restart_interval not initialized to 0
  4209. 0.54 allow NULL for 'int *comp'
  4210. 0.53 fix bug in png 3->4; speedup png decoding
  4211. 0.52 png handles req_comp=3,4 directly; minor cleanup; jpeg comments
  4212. 0.51 obey req_comp requests, 1-component jpegs return as 1-component,
  4213. on 'test' only check type, not whether we support this variant
  4214. 0.50 first released version
  4215. */