stb_image.c 143 KB

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