stb_image.c 145 KB

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