stb_image.h 154 KB

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