basisu_enc.cpp 93 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685
  1. // basisu_enc.cpp
  2. // Copyright (C) 2019-2024 Binomial LLC. All Rights Reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. #include "basisu_enc.h"
  16. #include "basisu_resampler.h"
  17. #include "basisu_resampler_filters.h"
  18. #include "basisu_etc.h"
  19. #include "../transcoder/basisu_transcoder.h"
  20. #include "basisu_bc7enc.h"
  21. #include "jpgd.h"
  22. #include "pvpngreader.h"
  23. #include "basisu_opencl.h"
  24. #include "basisu_astc_hdr_enc.h"
  25. #include <vector>
  26. #ifndef TINYEXR_USE_ZFP
  27. #define TINYEXR_USE_ZFP (1)
  28. #endif
  29. #include <tinyexr.h>
  30. #ifndef MINIZ_HEADER_FILE_ONLY
  31. #define MINIZ_HEADER_FILE_ONLY
  32. #endif
  33. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  34. #define MINIZ_NO_ZLIB_COMPATIBLE_NAMES
  35. #endif
  36. #include "basisu_miniz.h"
  37. #if defined(_WIN32)
  38. // For QueryPerformanceCounter/QueryPerformanceFrequency
  39. #define WIN32_LEAN_AND_MEAN
  40. #include <windows.h>
  41. #endif
  42. namespace basisu
  43. {
  44. uint64_t interval_timer::g_init_ticks, interval_timer::g_freq;
  45. double interval_timer::g_timer_freq;
  46. #if BASISU_SUPPORT_SSE
  47. bool g_cpu_supports_sse41;
  48. #endif
  49. uint8_t g_hamming_dist[256] =
  50. {
  51. 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4,
  52. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  53. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  54. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  55. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  56. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  57. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  58. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  59. 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5,
  60. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  61. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  62. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  63. 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6,
  64. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  65. 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7,
  66. 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8
  67. };
  68. // This is a Public Domain 8x8 font from here:
  69. // https://github.com/dhepper/font8x8/blob/master/font8x8_basic.h
  70. const uint8_t g_debug_font8x8_basic[127 - 32 + 1][8] =
  71. {
  72. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 ( )
  73. { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!)
  74. { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (")
  75. { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#)
  76. { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($)
  77. { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%)
  78. { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&)
  79. { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (')
  80. { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (()
  81. { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ())
  82. { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*)
  83. { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+)
  84. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,)
  85. { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-)
  86. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.)
  87. { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/)
  88. { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0)
  89. { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1)
  90. { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2)
  91. { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3)
  92. { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4)
  93. { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5)
  94. { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6)
  95. { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7)
  96. { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8)
  97. { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9)
  98. { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:)
  99. { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (;)
  100. { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<)
  101. { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=)
  102. { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>)
  103. { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?)
  104. { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@)
  105. { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A)
  106. { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B)
  107. { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C)
  108. { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D)
  109. { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E)
  110. { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F)
  111. { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G)
  112. { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H)
  113. { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I)
  114. { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J)
  115. { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K)
  116. { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L)
  117. { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M)
  118. { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N)
  119. { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O)
  120. { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P)
  121. { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q)
  122. { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R)
  123. { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S)
  124. { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T)
  125. { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U)
  126. { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V)
  127. { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W)
  128. { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X)
  129. { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y)
  130. { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z)
  131. { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([)
  132. { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\)
  133. { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (])
  134. { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^)
  135. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_)
  136. { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`)
  137. { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a)
  138. { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b)
  139. { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c)
  140. { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d)
  141. { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e)
  142. { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f)
  143. { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g)
  144. { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h)
  145. { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i)
  146. { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j)
  147. { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k)
  148. { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l)
  149. { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m)
  150. { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n)
  151. { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o)
  152. { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p)
  153. { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q)
  154. { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r)
  155. { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s)
  156. { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t)
  157. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u)
  158. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v)
  159. { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w)
  160. { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x)
  161. { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y)
  162. { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z)
  163. { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({)
  164. { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|)
  165. { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (})
  166. { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~)
  167. { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F
  168. };
  169. bool g_library_initialized;
  170. std::mutex g_encoder_init_mutex;
  171. // Encoder library initialization (just call once at startup)
  172. bool basisu_encoder_init(bool use_opencl, bool opencl_force_serialization)
  173. {
  174. std::lock_guard<std::mutex> lock(g_encoder_init_mutex);
  175. if (g_library_initialized)
  176. return true;
  177. detect_sse41();
  178. basist::basisu_transcoder_init();
  179. pack_etc1_solid_color_init();
  180. //uastc_init();
  181. bc7enc_compress_block_init(); // must be after uastc_init()
  182. // Don't bother initializing the OpenCL module at all if it's been completely disabled.
  183. if (use_opencl)
  184. {
  185. opencl_init(opencl_force_serialization);
  186. }
  187. interval_timer::init(); // make sure interval_timer globals are initialized from main thread to avoid TSAN reports
  188. astc_hdr_enc_init();
  189. basist::bc6h_enc_init();
  190. g_library_initialized = true;
  191. return true;
  192. }
  193. void basisu_encoder_deinit()
  194. {
  195. opencl_deinit();
  196. g_library_initialized = false;
  197. }
  198. void error_vprintf(const char* pFmt, va_list args)
  199. {
  200. char buf[8192];
  201. #ifdef _WIN32
  202. vsprintf_s(buf, sizeof(buf), pFmt, args);
  203. #else
  204. vsnprintf(buf, sizeof(buf), pFmt, args);
  205. #endif
  206. fprintf(stderr, "ERROR: %s", buf);
  207. }
  208. void error_printf(const char *pFmt, ...)
  209. {
  210. va_list args;
  211. va_start(args, pFmt);
  212. error_vprintf(pFmt, args);
  213. va_end(args);
  214. }
  215. #if defined(_WIN32)
  216. inline void query_counter(timer_ticks* pTicks)
  217. {
  218. QueryPerformanceCounter(reinterpret_cast<LARGE_INTEGER*>(pTicks));
  219. }
  220. inline void query_counter_frequency(timer_ticks* pTicks)
  221. {
  222. QueryPerformanceFrequency(reinterpret_cast<LARGE_INTEGER*>(pTicks));
  223. }
  224. #elif defined(__APPLE__) || defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__EMSCRIPTEN__)
  225. #include <sys/time.h>
  226. inline void query_counter(timer_ticks* pTicks)
  227. {
  228. struct timeval cur_time;
  229. gettimeofday(&cur_time, NULL);
  230. *pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
  231. }
  232. inline void query_counter_frequency(timer_ticks* pTicks)
  233. {
  234. *pTicks = 1000000;
  235. }
  236. #elif defined(__GNUC__)
  237. #include <sys/timex.h>
  238. inline void query_counter(timer_ticks* pTicks)
  239. {
  240. struct timeval cur_time;
  241. gettimeofday(&cur_time, NULL);
  242. *pTicks = static_cast<unsigned long long>(cur_time.tv_sec) * 1000000ULL + static_cast<unsigned long long>(cur_time.tv_usec);
  243. }
  244. inline void query_counter_frequency(timer_ticks* pTicks)
  245. {
  246. *pTicks = 1000000;
  247. }
  248. #else
  249. #error TODO
  250. #endif
  251. interval_timer::interval_timer() : m_start_time(0), m_stop_time(0), m_started(false), m_stopped(false)
  252. {
  253. if (!g_timer_freq)
  254. init();
  255. }
  256. void interval_timer::start()
  257. {
  258. query_counter(&m_start_time);
  259. m_started = true;
  260. m_stopped = false;
  261. }
  262. void interval_timer::stop()
  263. {
  264. assert(m_started);
  265. query_counter(&m_stop_time);
  266. m_stopped = true;
  267. }
  268. double interval_timer::get_elapsed_secs() const
  269. {
  270. assert(m_started);
  271. if (!m_started)
  272. return 0;
  273. timer_ticks stop_time = m_stop_time;
  274. if (!m_stopped)
  275. query_counter(&stop_time);
  276. timer_ticks delta = stop_time - m_start_time;
  277. return delta * g_timer_freq;
  278. }
  279. void interval_timer::init()
  280. {
  281. if (!g_timer_freq)
  282. {
  283. query_counter_frequency(&g_freq);
  284. g_timer_freq = 1.0f / g_freq;
  285. query_counter(&g_init_ticks);
  286. }
  287. }
  288. timer_ticks interval_timer::get_ticks()
  289. {
  290. if (!g_timer_freq)
  291. init();
  292. timer_ticks ticks;
  293. query_counter(&ticks);
  294. return ticks - g_init_ticks;
  295. }
  296. double interval_timer::ticks_to_secs(timer_ticks ticks)
  297. {
  298. if (!g_timer_freq)
  299. init();
  300. return ticks * g_timer_freq;
  301. }
  302. float linear_to_srgb(float l)
  303. {
  304. assert(l >= 0.0f && l <= 1.0f);
  305. if (l < .0031308f)
  306. return saturate(l * 12.92f);
  307. else
  308. return saturate(1.055f * powf(l, 1.0f / 2.4f) - .055f);
  309. }
  310. float srgb_to_linear(float s)
  311. {
  312. assert(s >= 0.0f && s <= 1.0f);
  313. if (s < .04045f)
  314. return saturate(s * (1.0f / 12.92f));
  315. else
  316. return saturate(powf((s + .055f) * (1.0f / 1.055f), 2.4f));
  317. }
  318. const uint32_t MAX_32BIT_ALLOC_SIZE = 250000000;
  319. bool load_tga(const char* pFilename, image& img)
  320. {
  321. int w = 0, h = 0, n_chans = 0;
  322. uint8_t* pImage_data = read_tga(pFilename, w, h, n_chans);
  323. if ((!pImage_data) || (!w) || (!h) || ((n_chans != 3) && (n_chans != 4)))
  324. {
  325. error_printf("Failed loading .TGA image \"%s\"!\n", pFilename);
  326. if (pImage_data)
  327. free(pImage_data);
  328. return false;
  329. }
  330. if (sizeof(void *) == sizeof(uint32_t))
  331. {
  332. if (((uint64_t)w * h * n_chans) > MAX_32BIT_ALLOC_SIZE)
  333. {
  334. error_printf("Image \"%s\" is too large (%ux%u) to process in a 32-bit build!\n", pFilename, w, h);
  335. if (pImage_data)
  336. free(pImage_data);
  337. return false;
  338. }
  339. }
  340. img.resize(w, h);
  341. const uint8_t *pSrc = pImage_data;
  342. for (int y = 0; y < h; y++)
  343. {
  344. color_rgba *pDst = &img(0, y);
  345. for (int x = 0; x < w; x++)
  346. {
  347. pDst->r = pSrc[0];
  348. pDst->g = pSrc[1];
  349. pDst->b = pSrc[2];
  350. pDst->a = (n_chans == 3) ? 255 : pSrc[3];
  351. pSrc += n_chans;
  352. ++pDst;
  353. }
  354. }
  355. free(pImage_data);
  356. return true;
  357. }
  358. bool load_qoi(const char* pFilename, image& img)
  359. {
  360. return false;
  361. }
  362. bool load_png(const uint8_t *pBuf, size_t buf_size, image &img, const char *pFilename)
  363. {
  364. interval_timer tm;
  365. tm.start();
  366. if (!buf_size)
  367. return false;
  368. uint32_t width = 0, height = 0, num_chans = 0;
  369. void* pImage = pv_png::load_png(pBuf, buf_size, 4, width, height, num_chans);
  370. if (!pBuf)
  371. {
  372. error_printf("pv_png::load_png failed while loading image \"%s\"\n", pFilename);
  373. return false;
  374. }
  375. img.grant_ownership(reinterpret_cast<color_rgba*>(pImage), width, height);
  376. //debug_printf("Total load_png() time: %3.3f secs\n", tm.get_elapsed_secs());
  377. return true;
  378. }
  379. bool load_png(const char* pFilename, image& img)
  380. {
  381. uint8_vec buffer;
  382. if (!read_file_to_vec(pFilename, buffer))
  383. {
  384. error_printf("load_png: Failed reading file \"%s\"!\n", pFilename);
  385. return false;
  386. }
  387. return load_png(buffer.data(), buffer.size(), img, pFilename);
  388. }
  389. bool load_jpg(const char *pFilename, image& img)
  390. {
  391. int width = 0, height = 0, actual_comps = 0;
  392. uint8_t *pImage_data = jpgd::decompress_jpeg_image_from_file(pFilename, &width, &height, &actual_comps, 4, jpgd::jpeg_decoder::cFlagBoxChromaFiltering);
  393. if (!pImage_data)
  394. return false;
  395. img.init(pImage_data, width, height, 4);
  396. free(pImage_data);
  397. return true;
  398. }
  399. bool load_image(const char* pFilename, image& img)
  400. {
  401. std::string ext(string_get_extension(std::string(pFilename)));
  402. if (ext.length() == 0)
  403. return false;
  404. const char *pExt = ext.c_str();
  405. if (strcasecmp(pExt, "png") == 0)
  406. return load_png(pFilename, img);
  407. if (strcasecmp(pExt, "tga") == 0)
  408. return load_tga(pFilename, img);
  409. if (strcasecmp(pExt, "qoi") == 0)
  410. return load_qoi(pFilename, img);
  411. if ( (strcasecmp(pExt, "jpg") == 0) || (strcasecmp(pExt, "jfif") == 0) || (strcasecmp(pExt, "jpeg") == 0) )
  412. return load_jpg(pFilename, img);
  413. return false;
  414. }
  415. static void convert_ldr_to_hdr_image(imagef &img, const image &ldr_img, bool ldr_srgb_to_linear)
  416. {
  417. img.resize(ldr_img.get_width(), ldr_img.get_height());
  418. for (uint32_t y = 0; y < ldr_img.get_height(); y++)
  419. {
  420. for (uint32_t x = 0; x < ldr_img.get_width(); x++)
  421. {
  422. const color_rgba& c = ldr_img(x, y);
  423. vec4F& d = img(x, y);
  424. if (ldr_srgb_to_linear)
  425. {
  426. // TODO: Multiply by 100-200 nits?
  427. d[0] = srgb_to_linear(c[0] * (1.0f / 255.0f));
  428. d[1] = srgb_to_linear(c[1] * (1.0f / 255.0f));
  429. d[2] = srgb_to_linear(c[2] * (1.0f / 255.0f));
  430. }
  431. else
  432. {
  433. d[0] = c[0] * (1.0f / 255.0f);
  434. d[1] = c[1] * (1.0f / 255.0f);
  435. d[2] = c[2] * (1.0f / 255.0f);
  436. }
  437. d[3] = c[3] * (1.0f / 255.0f);
  438. }
  439. }
  440. }
  441. bool load_image_hdr(const void* pMem, size_t mem_size, imagef& img, uint32_t width, uint32_t height, hdr_image_type img_type, bool ldr_srgb_to_linear)
  442. {
  443. if ((!pMem) || (!mem_size))
  444. {
  445. assert(0);
  446. return false;
  447. }
  448. switch (img_type)
  449. {
  450. case hdr_image_type::cHITRGBAHalfFloat:
  451. {
  452. if (mem_size != width * height * sizeof(basist::half_float) * 4)
  453. {
  454. assert(0);
  455. return false;
  456. }
  457. if ((!width) || (!height))
  458. {
  459. assert(0);
  460. return false;
  461. }
  462. const basist::half_float* pSrc_image_h = static_cast<const basist::half_float *>(pMem);
  463. img.resize(width, height);
  464. for (uint32_t y = 0; y < height; y++)
  465. {
  466. for (uint32_t x = 0; x < width; x++)
  467. {
  468. const basist::half_float* pSrc_pixel = &pSrc_image_h[x * 4];
  469. vec4F& dst = img(x, y);
  470. dst[0] = basist::half_to_float(pSrc_pixel[0]);
  471. dst[1] = basist::half_to_float(pSrc_pixel[1]);
  472. dst[2] = basist::half_to_float(pSrc_pixel[2]);
  473. dst[3] = basist::half_to_float(pSrc_pixel[3]);
  474. }
  475. pSrc_image_h += (width * 4);
  476. }
  477. break;
  478. }
  479. case hdr_image_type::cHITRGBAFloat:
  480. {
  481. if (mem_size != width * height * sizeof(float) * 4)
  482. {
  483. assert(0);
  484. return false;
  485. }
  486. if ((!width) || (!height))
  487. {
  488. assert(0);
  489. return false;
  490. }
  491. img.resize(width, height);
  492. memcpy(img.get_ptr(), pMem, width * height * sizeof(float) * 4);
  493. break;
  494. }
  495. case hdr_image_type::cHITPNGImage:
  496. {
  497. image ldr_img;
  498. if (!load_png(static_cast<const uint8_t *>(pMem), mem_size, ldr_img))
  499. return false;
  500. convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear);
  501. break;
  502. }
  503. case hdr_image_type::cHITEXRImage:
  504. {
  505. if (!read_exr(pMem, mem_size, img))
  506. return false;
  507. break;
  508. }
  509. case hdr_image_type::cHITHDRImage:
  510. {
  511. uint8_vec buf(mem_size);
  512. memcpy(buf.get_ptr(), pMem, mem_size);
  513. rgbe_header_info hdr;
  514. if (!read_rgbe(buf, img, hdr))
  515. return false;
  516. break;
  517. }
  518. default:
  519. assert(0);
  520. return false;
  521. }
  522. return true;
  523. }
  524. bool load_image_hdr(const char* pFilename, imagef& img, bool ldr_srgb_to_linear)
  525. {
  526. std::string ext(string_get_extension(std::string(pFilename)));
  527. if (ext.length() == 0)
  528. return false;
  529. const char* pExt = ext.c_str();
  530. if (strcasecmp(pExt, "hdr") == 0)
  531. {
  532. rgbe_header_info rgbe_info;
  533. if (!read_rgbe(pFilename, img, rgbe_info))
  534. return false;
  535. return true;
  536. }
  537. if (strcasecmp(pExt, "exr") == 0)
  538. {
  539. int n_chans = 0;
  540. if (!read_exr(pFilename, img, n_chans))
  541. return false;
  542. return true;
  543. }
  544. // Try loading image as LDR, then optionally convert to linear light.
  545. {
  546. image ldr_img;
  547. if (!load_image(pFilename, ldr_img))
  548. return false;
  549. convert_ldr_to_hdr_image(img, ldr_img, ldr_srgb_to_linear);
  550. }
  551. return true;
  552. }
  553. bool save_png(const char* pFilename, const image &img, uint32_t image_save_flags, uint32_t grayscale_comp)
  554. {
  555. if (!img.get_total_pixels())
  556. return false;
  557. void* pPNG_data = nullptr;
  558. size_t PNG_data_size = 0;
  559. if (image_save_flags & cImageSaveGrayscale)
  560. {
  561. uint8_vec g_pixels(img.get_total_pixels());
  562. uint8_t* pDst = &g_pixels[0];
  563. for (uint32_t y = 0; y < img.get_height(); y++)
  564. for (uint32_t x = 0; x < img.get_width(); x++)
  565. *pDst++ = img(x, y)[grayscale_comp];
  566. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(g_pixels.data(), img.get_width(), img.get_height(), 1, &PNG_data_size, 1, false);
  567. }
  568. else
  569. {
  570. bool has_alpha = false;
  571. if ((image_save_flags & cImageSaveIgnoreAlpha) == 0)
  572. has_alpha = img.has_alpha();
  573. if (!has_alpha)
  574. {
  575. uint8_vec rgb_pixels(img.get_total_pixels() * 3);
  576. uint8_t* pDst = &rgb_pixels[0];
  577. for (uint32_t y = 0; y < img.get_height(); y++)
  578. {
  579. const color_rgba* pSrc = &img(0, y);
  580. for (uint32_t x = 0; x < img.get_width(); x++)
  581. {
  582. pDst[0] = pSrc->r;
  583. pDst[1] = pSrc->g;
  584. pDst[2] = pSrc->b;
  585. pSrc++;
  586. pDst += 3;
  587. }
  588. }
  589. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(rgb_pixels.data(), img.get_width(), img.get_height(), 3, &PNG_data_size, 1, false);
  590. }
  591. else
  592. {
  593. pPNG_data = buminiz::tdefl_write_image_to_png_file_in_memory_ex(img.get_ptr(), img.get_width(), img.get_height(), 4, &PNG_data_size, 1, false);
  594. }
  595. }
  596. if (!pPNG_data)
  597. return false;
  598. bool status = write_data_to_file(pFilename, pPNG_data, PNG_data_size);
  599. if (!status)
  600. {
  601. error_printf("save_png: Failed writing to filename \"%s\"!\n", pFilename);
  602. }
  603. free(pPNG_data);
  604. return status;
  605. }
  606. bool read_file_to_vec(const char* pFilename, uint8_vec& data)
  607. {
  608. FILE* pFile = nullptr;
  609. #ifdef _WIN32
  610. fopen_s(&pFile, pFilename, "rb");
  611. #else
  612. pFile = fopen(pFilename, "rb");
  613. #endif
  614. if (!pFile)
  615. return false;
  616. fseek(pFile, 0, SEEK_END);
  617. #ifdef _WIN32
  618. int64_t filesize = _ftelli64(pFile);
  619. #else
  620. int64_t filesize = ftello(pFile);
  621. #endif
  622. if (filesize < 0)
  623. {
  624. fclose(pFile);
  625. return false;
  626. }
  627. fseek(pFile, 0, SEEK_SET);
  628. if (sizeof(size_t) == sizeof(uint32_t))
  629. {
  630. if (filesize > 0x70000000)
  631. {
  632. // File might be too big to load safely in one alloc
  633. fclose(pFile);
  634. return false;
  635. }
  636. }
  637. if (!data.try_resize((size_t)filesize))
  638. {
  639. fclose(pFile);
  640. return false;
  641. }
  642. if (filesize)
  643. {
  644. if (fread(&data[0], 1, (size_t)filesize, pFile) != (size_t)filesize)
  645. {
  646. fclose(pFile);
  647. return false;
  648. }
  649. }
  650. fclose(pFile);
  651. return true;
  652. }
  653. bool read_file_to_data(const char* pFilename, void *pData, size_t len)
  654. {
  655. assert(pData && len);
  656. if ((!pData) || (!len))
  657. return false;
  658. FILE* pFile = nullptr;
  659. #ifdef _WIN32
  660. fopen_s(&pFile, pFilename, "rb");
  661. #else
  662. pFile = fopen(pFilename, "rb");
  663. #endif
  664. if (!pFile)
  665. return false;
  666. fseek(pFile, 0, SEEK_END);
  667. #ifdef _WIN32
  668. int64_t filesize = _ftelli64(pFile);
  669. #else
  670. int64_t filesize = ftello(pFile);
  671. #endif
  672. if ((filesize < 0) || ((size_t)filesize < len))
  673. {
  674. fclose(pFile);
  675. return false;
  676. }
  677. fseek(pFile, 0, SEEK_SET);
  678. if (fread(pData, 1, (size_t)len, pFile) != (size_t)len)
  679. {
  680. fclose(pFile);
  681. return false;
  682. }
  683. fclose(pFile);
  684. return true;
  685. }
  686. bool write_data_to_file(const char* pFilename, const void* pData, size_t len)
  687. {
  688. FILE* pFile = nullptr;
  689. #ifdef _WIN32
  690. fopen_s(&pFile, pFilename, "wb");
  691. #else
  692. pFile = fopen(pFilename, "wb");
  693. #endif
  694. if (!pFile)
  695. return false;
  696. if (len)
  697. {
  698. if (fwrite(pData, 1, len, pFile) != len)
  699. {
  700. fclose(pFile);
  701. return false;
  702. }
  703. }
  704. return fclose(pFile) != EOF;
  705. }
  706. bool image_resample(const image &src, image &dst, bool srgb,
  707. const char *pFilter, float filter_scale,
  708. bool wrapping,
  709. uint32_t first_comp, uint32_t num_comps)
  710. {
  711. assert((first_comp + num_comps) <= 4);
  712. const int cMaxComps = 4;
  713. const uint32_t src_w = src.get_width(), src_h = src.get_height();
  714. const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
  715. if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
  716. {
  717. printf("Image is too large!\n");
  718. return false;
  719. }
  720. if (!src_w || !src_h || !dst_w || !dst_h)
  721. return false;
  722. if ((num_comps < 1) || (num_comps > cMaxComps))
  723. return false;
  724. if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
  725. {
  726. printf("Image is too large!\n");
  727. return false;
  728. }
  729. if ((src_w == dst_w) && (src_h == dst_h))
  730. {
  731. dst = src;
  732. return true;
  733. }
  734. float srgb_to_linear_table[256];
  735. if (srgb)
  736. {
  737. for (int i = 0; i < 256; ++i)
  738. srgb_to_linear_table[i] = srgb_to_linear((float)i * (1.0f/255.0f));
  739. }
  740. const int LINEAR_TO_SRGB_TABLE_SIZE = 8192;
  741. uint8_t linear_to_srgb_table[LINEAR_TO_SRGB_TABLE_SIZE];
  742. if (srgb)
  743. {
  744. for (int i = 0; i < LINEAR_TO_SRGB_TABLE_SIZE; ++i)
  745. linear_to_srgb_table[i] = (uint8_t)clamp<int>((int)(255.0f * linear_to_srgb((float)i * (1.0f / (LINEAR_TO_SRGB_TABLE_SIZE - 1))) + .5f), 0, 255);
  746. }
  747. std::vector<float> samples[cMaxComps];
  748. Resampler *resamplers[cMaxComps];
  749. resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
  750. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
  751. pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
  752. samples[0].resize(src_w);
  753. for (uint32_t i = 1; i < num_comps; ++i)
  754. {
  755. resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
  756. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 0.0f, 1.0f,
  757. pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
  758. samples[i].resize(src_w);
  759. }
  760. uint32_t dst_y = 0;
  761. for (uint32_t src_y = 0; src_y < src_h; ++src_y)
  762. {
  763. const color_rgba *pSrc = &src(0, src_y);
  764. // Put source lines into resampler(s)
  765. for (uint32_t x = 0; x < src_w; ++x)
  766. {
  767. for (uint32_t c = 0; c < num_comps; ++c)
  768. {
  769. const uint32_t comp_index = first_comp + c;
  770. const uint32_t v = (*pSrc)[comp_index];
  771. if (!srgb || (comp_index == 3))
  772. samples[c][x] = v * (1.0f / 255.0f);
  773. else
  774. samples[c][x] = srgb_to_linear_table[v];
  775. }
  776. pSrc++;
  777. }
  778. for (uint32_t c = 0; c < num_comps; ++c)
  779. {
  780. if (!resamplers[c]->put_line(&samples[c][0]))
  781. {
  782. for (uint32_t i = 0; i < num_comps; i++)
  783. delete resamplers[i];
  784. return false;
  785. }
  786. }
  787. // Now retrieve any output lines
  788. for (;;)
  789. {
  790. uint32_t c;
  791. for (c = 0; c < num_comps; ++c)
  792. {
  793. const uint32_t comp_index = first_comp + c;
  794. const float *pOutput_samples = resamplers[c]->get_line();
  795. if (!pOutput_samples)
  796. break;
  797. const bool linear_flag = !srgb || (comp_index == 3);
  798. color_rgba *pDst = &dst(0, dst_y);
  799. for (uint32_t x = 0; x < dst_w; x++)
  800. {
  801. // TODO: Add dithering
  802. if (linear_flag)
  803. {
  804. int j = (int)(255.0f * pOutput_samples[x] + .5f);
  805. (*pDst)[comp_index] = (uint8_t)clamp<int>(j, 0, 255);
  806. }
  807. else
  808. {
  809. int j = (int)((LINEAR_TO_SRGB_TABLE_SIZE - 1) * pOutput_samples[x] + .5f);
  810. (*pDst)[comp_index] = linear_to_srgb_table[clamp<int>(j, 0, LINEAR_TO_SRGB_TABLE_SIZE - 1)];
  811. }
  812. pDst++;
  813. }
  814. }
  815. if (c < num_comps)
  816. break;
  817. ++dst_y;
  818. }
  819. }
  820. for (uint32_t i = 0; i < num_comps; ++i)
  821. delete resamplers[i];
  822. return true;
  823. }
  824. bool image_resample(const imagef& src, imagef& dst,
  825. const char* pFilter, float filter_scale,
  826. bool wrapping,
  827. uint32_t first_comp, uint32_t num_comps)
  828. {
  829. assert((first_comp + num_comps) <= 4);
  830. const int cMaxComps = 4;
  831. const uint32_t src_w = src.get_width(), src_h = src.get_height();
  832. const uint32_t dst_w = dst.get_width(), dst_h = dst.get_height();
  833. if (maximum(src_w, src_h) > BASISU_RESAMPLER_MAX_DIMENSION)
  834. {
  835. printf("Image is too large!\n");
  836. return false;
  837. }
  838. if (!src_w || !src_h || !dst_w || !dst_h)
  839. return false;
  840. if ((num_comps < 1) || (num_comps > cMaxComps))
  841. return false;
  842. if ((minimum(dst_w, dst_h) < 1) || (maximum(dst_w, dst_h) > BASISU_RESAMPLER_MAX_DIMENSION))
  843. {
  844. printf("Image is too large!\n");
  845. return false;
  846. }
  847. if ((src_w == dst_w) && (src_h == dst_h))
  848. {
  849. dst = src;
  850. return true;
  851. }
  852. std::vector<float> samples[cMaxComps];
  853. Resampler* resamplers[cMaxComps];
  854. resamplers[0] = new Resampler(src_w, src_h, dst_w, dst_h,
  855. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
  856. pFilter, nullptr, nullptr, filter_scale, filter_scale, 0, 0);
  857. samples[0].resize(src_w);
  858. for (uint32_t i = 1; i < num_comps; ++i)
  859. {
  860. resamplers[i] = new Resampler(src_w, src_h, dst_w, dst_h,
  861. wrapping ? Resampler::BOUNDARY_WRAP : Resampler::BOUNDARY_CLAMP, 1.0f, 0.0f, // no clamping
  862. pFilter, resamplers[0]->get_clist_x(), resamplers[0]->get_clist_y(), filter_scale, filter_scale, 0, 0);
  863. samples[i].resize(src_w);
  864. }
  865. uint32_t dst_y = 0;
  866. for (uint32_t src_y = 0; src_y < src_h; ++src_y)
  867. {
  868. const vec4F* pSrc = &src(0, src_y);
  869. // Put source lines into resampler(s)
  870. for (uint32_t x = 0; x < src_w; ++x)
  871. {
  872. for (uint32_t c = 0; c < num_comps; ++c)
  873. {
  874. const uint32_t comp_index = first_comp + c;
  875. const float v = (*pSrc)[comp_index];
  876. samples[c][x] = v;
  877. }
  878. pSrc++;
  879. }
  880. for (uint32_t c = 0; c < num_comps; ++c)
  881. {
  882. if (!resamplers[c]->put_line(&samples[c][0]))
  883. {
  884. for (uint32_t i = 0; i < num_comps; i++)
  885. delete resamplers[i];
  886. return false;
  887. }
  888. }
  889. // Now retrieve any output lines
  890. for (;;)
  891. {
  892. uint32_t c;
  893. for (c = 0; c < num_comps; ++c)
  894. {
  895. const uint32_t comp_index = first_comp + c;
  896. const float* pOutput_samples = resamplers[c]->get_line();
  897. if (!pOutput_samples)
  898. break;
  899. vec4F* pDst = &dst(0, dst_y);
  900. for (uint32_t x = 0; x < dst_w; x++)
  901. {
  902. (*pDst)[comp_index] = pOutput_samples[x];
  903. pDst++;
  904. }
  905. }
  906. if (c < num_comps)
  907. break;
  908. ++dst_y;
  909. }
  910. }
  911. for (uint32_t i = 0; i < num_comps; ++i)
  912. delete resamplers[i];
  913. return true;
  914. }
  915. void canonical_huffman_calculate_minimum_redundancy(sym_freq *A, int num_syms)
  916. {
  917. // See the paper "In-Place Calculation of Minimum Redundancy Codes" by Moffat and Katajainen
  918. if (!num_syms)
  919. return;
  920. if (1 == num_syms)
  921. {
  922. A[0].m_key = 1;
  923. return;
  924. }
  925. A[0].m_key += A[1].m_key;
  926. int s = 2, r = 0, next;
  927. for (next = 1; next < (num_syms - 1); ++next)
  928. {
  929. if ((s >= num_syms) || (A[r].m_key < A[s].m_key))
  930. {
  931. A[next].m_key = A[r].m_key;
  932. A[r].m_key = next;
  933. ++r;
  934. }
  935. else
  936. {
  937. A[next].m_key = A[s].m_key;
  938. ++s;
  939. }
  940. if ((s >= num_syms) || ((r < next) && A[r].m_key < A[s].m_key))
  941. {
  942. A[next].m_key = A[next].m_key + A[r].m_key;
  943. A[r].m_key = next;
  944. ++r;
  945. }
  946. else
  947. {
  948. A[next].m_key = A[next].m_key + A[s].m_key;
  949. ++s;
  950. }
  951. }
  952. A[num_syms - 2].m_key = 0;
  953. for (next = num_syms - 3; next >= 0; --next)
  954. {
  955. A[next].m_key = 1 + A[A[next].m_key].m_key;
  956. }
  957. int num_avail = 1, num_used = 0, depth = 0;
  958. r = num_syms - 2;
  959. next = num_syms - 1;
  960. while (num_avail > 0)
  961. {
  962. for ( ; (r >= 0) && ((int)A[r].m_key == depth); ++num_used, --r )
  963. ;
  964. for ( ; num_avail > num_used; --next, --num_avail)
  965. A[next].m_key = depth;
  966. num_avail = 2 * num_used;
  967. num_used = 0;
  968. ++depth;
  969. }
  970. }
  971. void canonical_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
  972. {
  973. int i;
  974. uint32_t total = 0;
  975. if (code_list_len <= 1)
  976. return;
  977. for (i = max_code_size + 1; i <= cHuffmanMaxSupportedInternalCodeSize; i++)
  978. pNum_codes[max_code_size] += pNum_codes[i];
  979. for (i = max_code_size; i > 0; i--)
  980. total += (((uint32_t)pNum_codes[i]) << (max_code_size - i));
  981. while (total != (1UL << max_code_size))
  982. {
  983. pNum_codes[max_code_size]--;
  984. for (i = max_code_size - 1; i > 0; i--)
  985. {
  986. if (pNum_codes[i])
  987. {
  988. pNum_codes[i]--;
  989. pNum_codes[i + 1] += 2;
  990. break;
  991. }
  992. }
  993. total--;
  994. }
  995. }
  996. sym_freq *canonical_huffman_radix_sort_syms(uint32_t num_syms, sym_freq *pSyms0, sym_freq *pSyms1)
  997. {
  998. uint32_t total_passes = 2, pass_shift, pass, i, hist[256 * 2];
  999. sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1;
  1000. clear_obj(hist);
  1001. for (i = 0; i < num_syms; i++)
  1002. {
  1003. uint32_t freq = pSyms0[i].m_key;
  1004. // We scale all input frequencies to 16-bits.
  1005. assert(freq <= UINT16_MAX);
  1006. hist[freq & 0xFF]++;
  1007. hist[256 + ((freq >> 8) & 0xFF)]++;
  1008. }
  1009. while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256]))
  1010. total_passes--;
  1011. for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
  1012. {
  1013. const uint32_t *pHist = &hist[pass << 8];
  1014. uint32_t offsets[256], cur_ofs = 0;
  1015. for (i = 0; i < 256; i++)
  1016. {
  1017. offsets[i] = cur_ofs;
  1018. cur_ofs += pHist[i];
  1019. }
  1020. for (i = 0; i < num_syms; i++)
  1021. pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
  1022. sym_freq *t = pCur_syms;
  1023. pCur_syms = pNew_syms;
  1024. pNew_syms = t;
  1025. }
  1026. return pCur_syms;
  1027. }
  1028. bool huffman_encoding_table::init(uint32_t num_syms, const uint16_t *pFreq, uint32_t max_code_size)
  1029. {
  1030. if (max_code_size > cHuffmanMaxSupportedCodeSize)
  1031. return false;
  1032. if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
  1033. return false;
  1034. uint32_t total_used_syms = 0;
  1035. for (uint32_t i = 0; i < num_syms; i++)
  1036. if (pFreq[i])
  1037. total_used_syms++;
  1038. if (!total_used_syms)
  1039. return false;
  1040. std::vector<sym_freq> sym_freq0(total_used_syms), sym_freq1(total_used_syms);
  1041. for (uint32_t i = 0, j = 0; i < num_syms; i++)
  1042. {
  1043. if (pFreq[i])
  1044. {
  1045. sym_freq0[j].m_key = pFreq[i];
  1046. sym_freq0[j++].m_sym_index = static_cast<uint16_t>(i);
  1047. }
  1048. }
  1049. sym_freq *pSym_freq = canonical_huffman_radix_sort_syms(total_used_syms, &sym_freq0[0], &sym_freq1[0]);
  1050. canonical_huffman_calculate_minimum_redundancy(pSym_freq, total_used_syms);
  1051. int num_codes[cHuffmanMaxSupportedInternalCodeSize + 1];
  1052. clear_obj(num_codes);
  1053. for (uint32_t i = 0; i < total_used_syms; i++)
  1054. {
  1055. if (pSym_freq[i].m_key > cHuffmanMaxSupportedInternalCodeSize)
  1056. return false;
  1057. num_codes[pSym_freq[i].m_key]++;
  1058. }
  1059. canonical_huffman_enforce_max_code_size(num_codes, total_used_syms, max_code_size);
  1060. m_code_sizes.resize(0);
  1061. m_code_sizes.resize(num_syms);
  1062. m_codes.resize(0);
  1063. m_codes.resize(num_syms);
  1064. for (uint32_t i = 1, j = total_used_syms; i <= max_code_size; i++)
  1065. for (uint32_t l = num_codes[i]; l > 0; l--)
  1066. m_code_sizes[pSym_freq[--j].m_sym_index] = static_cast<uint8_t>(i);
  1067. uint32_t next_code[cHuffmanMaxSupportedInternalCodeSize + 1];
  1068. next_code[1] = 0;
  1069. for (uint32_t j = 0, i = 2; i <= max_code_size; i++)
  1070. next_code[i] = j = ((j + num_codes[i - 1]) << 1);
  1071. for (uint32_t i = 0; i < num_syms; i++)
  1072. {
  1073. uint32_t rev_code = 0, code, code_size;
  1074. if ((code_size = m_code_sizes[i]) == 0)
  1075. continue;
  1076. if (code_size > cHuffmanMaxSupportedInternalCodeSize)
  1077. return false;
  1078. code = next_code[code_size]++;
  1079. for (uint32_t l = code_size; l > 0; l--, code >>= 1)
  1080. rev_code = (rev_code << 1) | (code & 1);
  1081. m_codes[i] = static_cast<uint16_t>(rev_code);
  1082. }
  1083. return true;
  1084. }
  1085. bool huffman_encoding_table::init(uint32_t num_syms, const uint32_t *pSym_freq, uint32_t max_code_size)
  1086. {
  1087. if ((!num_syms) || (num_syms > cHuffmanMaxSyms))
  1088. return false;
  1089. uint16_vec sym_freq(num_syms);
  1090. uint32_t max_freq = 0;
  1091. for (uint32_t i = 0; i < num_syms; i++)
  1092. max_freq = maximum(max_freq, pSym_freq[i]);
  1093. if (max_freq < UINT16_MAX)
  1094. {
  1095. for (uint32_t i = 0; i < num_syms; i++)
  1096. sym_freq[i] = static_cast<uint16_t>(pSym_freq[i]);
  1097. }
  1098. else
  1099. {
  1100. for (uint32_t i = 0; i < num_syms; i++)
  1101. {
  1102. if (pSym_freq[i])
  1103. {
  1104. uint32_t f = static_cast<uint32_t>((static_cast<uint64_t>(pSym_freq[i]) * 65534U + (max_freq >> 1)) / max_freq);
  1105. sym_freq[i] = static_cast<uint16_t>(clamp<uint32_t>(f, 1, 65534));
  1106. }
  1107. }
  1108. }
  1109. return init(num_syms, &sym_freq[0], max_code_size);
  1110. }
  1111. void bitwise_coder::end_nonzero_run(uint16_vec &syms, uint32_t &run_size, uint32_t len)
  1112. {
  1113. if (run_size)
  1114. {
  1115. if (run_size < cHuffmanSmallRepeatSizeMin)
  1116. {
  1117. while (run_size--)
  1118. syms.push_back(static_cast<uint16_t>(len));
  1119. }
  1120. else if (run_size <= cHuffmanSmallRepeatSizeMax)
  1121. {
  1122. syms.push_back(static_cast<uint16_t>(cHuffmanSmallRepeatCode | ((run_size - cHuffmanSmallRepeatSizeMin) << 6)));
  1123. }
  1124. else
  1125. {
  1126. assert((run_size >= cHuffmanBigRepeatSizeMin) && (run_size <= cHuffmanBigRepeatSizeMax));
  1127. syms.push_back(static_cast<uint16_t>(cHuffmanBigRepeatCode | ((run_size - cHuffmanBigRepeatSizeMin) << 6)));
  1128. }
  1129. }
  1130. run_size = 0;
  1131. }
  1132. void bitwise_coder::end_zero_run(uint16_vec &syms, uint32_t &run_size)
  1133. {
  1134. if (run_size)
  1135. {
  1136. if (run_size < cHuffmanSmallZeroRunSizeMin)
  1137. {
  1138. while (run_size--)
  1139. syms.push_back(0);
  1140. }
  1141. else if (run_size <= cHuffmanSmallZeroRunSizeMax)
  1142. {
  1143. syms.push_back(static_cast<uint16_t>(cHuffmanSmallZeroRunCode | ((run_size - cHuffmanSmallZeroRunSizeMin) << 6)));
  1144. }
  1145. else
  1146. {
  1147. assert((run_size >= cHuffmanBigZeroRunSizeMin) && (run_size <= cHuffmanBigZeroRunSizeMax));
  1148. syms.push_back(static_cast<uint16_t>(cHuffmanBigZeroRunCode | ((run_size - cHuffmanBigZeroRunSizeMin) << 6)));
  1149. }
  1150. }
  1151. run_size = 0;
  1152. }
  1153. uint32_t bitwise_coder::emit_huffman_table(const huffman_encoding_table &tab)
  1154. {
  1155. const uint64_t start_bits = m_total_bits;
  1156. const uint8_vec &code_sizes = tab.get_code_sizes();
  1157. uint32_t total_used = tab.get_total_used_codes();
  1158. put_bits(total_used, cHuffmanMaxSymsLog2);
  1159. if (!total_used)
  1160. return 0;
  1161. uint16_vec syms;
  1162. syms.reserve(total_used + 16);
  1163. uint32_t prev_code_len = UINT_MAX, zero_run_size = 0, nonzero_run_size = 0;
  1164. for (uint32_t i = 0; i <= total_used; ++i)
  1165. {
  1166. const uint32_t code_len = (i == total_used) ? 0xFF : code_sizes[i];
  1167. assert((code_len == 0xFF) || (code_len <= 16));
  1168. if (code_len)
  1169. {
  1170. end_zero_run(syms, zero_run_size);
  1171. if (code_len != prev_code_len)
  1172. {
  1173. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1174. if (code_len != 0xFF)
  1175. syms.push_back(static_cast<uint16_t>(code_len));
  1176. }
  1177. else if (++nonzero_run_size == cHuffmanBigRepeatSizeMax)
  1178. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1179. }
  1180. else
  1181. {
  1182. end_nonzero_run(syms, nonzero_run_size, prev_code_len);
  1183. if (++zero_run_size == cHuffmanBigZeroRunSizeMax)
  1184. end_zero_run(syms, zero_run_size);
  1185. }
  1186. prev_code_len = code_len;
  1187. }
  1188. histogram h(cHuffmanTotalCodelengthCodes);
  1189. for (uint32_t i = 0; i < syms.size(); i++)
  1190. h.inc(syms[i] & 63);
  1191. huffman_encoding_table ct;
  1192. if (!ct.init(h, 7))
  1193. return 0;
  1194. assert(cHuffmanTotalSortedCodelengthCodes == cHuffmanTotalCodelengthCodes);
  1195. uint32_t total_codelength_codes;
  1196. for (total_codelength_codes = cHuffmanTotalSortedCodelengthCodes; total_codelength_codes > 0; total_codelength_codes--)
  1197. if (ct.get_code_sizes()[g_huffman_sorted_codelength_codes[total_codelength_codes - 1]])
  1198. break;
  1199. assert(total_codelength_codes);
  1200. put_bits(total_codelength_codes, 5);
  1201. for (uint32_t i = 0; i < total_codelength_codes; i++)
  1202. put_bits(ct.get_code_sizes()[g_huffman_sorted_codelength_codes[i]], 3);
  1203. for (uint32_t i = 0; i < syms.size(); ++i)
  1204. {
  1205. const uint32_t l = syms[i] & 63, e = syms[i] >> 6;
  1206. put_code(l, ct);
  1207. if (l == cHuffmanSmallZeroRunCode)
  1208. put_bits(e, cHuffmanSmallZeroRunExtraBits);
  1209. else if (l == cHuffmanBigZeroRunCode)
  1210. put_bits(e, cHuffmanBigZeroRunExtraBits);
  1211. else if (l == cHuffmanSmallRepeatCode)
  1212. put_bits(e, cHuffmanSmallRepeatExtraBits);
  1213. else if (l == cHuffmanBigRepeatCode)
  1214. put_bits(e, cHuffmanBigRepeatExtraBits);
  1215. }
  1216. return (uint32_t)(m_total_bits - start_bits);
  1217. }
  1218. bool huffman_test(int rand_seed)
  1219. {
  1220. histogram h(19);
  1221. // Feed in a fibonacci sequence to force large codesizes
  1222. h[0] += 1; h[1] += 1; h[2] += 2; h[3] += 3;
  1223. h[4] += 5; h[5] += 8; h[6] += 13; h[7] += 21;
  1224. h[8] += 34; h[9] += 55; h[10] += 89; h[11] += 144;
  1225. h[12] += 233; h[13] += 377; h[14] += 610; h[15] += 987;
  1226. h[16] += 1597; h[17] += 2584; h[18] += 4181;
  1227. huffman_encoding_table etab;
  1228. etab.init(h, 16);
  1229. {
  1230. bitwise_coder c;
  1231. c.init(1024);
  1232. c.emit_huffman_table(etab);
  1233. for (int i = 0; i < 19; i++)
  1234. c.put_code(i, etab);
  1235. c.flush();
  1236. basist::bitwise_decoder d;
  1237. d.init(&c.get_bytes()[0], static_cast<uint32_t>(c.get_bytes().size()));
  1238. basist::huffman_decoding_table dtab;
  1239. bool success = d.read_huffman_table(dtab);
  1240. if (!success)
  1241. {
  1242. assert(0);
  1243. printf("Failure 5\n");
  1244. return false;
  1245. }
  1246. for (uint32_t i = 0; i < 19; i++)
  1247. {
  1248. uint32_t s = d.decode_huffman(dtab);
  1249. if (s != i)
  1250. {
  1251. assert(0);
  1252. printf("Failure 5\n");
  1253. return false;
  1254. }
  1255. }
  1256. }
  1257. basisu::rand r;
  1258. r.seed(rand_seed);
  1259. for (int iter = 0; iter < 500000; iter++)
  1260. {
  1261. printf("%u\n", iter);
  1262. uint32_t max_sym = r.irand(0, 8193);
  1263. uint32_t num_codes = r.irand(1, 10000);
  1264. uint_vec syms(num_codes);
  1265. for (uint32_t i = 0; i < num_codes; i++)
  1266. {
  1267. if (r.bit())
  1268. syms[i] = r.irand(0, max_sym);
  1269. else
  1270. {
  1271. int s = (int)(r.gaussian((float)max_sym / 2, (float)maximum<int>(1, max_sym / 2)) + .5f);
  1272. s = basisu::clamp<int>(s, 0, max_sym);
  1273. syms[i] = s;
  1274. }
  1275. }
  1276. histogram h1(max_sym + 1);
  1277. for (uint32_t i = 0; i < num_codes; i++)
  1278. h1[syms[i]]++;
  1279. huffman_encoding_table etab2;
  1280. if (!etab2.init(h1, 16))
  1281. {
  1282. assert(0);
  1283. printf("Failed 0\n");
  1284. return false;
  1285. }
  1286. bitwise_coder c;
  1287. c.init(1024);
  1288. c.emit_huffman_table(etab2);
  1289. for (uint32_t i = 0; i < num_codes; i++)
  1290. c.put_code(syms[i], etab2);
  1291. c.flush();
  1292. basist::bitwise_decoder d;
  1293. d.init(&c.get_bytes()[0], (uint32_t)c.get_bytes().size());
  1294. basist::huffman_decoding_table dtab;
  1295. bool success = d.read_huffman_table(dtab);
  1296. if (!success)
  1297. {
  1298. assert(0);
  1299. printf("Failed 2\n");
  1300. return false;
  1301. }
  1302. for (uint32_t i = 0; i < num_codes; i++)
  1303. {
  1304. uint32_t s = d.decode_huffman(dtab);
  1305. if (s != syms[i])
  1306. {
  1307. assert(0);
  1308. printf("Failed 4\n");
  1309. return false;
  1310. }
  1311. }
  1312. }
  1313. return true;
  1314. }
  1315. void palette_index_reorderer::init(uint32_t num_indices, const uint32_t *pIndices, uint32_t num_syms, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1316. {
  1317. assert((num_syms > 0) && (num_indices > 0));
  1318. assert((dist_func_weight >= 0.0f) && (dist_func_weight <= 1.0f));
  1319. clear();
  1320. m_remap_table.resize(num_syms);
  1321. m_entries_picked.reserve(num_syms);
  1322. m_total_count_to_picked.resize(num_syms);
  1323. if (num_indices <= 1)
  1324. return;
  1325. prepare_hist(num_syms, num_indices, pIndices);
  1326. find_initial(num_syms);
  1327. while (m_entries_to_do.size())
  1328. {
  1329. // Find the best entry to move into the picked list.
  1330. uint32_t best_entry;
  1331. double best_count;
  1332. find_next_entry(best_entry, best_count, pDist_func, pCtx, dist_func_weight);
  1333. // We now have chosen an entry to place in the picked list, now determine which side it goes on.
  1334. const uint32_t entry_to_move = m_entries_to_do[best_entry];
  1335. float side = pick_side(num_syms, entry_to_move, pDist_func, pCtx, dist_func_weight);
  1336. // Put entry_to_move either on the "left" or "right" side of the picked entries
  1337. if (side <= 0)
  1338. m_entries_picked.push_back(entry_to_move);
  1339. else
  1340. m_entries_picked.insert(m_entries_picked.begin(), entry_to_move);
  1341. // Erase best_entry from the todo list
  1342. m_entries_to_do.erase(m_entries_to_do.begin() + best_entry);
  1343. // We've just moved best_entry to the picked list, so now we need to update m_total_count_to_picked[] to factor the additional count to best_entry
  1344. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1345. m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], entry_to_move, num_syms);
  1346. }
  1347. for (uint32_t i = 0; i < num_syms; i++)
  1348. m_remap_table[m_entries_picked[i]] = i;
  1349. }
  1350. void palette_index_reorderer::prepare_hist(uint32_t num_syms, uint32_t num_indices, const uint32_t *pIndices)
  1351. {
  1352. m_hist.resize(0);
  1353. m_hist.resize(num_syms * num_syms);
  1354. for (uint32_t i = 0; i < num_indices; i++)
  1355. {
  1356. const uint32_t idx = pIndices[i];
  1357. inc_hist(idx, (i < (num_indices - 1)) ? pIndices[i + 1] : -1, num_syms);
  1358. inc_hist(idx, (i > 0) ? pIndices[i - 1] : -1, num_syms);
  1359. }
  1360. }
  1361. void palette_index_reorderer::find_initial(uint32_t num_syms)
  1362. {
  1363. uint32_t max_count = 0, max_index = 0;
  1364. for (uint32_t i = 0; i < num_syms * num_syms; i++)
  1365. if (m_hist[i] > max_count)
  1366. max_count = m_hist[i], max_index = i;
  1367. uint32_t a = max_index / num_syms, b = max_index % num_syms;
  1368. const uint32_t ofs = m_entries_picked.size();
  1369. m_entries_picked.push_back(a);
  1370. m_entries_picked.push_back(b);
  1371. for (uint32_t i = 0; i < num_syms; i++)
  1372. if ((i != m_entries_picked[ofs + 1]) && (i != m_entries_picked[ofs]))
  1373. m_entries_to_do.push_back(i);
  1374. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1375. for (uint32_t j = 0; j < m_entries_picked.size(); j++)
  1376. m_total_count_to_picked[m_entries_to_do[i]] += get_hist(m_entries_to_do[i], m_entries_picked[j], num_syms);
  1377. }
  1378. void palette_index_reorderer::find_next_entry(uint32_t &best_entry, double &best_count, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1379. {
  1380. best_entry = 0;
  1381. best_count = 0;
  1382. for (uint32_t i = 0; i < m_entries_to_do.size(); i++)
  1383. {
  1384. const uint32_t u = m_entries_to_do[i];
  1385. double total_count = m_total_count_to_picked[u];
  1386. if (pDist_func)
  1387. {
  1388. float w = maximum<float>((*pDist_func)(u, m_entries_picked.front(), pCtx), (*pDist_func)(u, m_entries_picked.back(), pCtx));
  1389. assert((w >= 0.0f) && (w <= 1.0f));
  1390. total_count = (total_count + 1.0f) * lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, w);
  1391. }
  1392. if (total_count <= best_count)
  1393. continue;
  1394. best_entry = i;
  1395. best_count = total_count;
  1396. }
  1397. }
  1398. float palette_index_reorderer::pick_side(uint32_t num_syms, uint32_t entry_to_move, pEntry_dist_func pDist_func, void *pCtx, float dist_func_weight)
  1399. {
  1400. float which_side = 0;
  1401. int l_count = 0, r_count = 0;
  1402. for (uint32_t j = 0; j < m_entries_picked.size(); j++)
  1403. {
  1404. const int count = get_hist(entry_to_move, m_entries_picked[j], num_syms), r = ((int)m_entries_picked.size() + 1 - 2 * (j + 1));
  1405. which_side += static_cast<float>(r * count);
  1406. if (r >= 0)
  1407. l_count += r * count;
  1408. else
  1409. r_count += -r * count;
  1410. }
  1411. if (pDist_func)
  1412. {
  1413. float w_left = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.front(), pCtx));
  1414. float w_right = lerp(1.0f - dist_func_weight, 1.0f + dist_func_weight, (*pDist_func)(entry_to_move, m_entries_picked.back(), pCtx));
  1415. which_side = w_left * l_count - w_right * r_count;
  1416. }
  1417. return which_side;
  1418. }
  1419. void image_metrics::calc(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool log)
  1420. {
  1421. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1422. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1423. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1424. double max_e = -1e+30f;
  1425. double sum = 0.0f, sum_sqr = 0.0f;
  1426. m_has_neg = false;
  1427. m_any_abnormal = false;
  1428. m_hf_mag_overflow = false;
  1429. for (uint32_t y = 0; y < height; y++)
  1430. {
  1431. for (uint32_t x = 0; x < width; x++)
  1432. {
  1433. const vec4F& ca = a(x, y), &cb = b(x, y);
  1434. if (total_chans)
  1435. {
  1436. for (uint32_t c = 0; c < total_chans; c++)
  1437. {
  1438. float fa = ca[first_chan + c], fb = cb[first_chan + c];
  1439. if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
  1440. m_hf_mag_overflow = true;
  1441. if ((fa < 0.0f) || (fb < 0.0f))
  1442. m_has_neg = true;
  1443. if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
  1444. m_any_abnormal = true;
  1445. const double delta = fabs(fa - fb);
  1446. max_e = basisu::maximum<double>(max_e, delta);
  1447. if (log)
  1448. {
  1449. double log2_delta = log2f(basisu::maximum(0.0f, fa) + 1.0f) - log2f(basisu::maximum(0.0f, fb) + 1.0f);
  1450. sum += fabs(log2_delta);
  1451. sum_sqr += log2_delta * log2_delta;
  1452. }
  1453. else
  1454. {
  1455. sum += fabs(delta);
  1456. sum_sqr += delta * delta;
  1457. }
  1458. }
  1459. }
  1460. else
  1461. {
  1462. for (uint32_t c = 0; c < 3; c++)
  1463. {
  1464. float fa = ca[c], fb = cb[c];
  1465. if ((fabs(fa) > basist::MAX_HALF_FLOAT) || (fabs(fb) > basist::MAX_HALF_FLOAT))
  1466. m_hf_mag_overflow = true;
  1467. if ((fa < 0.0f) || (fb < 0.0f))
  1468. m_has_neg = true;
  1469. if (std::isinf(fa) || std::isinf(fb) || std::isnan(fa) || std::isnan(fb))
  1470. m_any_abnormal = true;
  1471. }
  1472. double ca_l = get_luminance(ca), cb_l = get_luminance(cb);
  1473. double delta = fabs(ca_l - cb_l);
  1474. max_e = basisu::maximum(max_e, delta);
  1475. if (log)
  1476. {
  1477. double log2_delta = log2(basisu::maximum<double>(0.0f, ca_l) + 1.0f) - log2(basisu::maximum<double>(0.0f, cb_l) + 1.0f);
  1478. sum += fabs(log2_delta);
  1479. sum_sqr += log2_delta * log2_delta;
  1480. }
  1481. else
  1482. {
  1483. sum += delta;
  1484. sum_sqr += delta * delta;
  1485. }
  1486. }
  1487. }
  1488. }
  1489. m_max = (double)(max_e);
  1490. double total_values = (double)width * (double)height;
  1491. if (avg_comp_error)
  1492. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1493. m_mean = (float)(sum / total_values);
  1494. m_mean_squared = (float)(sum_sqr / total_values);
  1495. m_rms = (float)sqrt(sum_sqr / total_values);
  1496. const double max_val = 1.0f;
  1497. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1498. }
  1499. void image_metrics::calc_half(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
  1500. {
  1501. assert(total_chans);
  1502. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1503. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1504. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1505. m_has_neg = false;
  1506. m_hf_mag_overflow = false;
  1507. m_any_abnormal = false;
  1508. uint_vec hist(65536);
  1509. for (uint32_t y = 0; y < height; y++)
  1510. {
  1511. for (uint32_t x = 0; x < width; x++)
  1512. {
  1513. const vec4F& ca = a(x, y), &cb = b(x, y);
  1514. for (uint32_t i = 0; i < 4; i++)
  1515. {
  1516. if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
  1517. m_has_neg = true;
  1518. if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
  1519. m_hf_mag_overflow = true;
  1520. if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
  1521. m_any_abnormal = true;
  1522. }
  1523. int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
  1524. int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
  1525. for (uint32_t c = 0; c < total_chans; c++)
  1526. hist[iabs(cah[first_chan + c] - cbh[first_chan + c]) & 65535]++;
  1527. } // x
  1528. } // y
  1529. m_max = 0;
  1530. double sum = 0.0f, sum2 = 0.0f;
  1531. for (uint32_t i = 0; i < 65536; i++)
  1532. {
  1533. if (hist[i])
  1534. {
  1535. m_max = basisu::maximum<double>(m_max, (double)i);
  1536. double v = (double)i * (double)hist[i];
  1537. sum += v;
  1538. sum2 += (double)i * v;
  1539. }
  1540. }
  1541. double total_values = (double)width * (double)height;
  1542. if (avg_comp_error)
  1543. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1544. const float max_val = 65535.0f;
  1545. m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
  1546. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
  1547. m_rms = (float)sqrt(m_mean_squared);
  1548. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1549. }
  1550. // Alt. variant, same as calc_half(), for validation.
  1551. void image_metrics::calc_half2(const imagef& a, const imagef& b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error)
  1552. {
  1553. assert(total_chans);
  1554. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1555. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1556. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1557. m_has_neg = false;
  1558. m_hf_mag_overflow = false;
  1559. m_any_abnormal = false;
  1560. double sum = 0.0f, sum2 = 0.0f;
  1561. m_max = 0;
  1562. for (uint32_t y = 0; y < height; y++)
  1563. {
  1564. for (uint32_t x = 0; x < width; x++)
  1565. {
  1566. const vec4F& ca = a(x, y), & cb = b(x, y);
  1567. for (uint32_t i = 0; i < 4; i++)
  1568. {
  1569. if ((ca[i] < 0.0f) || (cb[i] < 0.0f))
  1570. m_has_neg = true;
  1571. if ((fabs(ca[i]) > basist::MAX_HALF_FLOAT) || (fabs(cb[i]) > basist::MAX_HALF_FLOAT))
  1572. m_hf_mag_overflow = true;
  1573. if (std::isnan(ca[i]) || std::isnan(cb[i]) || std::isinf(ca[i]) || std::isinf(cb[i]))
  1574. m_any_abnormal = true;
  1575. }
  1576. int cah[4] = { basist::float_to_half(ca[0]), basist::float_to_half(ca[1]), basist::float_to_half(ca[2]), basist::float_to_half(ca[3]) };
  1577. int cbh[4] = { basist::float_to_half(cb[0]), basist::float_to_half(cb[1]), basist::float_to_half(cb[2]), basist::float_to_half(cb[3]) };
  1578. for (uint32_t c = 0; c < total_chans; c++)
  1579. {
  1580. int diff = iabs(cah[first_chan + c] - cbh[first_chan + c]);
  1581. if (diff)
  1582. m_max = std::max<double>(m_max, (double)diff);
  1583. sum += diff;
  1584. sum2 += squarei(cah[first_chan + c] - cbh[first_chan + c]);
  1585. }
  1586. } // x
  1587. } // y
  1588. double total_values = (double)width * (double)height;
  1589. if (avg_comp_error)
  1590. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1591. const float max_val = 65535.0f;
  1592. m_mean = (float)clamp<double>(sum / total_values, 0.0f, max_val);
  1593. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, max_val * max_val);
  1594. m_rms = (float)sqrt(m_mean_squared);
  1595. m_psnr = m_rms ? (float)clamp<double>(log10(max_val / m_rms) * 20.0f, 0.0f, 1000.0f) : 1000.0f;
  1596. }
  1597. void image_metrics::calc(const image &a, const image &b, uint32_t first_chan, uint32_t total_chans, bool avg_comp_error, bool use_601_luma)
  1598. {
  1599. assert((first_chan < 4U) && (first_chan + total_chans <= 4U));
  1600. const uint32_t width = basisu::minimum(a.get_width(), b.get_width());
  1601. const uint32_t height = basisu::minimum(a.get_height(), b.get_height());
  1602. double hist[256];
  1603. clear_obj(hist);
  1604. m_has_neg = false;
  1605. m_any_abnormal = false;
  1606. m_hf_mag_overflow = false;
  1607. for (uint32_t y = 0; y < height; y++)
  1608. {
  1609. for (uint32_t x = 0; x < width; x++)
  1610. {
  1611. const color_rgba &ca = a(x, y), &cb = b(x, y);
  1612. if (total_chans)
  1613. {
  1614. for (uint32_t c = 0; c < total_chans; c++)
  1615. hist[iabs(ca[first_chan + c] - cb[first_chan + c])]++;
  1616. }
  1617. else
  1618. {
  1619. if (use_601_luma)
  1620. hist[iabs(ca.get_601_luma() - cb.get_601_luma())]++;
  1621. else
  1622. hist[iabs(ca.get_709_luma() - cb.get_709_luma())]++;
  1623. }
  1624. }
  1625. }
  1626. m_max = 0;
  1627. double sum = 0.0f, sum2 = 0.0f;
  1628. for (uint32_t i = 0; i < 256; i++)
  1629. {
  1630. if (hist[i])
  1631. {
  1632. m_max = basisu::maximum<double>(m_max, (double)i);
  1633. double v = i * hist[i];
  1634. sum += v;
  1635. sum2 += i * v;
  1636. }
  1637. }
  1638. double total_values = (double)width * (double)height;
  1639. if (avg_comp_error)
  1640. total_values *= (double)clamp<uint32_t>(total_chans, 1, 4);
  1641. m_mean = (float)clamp<double>(sum / total_values, 0.0f, 255.0);
  1642. m_mean_squared = (float)clamp<double>(sum2 / total_values, 0.0f, 255.0f * 255.0f);
  1643. m_rms = (float)sqrt(m_mean_squared);
  1644. m_psnr = m_rms ? (float)clamp<double>(log10(255.0 / m_rms) * 20.0f, 0.0f, 100.0f) : 100.0f;
  1645. }
  1646. void fill_buffer_with_random_bytes(void *pBuf, size_t size, uint32_t seed)
  1647. {
  1648. rand r(seed);
  1649. uint8_t *pDst = static_cast<uint8_t *>(pBuf);
  1650. while (size >= sizeof(uint32_t))
  1651. {
  1652. *(uint32_t *)pDst = r.urand32();
  1653. pDst += sizeof(uint32_t);
  1654. size -= sizeof(uint32_t);
  1655. }
  1656. while (size)
  1657. {
  1658. *pDst++ = r.byte();
  1659. size--;
  1660. }
  1661. }
  1662. uint32_t hash_hsieh(const uint8_t *pBuf, size_t len)
  1663. {
  1664. if (!pBuf || !len)
  1665. return 0;
  1666. uint32_t h = static_cast<uint32_t>(len);
  1667. const uint32_t bytes_left = len & 3;
  1668. len >>= 2;
  1669. while (len--)
  1670. {
  1671. const uint16_t *pWords = reinterpret_cast<const uint16_t *>(pBuf);
  1672. h += pWords[0];
  1673. const uint32_t t = (pWords[1] << 11) ^ h;
  1674. h = (h << 16) ^ t;
  1675. pBuf += sizeof(uint32_t);
  1676. h += h >> 11;
  1677. }
  1678. switch (bytes_left)
  1679. {
  1680. case 1:
  1681. h += *reinterpret_cast<const signed char*>(pBuf);
  1682. h ^= h << 10;
  1683. h += h >> 1;
  1684. break;
  1685. case 2:
  1686. h += *reinterpret_cast<const uint16_t *>(pBuf);
  1687. h ^= h << 11;
  1688. h += h >> 17;
  1689. break;
  1690. case 3:
  1691. h += *reinterpret_cast<const uint16_t *>(pBuf);
  1692. h ^= h << 16;
  1693. h ^= (static_cast<signed char>(pBuf[sizeof(uint16_t)])) << 18;
  1694. h += h >> 11;
  1695. break;
  1696. default:
  1697. break;
  1698. }
  1699. h ^= h << 3;
  1700. h += h >> 5;
  1701. h ^= h << 4;
  1702. h += h >> 17;
  1703. h ^= h << 25;
  1704. h += h >> 6;
  1705. return h;
  1706. }
  1707. job_pool::job_pool(uint32_t num_threads) :
  1708. m_num_active_jobs(0),
  1709. m_kill_flag(false)
  1710. {
  1711. assert(num_threads >= 1U);
  1712. debug_printf("job_pool::job_pool: %u total threads\n", num_threads);
  1713. if (num_threads > 1)
  1714. {
  1715. m_threads.resize(num_threads - 1);
  1716. for (int i = 0; i < ((int)num_threads - 1); i++)
  1717. m_threads[i] = std::thread([this, i] { job_thread(i); });
  1718. }
  1719. }
  1720. job_pool::~job_pool()
  1721. {
  1722. debug_printf("job_pool::~job_pool\n");
  1723. // Notify all workers that they need to die right now.
  1724. m_kill_flag = true;
  1725. m_has_work.notify_all();
  1726. // Wait for all workers to die.
  1727. for (uint32_t i = 0; i < m_threads.size(); i++)
  1728. m_threads[i].join();
  1729. }
  1730. void job_pool::add_job(const std::function<void()>& job)
  1731. {
  1732. std::unique_lock<std::mutex> lock(m_mutex);
  1733. m_queue.emplace_back(job);
  1734. const size_t queue_size = m_queue.size();
  1735. lock.unlock();
  1736. if (queue_size > 1)
  1737. m_has_work.notify_one();
  1738. }
  1739. void job_pool::add_job(std::function<void()>&& job)
  1740. {
  1741. std::unique_lock<std::mutex> lock(m_mutex);
  1742. m_queue.emplace_back(std::move(job));
  1743. const size_t queue_size = m_queue.size();
  1744. lock.unlock();
  1745. if (queue_size > 1)
  1746. {
  1747. m_has_work.notify_one();
  1748. }
  1749. }
  1750. void job_pool::wait_for_all()
  1751. {
  1752. std::unique_lock<std::mutex> lock(m_mutex);
  1753. // Drain the job queue on the calling thread.
  1754. while (!m_queue.empty())
  1755. {
  1756. std::function<void()> job(m_queue.back());
  1757. m_queue.pop_back();
  1758. lock.unlock();
  1759. job();
  1760. lock.lock();
  1761. }
  1762. // The queue is empty, now wait for all active jobs to finish up.
  1763. m_no_more_jobs.wait(lock, [this]{ return !m_num_active_jobs; } );
  1764. }
  1765. void job_pool::job_thread(uint32_t index)
  1766. {
  1767. BASISU_NOTE_UNUSED(index);
  1768. //debug_printf("job_pool::job_thread: starting %u\n", index);
  1769. while (true)
  1770. {
  1771. std::unique_lock<std::mutex> lock(m_mutex);
  1772. // Wait for any jobs to be issued.
  1773. m_has_work.wait(lock, [this] { return m_kill_flag || m_queue.size(); } );
  1774. // Check to see if we're supposed to exit.
  1775. if (m_kill_flag)
  1776. break;
  1777. // Get the job and execute it.
  1778. std::function<void()> job(m_queue.back());
  1779. m_queue.pop_back();
  1780. ++m_num_active_jobs;
  1781. lock.unlock();
  1782. job();
  1783. lock.lock();
  1784. --m_num_active_jobs;
  1785. // Now check if there are no more jobs remaining.
  1786. const bool all_done = m_queue.empty() && !m_num_active_jobs;
  1787. lock.unlock();
  1788. if (all_done)
  1789. m_no_more_jobs.notify_all();
  1790. }
  1791. //debug_printf("job_pool::job_thread: exiting\n");
  1792. }
  1793. // .TGA image loading
  1794. #pragma pack(push)
  1795. #pragma pack(1)
  1796. struct tga_header
  1797. {
  1798. uint8_t m_id_len;
  1799. uint8_t m_cmap;
  1800. uint8_t m_type;
  1801. packed_uint<2> m_cmap_first;
  1802. packed_uint<2> m_cmap_len;
  1803. uint8_t m_cmap_bpp;
  1804. packed_uint<2> m_x_org;
  1805. packed_uint<2> m_y_org;
  1806. packed_uint<2> m_width;
  1807. packed_uint<2> m_height;
  1808. uint8_t m_depth;
  1809. uint8_t m_desc;
  1810. };
  1811. #pragma pack(pop)
  1812. const uint32_t MAX_TGA_IMAGE_SIZE = 16384;
  1813. enum tga_image_type
  1814. {
  1815. cITPalettized = 1,
  1816. cITRGB = 2,
  1817. cITGrayscale = 3
  1818. };
  1819. uint8_t *read_tga(const uint8_t *pBuf, uint32_t buf_size, int &width, int &height, int &n_chans)
  1820. {
  1821. width = 0;
  1822. height = 0;
  1823. n_chans = 0;
  1824. if (buf_size <= sizeof(tga_header))
  1825. return nullptr;
  1826. const tga_header &hdr = *reinterpret_cast<const tga_header *>(pBuf);
  1827. if ((!hdr.m_width) || (!hdr.m_height) || (hdr.m_width > MAX_TGA_IMAGE_SIZE) || (hdr.m_height > MAX_TGA_IMAGE_SIZE))
  1828. return nullptr;
  1829. if (hdr.m_desc >> 6)
  1830. return nullptr;
  1831. // Simple validation
  1832. if ((hdr.m_cmap != 0) && (hdr.m_cmap != 1))
  1833. return nullptr;
  1834. if (hdr.m_cmap)
  1835. {
  1836. if ((hdr.m_cmap_bpp == 0) || (hdr.m_cmap_bpp > 32))
  1837. return nullptr;
  1838. // Nobody implements CMapFirst correctly, so we're not supporting it. Never seen it used, either.
  1839. if (hdr.m_cmap_first != 0)
  1840. return nullptr;
  1841. }
  1842. const bool x_flipped = (hdr.m_desc & 0x10) != 0;
  1843. const bool y_flipped = (hdr.m_desc & 0x20) == 0;
  1844. bool rle_flag = false;
  1845. int file_image_type = hdr.m_type;
  1846. if (file_image_type > 8)
  1847. {
  1848. file_image_type -= 8;
  1849. rle_flag = true;
  1850. }
  1851. const tga_image_type image_type = static_cast<tga_image_type>(file_image_type);
  1852. switch (file_image_type)
  1853. {
  1854. case cITRGB:
  1855. if (hdr.m_depth == 8)
  1856. return nullptr;
  1857. break;
  1858. case cITPalettized:
  1859. if ((hdr.m_depth != 8) || (hdr.m_cmap != 1) || (hdr.m_cmap_len == 0))
  1860. return nullptr;
  1861. break;
  1862. case cITGrayscale:
  1863. if ((hdr.m_cmap != 0) || (hdr.m_cmap_len != 0))
  1864. return nullptr;
  1865. if ((hdr.m_depth != 8) && (hdr.m_depth != 16))
  1866. return nullptr;
  1867. break;
  1868. default:
  1869. return nullptr;
  1870. }
  1871. uint32_t tga_bytes_per_pixel = 0;
  1872. switch (hdr.m_depth)
  1873. {
  1874. case 32:
  1875. tga_bytes_per_pixel = 4;
  1876. n_chans = 4;
  1877. break;
  1878. case 24:
  1879. tga_bytes_per_pixel = 3;
  1880. n_chans = 3;
  1881. break;
  1882. case 16:
  1883. case 15:
  1884. tga_bytes_per_pixel = 2;
  1885. // For compatibility with stb_image_write.h
  1886. n_chans = ((file_image_type == cITGrayscale) && (hdr.m_depth == 16)) ? 4 : 3;
  1887. break;
  1888. case 8:
  1889. tga_bytes_per_pixel = 1;
  1890. // For palettized RGBA support, which both FreeImage and stb_image support.
  1891. n_chans = ((file_image_type == cITPalettized) && (hdr.m_cmap_bpp == 32)) ? 4 : 3;
  1892. break;
  1893. default:
  1894. return nullptr;
  1895. }
  1896. //const uint32_t bytes_per_line = hdr.m_width * tga_bytes_per_pixel;
  1897. const uint8_t *pSrc = pBuf + sizeof(tga_header);
  1898. uint32_t bytes_remaining = buf_size - sizeof(tga_header);
  1899. if (hdr.m_id_len)
  1900. {
  1901. if (bytes_remaining < hdr.m_id_len)
  1902. return nullptr;
  1903. pSrc += hdr.m_id_len;
  1904. bytes_remaining += hdr.m_id_len;
  1905. }
  1906. color_rgba pal[256];
  1907. for (uint32_t i = 0; i < 256; i++)
  1908. pal[i].set(0, 0, 0, 255);
  1909. if ((hdr.m_cmap) && (hdr.m_cmap_len))
  1910. {
  1911. if (image_type == cITPalettized)
  1912. {
  1913. // Note I cannot find any files using 32bpp palettes in the wild (never seen any in ~30 years).
  1914. if ( ((hdr.m_cmap_bpp != 32) && (hdr.m_cmap_bpp != 24) && (hdr.m_cmap_bpp != 15) && (hdr.m_cmap_bpp != 16)) || (hdr.m_cmap_len > 256) )
  1915. return nullptr;
  1916. if (hdr.m_cmap_bpp == 32)
  1917. {
  1918. const uint32_t pal_size = hdr.m_cmap_len * 4;
  1919. if (bytes_remaining < pal_size)
  1920. return nullptr;
  1921. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  1922. {
  1923. pal[i].r = pSrc[i * 4 + 2];
  1924. pal[i].g = pSrc[i * 4 + 1];
  1925. pal[i].b = pSrc[i * 4 + 0];
  1926. pal[i].a = pSrc[i * 4 + 3];
  1927. }
  1928. bytes_remaining -= pal_size;
  1929. pSrc += pal_size;
  1930. }
  1931. else if (hdr.m_cmap_bpp == 24)
  1932. {
  1933. const uint32_t pal_size = hdr.m_cmap_len * 3;
  1934. if (bytes_remaining < pal_size)
  1935. return nullptr;
  1936. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  1937. {
  1938. pal[i].r = pSrc[i * 3 + 2];
  1939. pal[i].g = pSrc[i * 3 + 1];
  1940. pal[i].b = pSrc[i * 3 + 0];
  1941. pal[i].a = 255;
  1942. }
  1943. bytes_remaining -= pal_size;
  1944. pSrc += pal_size;
  1945. }
  1946. else
  1947. {
  1948. const uint32_t pal_size = hdr.m_cmap_len * 2;
  1949. if (bytes_remaining < pal_size)
  1950. return nullptr;
  1951. for (uint32_t i = 0; i < hdr.m_cmap_len; i++)
  1952. {
  1953. const uint32_t v = pSrc[i * 2 + 0] | (pSrc[i * 2 + 1] << 8);
  1954. pal[i].r = (((v >> 10) & 31) * 255 + 15) / 31;
  1955. pal[i].g = (((v >> 5) & 31) * 255 + 15) / 31;
  1956. pal[i].b = ((v & 31) * 255 + 15) / 31;
  1957. pal[i].a = 255;
  1958. }
  1959. bytes_remaining -= pal_size;
  1960. pSrc += pal_size;
  1961. }
  1962. }
  1963. else
  1964. {
  1965. const uint32_t bytes_to_skip = (hdr.m_cmap_bpp >> 3) * hdr.m_cmap_len;
  1966. if (bytes_remaining < bytes_to_skip)
  1967. return nullptr;
  1968. pSrc += bytes_to_skip;
  1969. bytes_remaining += bytes_to_skip;
  1970. }
  1971. }
  1972. width = hdr.m_width;
  1973. height = hdr.m_height;
  1974. const uint32_t source_pitch = width * tga_bytes_per_pixel;
  1975. const uint32_t dest_pitch = width * n_chans;
  1976. uint8_t *pImage = (uint8_t *)malloc(dest_pitch * height);
  1977. if (!pImage)
  1978. return nullptr;
  1979. std::vector<uint8_t> input_line_buf;
  1980. if (rle_flag)
  1981. input_line_buf.resize(source_pitch);
  1982. int run_type = 0, run_remaining = 0;
  1983. uint8_t run_pixel[4];
  1984. memset(run_pixel, 0, sizeof(run_pixel));
  1985. for (int y = 0; y < height; y++)
  1986. {
  1987. const uint8_t *pLine_data;
  1988. if (rle_flag)
  1989. {
  1990. int pixels_remaining = width;
  1991. uint8_t *pDst = &input_line_buf[0];
  1992. do
  1993. {
  1994. if (!run_remaining)
  1995. {
  1996. if (bytes_remaining < 1)
  1997. {
  1998. free(pImage);
  1999. return nullptr;
  2000. }
  2001. int v = *pSrc++;
  2002. bytes_remaining--;
  2003. run_type = v & 0x80;
  2004. run_remaining = (v & 0x7F) + 1;
  2005. if (run_type)
  2006. {
  2007. if (bytes_remaining < tga_bytes_per_pixel)
  2008. {
  2009. free(pImage);
  2010. return nullptr;
  2011. }
  2012. memcpy(run_pixel, pSrc, tga_bytes_per_pixel);
  2013. pSrc += tga_bytes_per_pixel;
  2014. bytes_remaining -= tga_bytes_per_pixel;
  2015. }
  2016. }
  2017. const uint32_t n = basisu::minimum<uint32_t>(pixels_remaining, run_remaining);
  2018. pixels_remaining -= n;
  2019. run_remaining -= n;
  2020. if (run_type)
  2021. {
  2022. for (uint32_t i = 0; i < n; i++)
  2023. for (uint32_t j = 0; j < tga_bytes_per_pixel; j++)
  2024. *pDst++ = run_pixel[j];
  2025. }
  2026. else
  2027. {
  2028. const uint32_t bytes_wanted = n * tga_bytes_per_pixel;
  2029. if (bytes_remaining < bytes_wanted)
  2030. {
  2031. free(pImage);
  2032. return nullptr;
  2033. }
  2034. memcpy(pDst, pSrc, bytes_wanted);
  2035. pDst += bytes_wanted;
  2036. pSrc += bytes_wanted;
  2037. bytes_remaining -= bytes_wanted;
  2038. }
  2039. } while (pixels_remaining);
  2040. assert((pDst - &input_line_buf[0]) == (int)(width * tga_bytes_per_pixel));
  2041. pLine_data = &input_line_buf[0];
  2042. }
  2043. else
  2044. {
  2045. if (bytes_remaining < source_pitch)
  2046. {
  2047. free(pImage);
  2048. return nullptr;
  2049. }
  2050. pLine_data = pSrc;
  2051. bytes_remaining -= source_pitch;
  2052. pSrc += source_pitch;
  2053. }
  2054. // Convert to 24bpp RGB or 32bpp RGBA.
  2055. uint8_t *pDst = pImage + (y_flipped ? (height - 1 - y) : y) * dest_pitch + (x_flipped ? (width - 1) * n_chans : 0);
  2056. const int dst_stride = x_flipped ? -((int)n_chans) : n_chans;
  2057. switch (hdr.m_depth)
  2058. {
  2059. case 32:
  2060. assert(tga_bytes_per_pixel == 4 && n_chans == 4);
  2061. for (int i = 0; i < width; i++, pLine_data += 4, pDst += dst_stride)
  2062. {
  2063. pDst[0] = pLine_data[2];
  2064. pDst[1] = pLine_data[1];
  2065. pDst[2] = pLine_data[0];
  2066. pDst[3] = pLine_data[3];
  2067. }
  2068. break;
  2069. case 24:
  2070. assert(tga_bytes_per_pixel == 3 && n_chans == 3);
  2071. for (int i = 0; i < width; i++, pLine_data += 3, pDst += dst_stride)
  2072. {
  2073. pDst[0] = pLine_data[2];
  2074. pDst[1] = pLine_data[1];
  2075. pDst[2] = pLine_data[0];
  2076. }
  2077. break;
  2078. case 16:
  2079. case 15:
  2080. if (image_type == cITRGB)
  2081. {
  2082. assert(tga_bytes_per_pixel == 2 && n_chans == 3);
  2083. for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
  2084. {
  2085. const uint32_t v = pLine_data[0] | (pLine_data[1] << 8);
  2086. pDst[0] = (((v >> 10) & 31) * 255 + 15) / 31;
  2087. pDst[1] = (((v >> 5) & 31) * 255 + 15) / 31;
  2088. pDst[2] = ((v & 31) * 255 + 15) / 31;
  2089. }
  2090. }
  2091. else
  2092. {
  2093. assert(image_type == cITGrayscale && tga_bytes_per_pixel == 2 && n_chans == 4);
  2094. for (int i = 0; i < width; i++, pLine_data += 2, pDst += dst_stride)
  2095. {
  2096. pDst[0] = pLine_data[0];
  2097. pDst[1] = pLine_data[0];
  2098. pDst[2] = pLine_data[0];
  2099. pDst[3] = pLine_data[1];
  2100. }
  2101. }
  2102. break;
  2103. case 8:
  2104. assert(tga_bytes_per_pixel == 1);
  2105. if (image_type == cITPalettized)
  2106. {
  2107. if (hdr.m_cmap_bpp == 32)
  2108. {
  2109. assert(n_chans == 4);
  2110. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2111. {
  2112. const uint32_t c = *pLine_data;
  2113. pDst[0] = pal[c].r;
  2114. pDst[1] = pal[c].g;
  2115. pDst[2] = pal[c].b;
  2116. pDst[3] = pal[c].a;
  2117. }
  2118. }
  2119. else
  2120. {
  2121. assert(n_chans == 3);
  2122. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2123. {
  2124. const uint32_t c = *pLine_data;
  2125. pDst[0] = pal[c].r;
  2126. pDst[1] = pal[c].g;
  2127. pDst[2] = pal[c].b;
  2128. }
  2129. }
  2130. }
  2131. else
  2132. {
  2133. assert(n_chans == 3);
  2134. for (int i = 0; i < width; i++, pLine_data++, pDst += dst_stride)
  2135. {
  2136. const uint8_t c = *pLine_data;
  2137. pDst[0] = c;
  2138. pDst[1] = c;
  2139. pDst[2] = c;
  2140. }
  2141. }
  2142. break;
  2143. default:
  2144. assert(0);
  2145. break;
  2146. }
  2147. } // y
  2148. return pImage;
  2149. }
  2150. uint8_t *read_tga(const char *pFilename, int &width, int &height, int &n_chans)
  2151. {
  2152. width = height = n_chans = 0;
  2153. uint8_vec filedata;
  2154. if (!read_file_to_vec(pFilename, filedata))
  2155. return nullptr;
  2156. if (!filedata.size() || (filedata.size() > UINT32_MAX))
  2157. return nullptr;
  2158. return read_tga(&filedata[0], (uint32_t)filedata.size(), width, height, n_chans);
  2159. }
  2160. static inline void hdr_convert(const color_rgba& rgbe, vec4F& c)
  2161. {
  2162. if (rgbe[3] != 0)
  2163. {
  2164. float scale = ldexp(1.0f, rgbe[3] - 128 - 8);
  2165. c.set((float)rgbe[0] * scale, (float)rgbe[1] * scale, (float)rgbe[2] * scale, 1.0f);
  2166. }
  2167. else
  2168. {
  2169. c.set(0.0f, 0.0f, 0.0f, 1.0f);
  2170. }
  2171. }
  2172. bool string_begins_with(const std::string& str, const char* pPhrase)
  2173. {
  2174. const size_t str_len = str.size();
  2175. const size_t phrase_len = strlen(pPhrase);
  2176. assert(phrase_len);
  2177. if (str_len >= phrase_len)
  2178. {
  2179. #ifdef _MSC_VER
  2180. if (_strnicmp(pPhrase, str.c_str(), phrase_len) == 0)
  2181. #else
  2182. if (strncasecmp(pPhrase, str.c_str(), phrase_len) == 0)
  2183. #endif
  2184. return true;
  2185. }
  2186. return false;
  2187. }
  2188. // Radiance RGBE (.HDR) image reading.
  2189. // This code tries to preserve the original logic in Radiance's ray/src/common/color.c code:
  2190. // https://www.radiance-online.org/cgi-bin/viewcvs.cgi/ray/src/common/color.c?revision=2.26&view=markup&sortby=log
  2191. // Also see: https://flipcode.com/archives/HDR_Image_Reader.shtml.
  2192. // https://github.com/LuminanceHDR/LuminanceHDR/blob/master/src/Libpfs/io/rgbereader.cpp.
  2193. // https://radsite.lbl.gov/radiance/refer/filefmts.pdf
  2194. // Buggy readers:
  2195. // stb_image.h: appears to be a clone of rgbe.c, but with goto's (doesn't support old format files, doesn't support mixture of RLE/non-RLE scanlines)
  2196. // http://www.graphics.cornell.edu/~bjw/rgbe.html - rgbe.c/h
  2197. // http://www.graphics.cornell.edu/online/formats/rgbe/ - rgbe.c/.h - buggy
  2198. bool read_rgbe(const uint8_vec &filedata, imagef& img, rgbe_header_info& hdr_info)
  2199. {
  2200. hdr_info.clear();
  2201. const uint32_t MAX_SUPPORTED_DIM = 65536;
  2202. if (filedata.size() < 4)
  2203. return false;
  2204. // stb_image.h checks for the string "#?RADIANCE" or "#?RGBE" in the header.
  2205. // The original Radiance header code doesn't care about the specific string.
  2206. // opencv's reader only checks for "#?", so that's what we're going to do.
  2207. if ((filedata[0] != '#') || (filedata[1] != '?'))
  2208. return false;
  2209. //uint32_t width = 0, height = 0;
  2210. bool is_rgbe = false;
  2211. size_t cur_ofs = 0;
  2212. // Parse the lines until we encounter a blank line.
  2213. std::string cur_line;
  2214. for (; ; )
  2215. {
  2216. if (cur_ofs >= filedata.size())
  2217. return false;
  2218. const uint32_t HEADER_TOO_BIG_SIZE = 4096;
  2219. if (cur_ofs >= HEADER_TOO_BIG_SIZE)
  2220. {
  2221. // Header seems too large - something is likely wrong. Return failure.
  2222. return false;
  2223. }
  2224. uint8_t c = filedata[cur_ofs++];
  2225. if (c == '\n')
  2226. {
  2227. if (!cur_line.size())
  2228. break;
  2229. if ((cur_line[0] == '#') && (!string_begins_with(cur_line, "#?")) && (!hdr_info.m_program.size()))
  2230. {
  2231. cur_line.erase(0, 1);
  2232. while (cur_line.size() && (cur_line[0] == ' '))
  2233. cur_line.erase(0, 1);
  2234. hdr_info.m_program = cur_line;
  2235. }
  2236. else if (string_begins_with(cur_line, "EXPOSURE=") && (cur_line.size() > 9))
  2237. {
  2238. hdr_info.m_exposure = atof(cur_line.c_str() + 9);
  2239. hdr_info.m_has_exposure = true;
  2240. }
  2241. else if (string_begins_with(cur_line, "GAMMA=") && (cur_line.size() > 6))
  2242. {
  2243. hdr_info.m_exposure = atof(cur_line.c_str() + 6);
  2244. hdr_info.m_has_gamma = true;
  2245. }
  2246. else if (cur_line == "FORMAT=32-bit_rle_rgbe")
  2247. {
  2248. is_rgbe = true;
  2249. }
  2250. cur_line.resize(0);
  2251. }
  2252. else
  2253. cur_line.push_back((char)c);
  2254. }
  2255. if (!is_rgbe)
  2256. return false;
  2257. // Assume and require the final line to have the image's dimensions. We're not supporting flipping.
  2258. for (; ; )
  2259. {
  2260. if (cur_ofs >= filedata.size())
  2261. return false;
  2262. uint8_t c = filedata[cur_ofs++];
  2263. if (c == '\n')
  2264. break;
  2265. cur_line.push_back((char)c);
  2266. }
  2267. int comp[2] = { 1, 0 }; // y, x (major, minor)
  2268. int dir[2] = { -1, 1 }; // -1, 1, (major, minor), for y -1=up
  2269. uint32_t major_dim = 0, minor_dim = 0;
  2270. // Parse the dimension string, normally it'll be "-Y # +X #" (major, minor), rarely it differs
  2271. for (uint32_t d = 0; d < 2; d++) // 0=major, 1=minor
  2272. {
  2273. const bool is_neg_x = (strncmp(&cur_line[0], "-X ", 3) == 0);
  2274. const bool is_pos_x = (strncmp(&cur_line[0], "+X ", 3) == 0);
  2275. const bool is_x = is_neg_x || is_pos_x;
  2276. const bool is_neg_y = (strncmp(&cur_line[0], "-Y ", 3) == 0);
  2277. const bool is_pos_y = (strncmp(&cur_line[0], "+Y ", 3) == 0);
  2278. const bool is_y = is_neg_y || is_pos_y;
  2279. if (cur_line.size() < 3)
  2280. return false;
  2281. if (!is_x && !is_y)
  2282. return false;
  2283. comp[d] = is_x ? 0 : 1;
  2284. dir[d] = (is_neg_x || is_neg_y) ? -1 : 1;
  2285. uint32_t& dim = d ? minor_dim : major_dim;
  2286. cur_line.erase(0, 3);
  2287. while (cur_line.size())
  2288. {
  2289. char c = cur_line[0];
  2290. if (c != ' ')
  2291. break;
  2292. cur_line.erase(0, 1);
  2293. }
  2294. bool has_digits = false;
  2295. while (cur_line.size())
  2296. {
  2297. char c = cur_line[0];
  2298. cur_line.erase(0, 1);
  2299. if (c == ' ')
  2300. break;
  2301. if ((c < '0') || (c > '9'))
  2302. return false;
  2303. const uint32_t prev_dim = dim;
  2304. dim = dim * 10 + (c - '0');
  2305. if (dim < prev_dim)
  2306. return false;
  2307. has_digits = true;
  2308. }
  2309. if (!has_digits)
  2310. return false;
  2311. if ((dim < 1) || (dim > MAX_SUPPORTED_DIM))
  2312. return false;
  2313. }
  2314. // temp image: width=minor, height=major
  2315. img.resize(minor_dim, major_dim);
  2316. std::vector<color_rgba> temp_scanline(minor_dim);
  2317. // Read the scanlines.
  2318. for (uint32_t y = 0; y < major_dim; y++)
  2319. {
  2320. vec4F* pDst = &img(0, y);
  2321. if ((filedata.size() - cur_ofs) < 4)
  2322. return false;
  2323. // Determine if the line uses the new or old format. See the logic in color.c.
  2324. bool old_decrunch = false;
  2325. if ((minor_dim < 8) || (minor_dim > 0x7FFF))
  2326. {
  2327. // Line is too short or long; must be old format.
  2328. old_decrunch = true;
  2329. }
  2330. else if (filedata[cur_ofs] != 2)
  2331. {
  2332. // R is not 2, must be old format
  2333. old_decrunch = true;
  2334. }
  2335. else
  2336. {
  2337. // c[0]/red is 2.Check GB and E for validity.
  2338. color_rgba c;
  2339. memcpy(&c, &filedata[cur_ofs], 4);
  2340. if ((c[1] != 2) || (c[2] & 0x80))
  2341. {
  2342. // G isn't 2, or the high bit of B is set which is impossible (image's > 0x7FFF pixels can't get here). Use old format.
  2343. old_decrunch = true;
  2344. }
  2345. else
  2346. {
  2347. // Check B and E. If this isn't the minor_dim in network order, something is wrong. The pixel would also be denormalized, and invalid.
  2348. uint32_t w = (c[2] << 8) | c[3];
  2349. if (w != minor_dim)
  2350. return false;
  2351. cur_ofs += 4;
  2352. }
  2353. }
  2354. if (old_decrunch)
  2355. {
  2356. uint32_t rshift = 0, x = 0;
  2357. while (x < minor_dim)
  2358. {
  2359. if ((filedata.size() - cur_ofs) < 4)
  2360. return false;
  2361. color_rgba c;
  2362. memcpy(&c, &filedata[cur_ofs], 4);
  2363. cur_ofs += 4;
  2364. if ((c[0] == 1) && (c[1] == 1) && (c[2] == 1))
  2365. {
  2366. // We'll allow RLE matches to cross scanlines, but not on the very first pixel.
  2367. if ((!x) && (!y))
  2368. return false;
  2369. const uint32_t run_len = c[3] << rshift;
  2370. const vec4F run_color(pDst[-1]);
  2371. if ((x + run_len) > minor_dim)
  2372. return false;
  2373. for (uint32_t i = 0; i < run_len; i++)
  2374. *pDst++ = run_color;
  2375. rshift += 8;
  2376. x += run_len;
  2377. }
  2378. else
  2379. {
  2380. rshift = 0;
  2381. hdr_convert(c, *pDst);
  2382. pDst++;
  2383. x++;
  2384. }
  2385. }
  2386. continue;
  2387. }
  2388. // New format
  2389. for (uint32_t s = 0; s < 4; s++)
  2390. {
  2391. uint32_t x_ofs = 0;
  2392. while (x_ofs < minor_dim)
  2393. {
  2394. uint32_t num_remaining = minor_dim - x_ofs;
  2395. if (cur_ofs >= filedata.size())
  2396. return false;
  2397. uint8_t count = filedata[cur_ofs++];
  2398. if (count > 128)
  2399. {
  2400. count -= 128;
  2401. if (count > num_remaining)
  2402. return false;
  2403. if (cur_ofs >= filedata.size())
  2404. return false;
  2405. const uint8_t val = filedata[cur_ofs++];
  2406. for (uint32_t i = 0; i < count; i++)
  2407. temp_scanline[x_ofs + i][s] = val;
  2408. x_ofs += count;
  2409. }
  2410. else
  2411. {
  2412. if ((!count) || (count > num_remaining))
  2413. return false;
  2414. for (uint32_t i = 0; i < count; i++)
  2415. {
  2416. if (cur_ofs >= filedata.size())
  2417. return false;
  2418. const uint8_t val = filedata[cur_ofs++];
  2419. temp_scanline[x_ofs + i][s] = val;
  2420. }
  2421. x_ofs += count;
  2422. }
  2423. } // while (x_ofs < minor_dim)
  2424. } // c
  2425. // Convert all the RGBE pixels to float now
  2426. for (uint32_t x = 0; x < minor_dim; x++, pDst++)
  2427. hdr_convert(temp_scanline[x], *pDst);
  2428. assert((pDst - &img(0, y)) == (int)minor_dim);
  2429. } // y
  2430. // at here:
  2431. // img(width,height)=image pixels as read from file, x=minor axis, y=major axis
  2432. // width=minor axis dimension
  2433. // height=major axis dimension
  2434. // in file, pixels are emitted in minor order, them major (so major=scanlines in the file)
  2435. imagef final_img;
  2436. if (comp[0] == 0) // if major axis is X
  2437. final_img.resize(major_dim, minor_dim);
  2438. else // major axis is Y, minor is X
  2439. final_img.resize(minor_dim, major_dim);
  2440. // TODO: optimize the identity case
  2441. for (uint32_t major_iter = 0; major_iter < major_dim; major_iter++)
  2442. {
  2443. for (uint32_t minor_iter = 0; minor_iter < minor_dim; minor_iter++)
  2444. {
  2445. const vec4F& p = img(minor_iter, major_iter);
  2446. uint32_t dst_x = 0, dst_y = 0;
  2447. // is the minor dim output x?
  2448. if (comp[1] == 0)
  2449. {
  2450. // minor axis is x, major is y
  2451. // is minor axis (which is output x) flipped?
  2452. if (dir[1] < 0)
  2453. dst_x = minor_dim - 1 - minor_iter;
  2454. else
  2455. dst_x = minor_iter;
  2456. // is major axis (which is output y) flipped? -1=down in raster order, 1=up
  2457. if (dir[0] < 0)
  2458. dst_y = major_iter;
  2459. else
  2460. dst_y = major_dim - 1 - major_iter;
  2461. }
  2462. else
  2463. {
  2464. // minor axis is output y, major is output x
  2465. // is minor axis (which is output y) flipped?
  2466. if (dir[1] < 0)
  2467. dst_y = minor_iter;
  2468. else
  2469. dst_y = minor_dim - 1 - minor_iter;
  2470. // is major axis (which is output x) flipped?
  2471. if (dir[0] < 0)
  2472. dst_x = major_dim - 1 - major_iter;
  2473. else
  2474. dst_x = major_iter;
  2475. }
  2476. final_img(dst_x, dst_y) = p;
  2477. }
  2478. }
  2479. final_img.swap(img);
  2480. return true;
  2481. }
  2482. bool read_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
  2483. {
  2484. uint8_vec filedata;
  2485. if (!read_file_to_vec(pFilename, filedata))
  2486. return false;
  2487. return read_rgbe(filedata, img, hdr_info);
  2488. }
  2489. static uint8_vec& append_string(uint8_vec& buf, const char* pStr)
  2490. {
  2491. const size_t str_len = strlen(pStr);
  2492. if (!str_len)
  2493. return buf;
  2494. const size_t ofs = buf.size();
  2495. buf.resize(ofs + str_len);
  2496. memcpy(&buf[ofs], pStr, str_len);
  2497. return buf;
  2498. }
  2499. static uint8_vec& append_string(uint8_vec& buf, const std::string& str)
  2500. {
  2501. if (!str.size())
  2502. return buf;
  2503. return append_string(buf, str.c_str());
  2504. }
  2505. static inline void float2rgbe(color_rgba &rgbe, const vec4F &c)
  2506. {
  2507. const float red = c[0], green = c[1], blue = c[2];
  2508. assert(red >= 0.0f && green >= 0.0f && blue >= 0.0f);
  2509. const float max_v = basisu::maximumf(basisu::maximumf(red, green), blue);
  2510. if (max_v < 1e-32f)
  2511. rgbe.clear();
  2512. else
  2513. {
  2514. int e;
  2515. const float scale = frexp(max_v, &e) * 256.0f / max_v;
  2516. rgbe[0] = (uint8_t)(clamp<int>((int)(red * scale), 0, 255));
  2517. rgbe[1] = (uint8_t)(clamp<int>((int)(green * scale), 0, 255));
  2518. rgbe[2] = (uint8_t)(clamp<int>((int)(blue * scale), 0, 255));
  2519. rgbe[3] = (uint8_t)(e + 128);
  2520. }
  2521. }
  2522. const bool RGBE_FORCE_RAW = false;
  2523. const bool RGBE_FORCE_OLD_CRUNCH = false; // note must readers (particularly stb_image.h's) don't properly support this, when they should
  2524. bool write_rgbe(uint8_vec &file_data, imagef& img, rgbe_header_info& hdr_info)
  2525. {
  2526. if (!img.get_width() || !img.get_height())
  2527. return false;
  2528. const uint32_t width = img.get_width(), height = img.get_height();
  2529. file_data.resize(0);
  2530. file_data.reserve(1024 + img.get_width() * img.get_height() * 4);
  2531. append_string(file_data, "#?RADIANCE\n");
  2532. if (hdr_info.m_has_exposure)
  2533. append_string(file_data, string_format("EXPOSURE=%g\n", hdr_info.m_exposure));
  2534. if (hdr_info.m_has_gamma)
  2535. append_string(file_data, string_format("GAMMA=%g\n", hdr_info.m_gamma));
  2536. append_string(file_data, "FORMAT=32-bit_rle_rgbe\n\n");
  2537. append_string(file_data, string_format("-Y %u +X %u\n", height, width));
  2538. if (((width < 8) || (width > 0x7FFF)) || (RGBE_FORCE_RAW))
  2539. {
  2540. for (uint32_t y = 0; y < height; y++)
  2541. {
  2542. for (uint32_t x = 0; x < width; x++)
  2543. {
  2544. color_rgba rgbe;
  2545. float2rgbe(rgbe, img(x, y));
  2546. append_vector(file_data, (const uint8_t *)&rgbe, sizeof(rgbe));
  2547. }
  2548. }
  2549. }
  2550. else if (RGBE_FORCE_OLD_CRUNCH)
  2551. {
  2552. for (uint32_t y = 0; y < height; y++)
  2553. {
  2554. int prev_r = -1, prev_g = -1, prev_b = -1, prev_e = -1;
  2555. uint32_t cur_run_len = 0;
  2556. for (uint32_t x = 0; x < width; x++)
  2557. {
  2558. color_rgba rgbe;
  2559. float2rgbe(rgbe, img(x, y));
  2560. if ((rgbe[0] == prev_r) && (rgbe[1] == prev_g) && (rgbe[2] == prev_b) && (rgbe[3] == prev_e))
  2561. {
  2562. if (++cur_run_len == 255)
  2563. {
  2564. // this ensures rshift stays 0, it's lame but this path is only for testing readers
  2565. color_rgba f(1, 1, 1, cur_run_len - 1);
  2566. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2567. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2568. cur_run_len = 0;
  2569. }
  2570. }
  2571. else
  2572. {
  2573. if (cur_run_len > 0)
  2574. {
  2575. color_rgba f(1, 1, 1, cur_run_len);
  2576. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2577. cur_run_len = 0;
  2578. }
  2579. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2580. prev_r = rgbe[0];
  2581. prev_g = rgbe[1];
  2582. prev_b = rgbe[2];
  2583. prev_e = rgbe[3];
  2584. }
  2585. } // x
  2586. if (cur_run_len > 0)
  2587. {
  2588. color_rgba f(1, 1, 1, cur_run_len);
  2589. append_vector(file_data, (const uint8_t*)&f, sizeof(f));
  2590. }
  2591. } // y
  2592. }
  2593. else
  2594. {
  2595. uint8_vec temp[4];
  2596. for (uint32_t c = 0; c < 4; c++)
  2597. temp[c].resize(width);
  2598. for (uint32_t y = 0; y < height; y++)
  2599. {
  2600. color_rgba rgbe(2, 2, width >> 8, width & 0xFF);
  2601. append_vector(file_data, (const uint8_t*)&rgbe, sizeof(rgbe));
  2602. for (uint32_t x = 0; x < width; x++)
  2603. {
  2604. float2rgbe(rgbe, img(x, y));
  2605. for (uint32_t c = 0; c < 4; c++)
  2606. temp[c][x] = rgbe[c];
  2607. }
  2608. for (uint32_t c = 0; c < 4; c++)
  2609. {
  2610. int raw_ofs = -1;
  2611. uint32_t x = 0;
  2612. while (x < width)
  2613. {
  2614. const uint32_t num_bytes_remaining = width - x;
  2615. const uint32_t max_run_len = basisu::minimum<uint32_t>(num_bytes_remaining, 127);
  2616. const uint8_t cur_byte = temp[c][x];
  2617. uint32_t run_len = 1;
  2618. while (run_len < max_run_len)
  2619. {
  2620. if (temp[c][x + run_len] != cur_byte)
  2621. break;
  2622. run_len++;
  2623. }
  2624. const uint32_t cost_to_keep_raw = ((raw_ofs != -1) ? 0 : 1) + run_len; // 0 or 1 bytes to start a raw run, then the repeated bytes issued as raw
  2625. const uint32_t cost_to_take_run = 2 + 1; // 2 bytes to issue the RLE, then 1 bytes to start whatever follows it (raw or RLE)
  2626. if ((run_len >= 3) && (cost_to_take_run < cost_to_keep_raw))
  2627. {
  2628. file_data.push_back((uint8_t)(128 + run_len));
  2629. file_data.push_back(cur_byte);
  2630. x += run_len;
  2631. raw_ofs = -1;
  2632. }
  2633. else
  2634. {
  2635. if (raw_ofs < 0)
  2636. {
  2637. raw_ofs = (int)file_data.size();
  2638. file_data.push_back(0);
  2639. }
  2640. if (++file_data[raw_ofs] == 128)
  2641. raw_ofs = -1;
  2642. file_data.push_back(cur_byte);
  2643. x++;
  2644. }
  2645. } // x
  2646. } // c
  2647. } // y
  2648. }
  2649. return true;
  2650. }
  2651. bool write_rgbe(const char* pFilename, imagef& img, rgbe_header_info& hdr_info)
  2652. {
  2653. uint8_vec file_data;
  2654. if (!write_rgbe(file_data, img, hdr_info))
  2655. return false;
  2656. return write_vec_to_file(pFilename, file_data);
  2657. }
  2658. bool read_exr(const char* pFilename, imagef& img, int& n_chans)
  2659. {
  2660. n_chans = 0;
  2661. int width = 0, height = 0;
  2662. float* out_rgba = nullptr;
  2663. const char* err = nullptr;
  2664. int status = LoadEXRWithLayer(&out_rgba, &width, &height, pFilename, nullptr, &err);
  2665. n_chans = 4;
  2666. if (status != 0)
  2667. {
  2668. error_printf("Failed loading .EXR image \"%s\"! (TinyEXR error: %s)\n", pFilename, err ? err : "?");
  2669. FreeEXRErrorMessage(err);
  2670. free(out_rgba);
  2671. return false;
  2672. }
  2673. const uint32_t MAX_SUPPORTED_DIM = 65536;
  2674. if ((width < 1) || (height < 1) || (width > (int)MAX_SUPPORTED_DIM) || (height > (int)MAX_SUPPORTED_DIM))
  2675. {
  2676. error_printf("Invalid dimensions of .EXR image \"%s\"!\n", pFilename);
  2677. free(out_rgba);
  2678. return false;
  2679. }
  2680. img.resize(width, height);
  2681. if (n_chans == 1)
  2682. {
  2683. const float* pSrc = out_rgba;
  2684. vec4F* pDst = img.get_ptr();
  2685. for (int y = 0; y < height; y++)
  2686. {
  2687. for (int x = 0; x < width; x++)
  2688. {
  2689. (*pDst)[0] = pSrc[0];
  2690. (*pDst)[1] = pSrc[1];
  2691. (*pDst)[2] = pSrc[2];
  2692. (*pDst)[3] = 1.0f;
  2693. pSrc += 4;
  2694. ++pDst;
  2695. }
  2696. }
  2697. }
  2698. else
  2699. {
  2700. memcpy(img.get_ptr(), out_rgba, sizeof(float) * 4 * img.get_total_pixels());
  2701. }
  2702. free(out_rgba);
  2703. return true;
  2704. }
  2705. bool read_exr(const void* pMem, size_t mem_size, imagef& img)
  2706. {
  2707. float* out_rgba = nullptr;
  2708. int width = 0, height = 0;
  2709. const char* pErr = nullptr;
  2710. int res = LoadEXRFromMemory(&out_rgba, &width, &height, (const uint8_t*)pMem, mem_size, &pErr);
  2711. if (res < 0)
  2712. {
  2713. error_printf("Failed loading .EXR image from memory! (TinyEXR error: %s)\n", pErr ? pErr : "?");
  2714. FreeEXRErrorMessage(pErr);
  2715. free(out_rgba);
  2716. return false;
  2717. }
  2718. img.resize(width, height);
  2719. memcpy(img.get_ptr(), out_rgba, width * height * sizeof(float) * 4);
  2720. free(out_rgba);
  2721. return true;
  2722. }
  2723. bool write_exr(const char* pFilename, imagef& img, uint32_t n_chans, uint32_t flags)
  2724. {
  2725. assert((n_chans == 1) || (n_chans == 3) || (n_chans == 4));
  2726. const bool linear_hint = (flags & WRITE_EXR_LINEAR_HINT) != 0,
  2727. store_float = (flags & WRITE_EXR_STORE_FLOATS) != 0,
  2728. no_compression = (flags & WRITE_EXR_NO_COMPRESSION) != 0;
  2729. const uint32_t width = img.get_width(), height = img.get_height();
  2730. assert(width && height);
  2731. if (!width || !height)
  2732. return false;
  2733. float_vec layers[4];
  2734. float* image_ptrs[4];
  2735. for (uint32_t c = 0; c < n_chans; c++)
  2736. {
  2737. layers[c].resize(width * height);
  2738. image_ptrs[c] = layers[c].get_ptr();
  2739. }
  2740. // ABGR
  2741. int chan_order[4] = { 3, 2, 1, 0 };
  2742. if (n_chans == 1)
  2743. {
  2744. // Y
  2745. chan_order[0] = 0;
  2746. }
  2747. else if (n_chans == 3)
  2748. {
  2749. // BGR
  2750. chan_order[0] = 2;
  2751. chan_order[1] = 1;
  2752. chan_order[2] = 0;
  2753. }
  2754. else if (n_chans != 4)
  2755. {
  2756. assert(0);
  2757. return false;
  2758. }
  2759. for (uint32_t y = 0; y < height; y++)
  2760. {
  2761. for (uint32_t x = 0; x < width; x++)
  2762. {
  2763. const vec4F& p = img(x, y);
  2764. for (uint32_t c = 0; c < n_chans; c++)
  2765. layers[c][x + y * width] = p[chan_order[c]];
  2766. } // x
  2767. } // y
  2768. EXRHeader header;
  2769. InitEXRHeader(&header);
  2770. EXRImage image;
  2771. InitEXRImage(&image);
  2772. image.num_channels = n_chans;
  2773. image.images = (unsigned char**)image_ptrs;
  2774. image.width = width;
  2775. image.height = height;
  2776. header.num_channels = n_chans;
  2777. header.channels = (EXRChannelInfo*)calloc(header.num_channels, sizeof(EXRChannelInfo));
  2778. // Must be (A)BGR order, since most of EXR viewers expect this channel order.
  2779. for (uint32_t i = 0; i < n_chans; i++)
  2780. {
  2781. char c = 'Y';
  2782. if (n_chans == 3)
  2783. c = "BGR"[i];
  2784. else if (n_chans == 4)
  2785. c = "ABGR"[i];
  2786. header.channels[i].name[0] = c;
  2787. header.channels[i].name[1] = '\0';
  2788. header.channels[i].p_linear = linear_hint;
  2789. }
  2790. header.pixel_types = (int*)calloc(header.num_channels, sizeof(int));
  2791. header.requested_pixel_types = (int*)calloc(header.num_channels, sizeof(int));
  2792. if (!no_compression)
  2793. header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP;
  2794. for (int i = 0; i < header.num_channels; i++)
  2795. {
  2796. // pixel type of input image
  2797. header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT;
  2798. // pixel type of output image to be stored in .EXR
  2799. header.requested_pixel_types[i] = store_float ? TINYEXR_PIXELTYPE_FLOAT : TINYEXR_PIXELTYPE_HALF;
  2800. }
  2801. const char* pErr_msg = nullptr;
  2802. int ret = SaveEXRImageToFile(&image, &header, pFilename, &pErr_msg);
  2803. if (ret != TINYEXR_SUCCESS)
  2804. {
  2805. error_printf("Save EXR err: %s\n", pErr_msg);
  2806. FreeEXRErrorMessage(pErr_msg);
  2807. }
  2808. free(header.channels);
  2809. free(header.pixel_types);
  2810. free(header.requested_pixel_types);
  2811. return (ret == TINYEXR_SUCCESS);
  2812. }
  2813. void image::debug_text(uint32_t x_ofs, uint32_t y_ofs, uint32_t scale_x, uint32_t scale_y, const color_rgba& fg, const color_rgba* pBG, bool alpha_only, const char* pFmt, ...)
  2814. {
  2815. char buf[2048];
  2816. va_list args;
  2817. va_start(args, pFmt);
  2818. #ifdef _WIN32
  2819. vsprintf_s(buf, sizeof(buf), pFmt, args);
  2820. #else
  2821. vsnprintf(buf, sizeof(buf), pFmt, args);
  2822. #endif
  2823. va_end(args);
  2824. const char* p = buf;
  2825. const uint32_t orig_x_ofs = x_ofs;
  2826. while (*p)
  2827. {
  2828. uint8_t c = *p++;
  2829. if ((c < 32) || (c > 127))
  2830. c = '.';
  2831. const uint8_t* pGlpyh = &g_debug_font8x8_basic[c - 32][0];
  2832. for (uint32_t y = 0; y < 8; y++)
  2833. {
  2834. uint32_t row_bits = pGlpyh[y];
  2835. for (uint32_t x = 0; x < 8; x++)
  2836. {
  2837. const uint32_t q = row_bits & (1 << x);
  2838. const color_rgba* pColor = q ? &fg : pBG;
  2839. if (!pColor)
  2840. continue;
  2841. if (alpha_only)
  2842. fill_box_alpha(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
  2843. else
  2844. fill_box(x_ofs + x * scale_x, y_ofs + y * scale_y, scale_x, scale_y, *pColor);
  2845. }
  2846. }
  2847. x_ofs += 8 * scale_x;
  2848. if ((x_ofs + 8 * scale_x) > m_width)
  2849. {
  2850. x_ofs = orig_x_ofs;
  2851. y_ofs += 8 * scale_y;
  2852. }
  2853. }
  2854. }
  2855. // Very basic global Reinhard tone mapping, output converted to sRGB with no dithering, alpha is carried through unchanged.
  2856. // Only used for debugging/development.
  2857. void tonemap_image_reinhard(image &ldr_img, const imagef &hdr_img, float exposure)
  2858. {
  2859. uint32_t width = hdr_img.get_width(), height = hdr_img.get_height();
  2860. ldr_img.resize(width, height);
  2861. for (uint32_t y = 0; y < height; y++)
  2862. {
  2863. for (uint32_t x = 0; x < width; x++)
  2864. {
  2865. vec4F c(hdr_img(x, y));
  2866. for (uint32_t t = 0; t < 3; t++)
  2867. {
  2868. if (c[t] <= 0.0f)
  2869. {
  2870. c[t] = 0.0f;
  2871. }
  2872. else
  2873. {
  2874. c[t] *= exposure;
  2875. c[t] = c[t] / (1.0f + c[t]);
  2876. }
  2877. }
  2878. c.clamp(0.0f, 1.0f);
  2879. c[0] = linear_to_srgb(c[0]) * 255.0f;
  2880. c[1] = linear_to_srgb(c[1]) * 255.0f;
  2881. c[2] = linear_to_srgb(c[2]) * 255.0f;
  2882. c[3] = c[3] * 255.0f;
  2883. color_rgba& o = ldr_img(x, y);
  2884. o[0] = (uint8_t)std::round(c[0]);
  2885. o[1] = (uint8_t)std::round(c[1]);
  2886. o[2] = (uint8_t)std::round(c[2]);
  2887. o[3] = (uint8_t)std::round(c[3]);
  2888. }
  2889. }
  2890. }
  2891. bool tonemap_image_compressive(image& dst_img, const imagef& hdr_test_img)
  2892. {
  2893. const uint32_t width = hdr_test_img.get_width();
  2894. const uint32_t height = hdr_test_img.get_height();
  2895. uint16_vec orig_half_img(width * 3 * height);
  2896. uint16_vec half_img(width * 3 * height);
  2897. int max_shift = 32;
  2898. for (uint32_t y = 0; y < height; y++)
  2899. {
  2900. for (uint32_t x = 0; x < width; x++)
  2901. {
  2902. const vec4F& p = hdr_test_img(x, y);
  2903. for (uint32_t i = 0; i < 3; i++)
  2904. {
  2905. if (p[i] < 0.0f)
  2906. return false;
  2907. if (p[i] > basist::MAX_HALF_FLOAT)
  2908. return false;
  2909. uint32_t h = basist::float_to_half(p[i]);
  2910. //uint32_t orig_h = h;
  2911. orig_half_img[(x + y * width) * 3 + i] = (uint16_t)h;
  2912. // Rotate sign bit into LSB
  2913. //h = rot_left16((uint16_t)h, 1);
  2914. //assert(rot_right16((uint16_t)h, 1) == orig_h);
  2915. h <<= 1;
  2916. half_img[(x + y * width) * 3 + i] = (uint16_t)h;
  2917. // Determine # of leading zero bits, ignoring the sign bit
  2918. if (h)
  2919. {
  2920. int lz = clz(h) - 16;
  2921. assert(lz >= 0 && lz <= 16);
  2922. assert((h << lz) <= 0xFFFF);
  2923. max_shift = basisu::minimum<int>(max_shift, lz);
  2924. }
  2925. } // i
  2926. } // x
  2927. } // y
  2928. //printf("tonemap_image_compressive: Max leading zeros: %i\n", max_shift);
  2929. uint32_t high_hist[256];
  2930. clear_obj(high_hist);
  2931. for (uint32_t y = 0; y < height; y++)
  2932. {
  2933. for (uint32_t x = 0; x < width; x++)
  2934. {
  2935. for (uint32_t i = 0; i < 3; i++)
  2936. {
  2937. uint16_t& hf = half_img[(x + y * width) * 3 + i];
  2938. assert(((uint32_t)hf << max_shift) <= 65535);
  2939. hf <<= max_shift;
  2940. uint32_t h = (uint8_t)(hf >> 8);
  2941. high_hist[h]++;
  2942. }
  2943. } // x
  2944. } // y
  2945. uint32_t total_vals_used = 0;
  2946. int remap_old_to_new[256];
  2947. for (uint32_t i = 0; i < 256; i++)
  2948. remap_old_to_new[i] = -1;
  2949. for (uint32_t i = 0; i < 256; i++)
  2950. {
  2951. if (high_hist[i] != 0)
  2952. {
  2953. remap_old_to_new[i] = total_vals_used;
  2954. total_vals_used++;
  2955. }
  2956. }
  2957. assert(total_vals_used >= 1);
  2958. //printf("tonemap_image_compressive: Total used high byte values: %u, unused: %u\n", total_vals_used, 256 - total_vals_used);
  2959. bool val_used[256];
  2960. clear_obj(val_used);
  2961. int remap_new_to_old[256];
  2962. for (uint32_t i = 0; i < 256; i++)
  2963. remap_new_to_old[i] = -1;
  2964. BASISU_NOTE_UNUSED(remap_new_to_old);
  2965. int prev_c = -1;
  2966. BASISU_NOTE_UNUSED(prev_c);
  2967. for (uint32_t i = 0; i < 256; i++)
  2968. {
  2969. if (remap_old_to_new[i] >= 0)
  2970. {
  2971. int c;
  2972. if (total_vals_used <= 1)
  2973. c = remap_old_to_new[i];
  2974. else
  2975. {
  2976. c = (remap_old_to_new[i] * 255 + ((total_vals_used - 1) / 2)) / (total_vals_used - 1);
  2977. assert(c > prev_c);
  2978. }
  2979. assert(!val_used[c]);
  2980. remap_new_to_old[c] = i;
  2981. remap_old_to_new[i] = c;
  2982. prev_c = c;
  2983. //printf("%u ", c);
  2984. val_used[c] = true;
  2985. }
  2986. } // i
  2987. //printf("\n");
  2988. dst_img.resize(width, height);
  2989. for (uint32_t y = 0; y < height; y++)
  2990. {
  2991. for (uint32_t x = 0; x < width; x++)
  2992. {
  2993. for (uint32_t c = 0; c < 3; c++)
  2994. {
  2995. uint16_t& v16 = half_img[(x + y * width) * 3 + c];
  2996. uint32_t hb = v16 >> 8;
  2997. //uint32_t lb = v16 & 0xFF;
  2998. assert(remap_old_to_new[hb] != -1);
  2999. assert(remap_old_to_new[hb] <= 255);
  3000. assert(remap_new_to_old[remap_old_to_new[hb]] == (int)hb);
  3001. hb = remap_old_to_new[hb];
  3002. //v16 = (uint16_t)((hb << 8) | lb);
  3003. dst_img(x, y)[c] = (uint8_t)hb;
  3004. }
  3005. } // x
  3006. } // y
  3007. return true;
  3008. }
  3009. } // namespace basisu