stb_image.h 154 KB

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