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

stb_image.h 153KB

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