sokol_fetch.h 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810
  1. #if defined(SOKOL_IMPL) && !defined(SOKOL_FETCH_IMPL)
  2. #define SOKOL_FETCH_IMPL
  3. #endif
  4. #ifndef SOKOL_FETCH_INCLUDED
  5. /*
  6. sokol_fetch.h -- asynchronous data loading/streaming
  7. Project URL: https://github.com/floooh/sokol
  8. Do this:
  9. #define SOKOL_IMPL or
  10. #define SOKOL_FETCH_IMPL
  11. before you include this file in *one* C or C++ file to create the
  12. implementation.
  13. Optionally provide the following defines with your own implementations:
  14. SOKOL_ASSERT(c) - your own assert macro (default: assert(c))
  15. SOKOL_UNREACHABLE() - a guard macro for unreachable code (default: assert(false))
  16. SOKOL_FETCH_API_DECL - public function declaration prefix (default: extern)
  17. SOKOL_API_DECL - same as SOKOL_FETCH_API_DECL
  18. SOKOL_API_IMPL - public function implementation prefix (default: -)
  19. SFETCH_MAX_PATH - max length of UTF-8 filesystem path / URL (default: 1024 bytes)
  20. SFETCH_MAX_USERDATA_UINT64 - max size of embedded userdata in number of uint64_t, userdata
  21. will be copied into an 8-byte aligned memory region associated
  22. with each in-flight request, default value is 16 (== 128 bytes)
  23. SFETCH_MAX_CHANNELS - max number of IO channels (default is 16, also see sfetch_desc_t.num_channels)
  24. If sokol_fetch.h is compiled as a DLL, define the following before
  25. including the declaration or implementation:
  26. SOKOL_DLL
  27. On Windows, SOKOL_DLL will define SOKOL_FETCH_API_DECL as __declspec(dllexport)
  28. or __declspec(dllimport) as needed.
  29. NOTE: The following documentation talks a lot about "IO threads". Actual
  30. threads are only used on platforms where threads are available. The web
  31. version (emscripten/wasm) doesn't use POSIX-style threads, but instead
  32. asynchronous Javascript calls chained together by callbacks. The actual
  33. source code differences between the two approaches have been kept to
  34. a minimum though.
  35. FEATURE OVERVIEW
  36. ================
  37. - Asynchronously load complete files, or stream files incrementally via
  38. HTTP (on web platform), or the local file system (on native platforms)
  39. - Request / response-callback model, user code sends a request
  40. to initiate a file-load, sokol_fetch.h calls the response callback
  41. on the same thread when data is ready or user-code needs
  42. to respond otherwise
  43. - Not limited to the main-thread or a single thread: A sokol-fetch
  44. "context" can live on any thread, and multiple contexts
  45. can operate side-by-side on different threads.
  46. - Memory management for data buffers is under full control of user code.
  47. sokol_fetch.h won't allocate memory after it has been setup.
  48. - Automatic rate-limiting guarantees that only a maximum number of
  49. requests is processed at any one time, allowing a zero-allocation
  50. model, where all data is streamed into fixed-size, pre-allocated
  51. buffers.
  52. - Active Requests can be paused, continued and cancelled from anywhere
  53. in the user-thread which sent this request.
  54. TL;DR EXAMPLE CODE
  55. ==================
  56. This is the most-simple example code to load a single data file with a
  57. known maximum size:
  58. (1) initialize sokol-fetch with default parameters (but NOTE that the
  59. default setup parameters provide a safe-but-slow "serialized"
  60. operation). In order to see any logging output in case or errors
  61. you should always provide a logging function
  62. (such as 'slog_func' from sokol_log.h):
  63. sfetch_setup(&(sfetch_desc_t){ .logger.func = slog_func });
  64. (2) send a fetch-request to load a file from the current directory
  65. into a buffer big enough to hold the entire file content:
  66. static uint8_t buf[MAX_FILE_SIZE];
  67. sfetch_send(&(sfetch_request_t){
  68. .path = "my_file.txt",
  69. .callback = response_callback,
  70. .buffer = {
  71. .ptr = buf,
  72. .size = sizeof(buf)
  73. }
  74. });
  75. If 'buf' is a value (e.g. an array or struct item), the .buffer item can
  76. be initialized with the SFETCH_RANGE() helper macro:
  77. sfetch_send(&(sfetch_request_t){
  78. .path = "my_file.txt",
  79. .callback = response_callback,
  80. .buffer = SFETCH_RANGE(buf)
  81. });
  82. (3) write a 'response-callback' function, this will be called whenever
  83. the user-code must respond to state changes of the request
  84. (most importantly when data has been loaded):
  85. void response_callback(const sfetch_response_t* response) {
  86. if (response->fetched) {
  87. // data has been loaded, and is available via the
  88. // sfetch_range_t struct item 'data':
  89. const void* ptr = response->data.ptr;
  90. size_t num_bytes = response->data.size;
  91. }
  92. if (response->finished) {
  93. // the 'finished'-flag is the catch-all flag for when the request
  94. // is finished, no matter if loading was successful or failed,
  95. // so any cleanup-work should happen here...
  96. ...
  97. if (response->failed) {
  98. // 'failed' is true in (addition to 'finished') if something
  99. // went wrong (file doesn't exist, or less bytes could be
  100. // read from the file than expected)
  101. }
  102. }
  103. }
  104. (4) pump the sokol-fetch message queues, and invoke response callbacks
  105. by calling:
  106. sfetch_dowork();
  107. In an event-driven app this should be called in the event loop. If you
  108. use sokol-app this would be in your frame_cb function.
  109. (5) finally, call sfetch_shutdown() at the end of the application:
  110. There's many other loading-scenarios, for instance one doesn't have to
  111. provide a buffer upfront, this can also happen in the response callback.
  112. Or it's possible to stream huge files into small fixed-size buffer,
  113. complete with pausing and continuing the download.
  114. It's also possible to improve the 'pipeline throughput' by fetching
  115. multiple files in parallel, but at the same time limit the maximum
  116. number of requests that can be 'in-flight'.
  117. For how this all works, please read the following documentation sections :)
  118. API DOCUMENTATION
  119. =================
  120. void sfetch_setup(const sfetch_desc_t* desc)
  121. --------------------------------------------
  122. First call sfetch_setup(const sfetch_desc_t*) on any thread before calling
  123. any other sokol-fetch functions on the same thread.
  124. sfetch_setup() takes a pointer to an sfetch_desc_t struct with setup
  125. parameters. Parameters which should use their default values must
  126. be zero-initialized:
  127. - max_requests (uint32_t):
  128. The maximum number of requests that can be alive at any time, the
  129. default is 128.
  130. - num_channels (uint32_t):
  131. The number of "IO channels" used to parallelize and prioritize
  132. requests, the default is 1.
  133. - num_lanes (uint32_t):
  134. The number of "lanes" on a single channel. Each request which is
  135. currently 'inflight' on a channel occupies one lane until the
  136. request is finished. This is used for automatic rate-limiting
  137. (search below for CHANNELS AND LANES for more details). The
  138. default number of lanes is 1.
  139. For example, to setup sokol-fetch for max 1024 active requests, 4 channels,
  140. and 8 lanes per channel in C99:
  141. sfetch_setup(&(sfetch_desc_t){
  142. .max_requests = 1024,
  143. .num_channels = 4,
  144. .num_lanes = 8
  145. });
  146. sfetch_setup() is the only place where sokol-fetch will allocate memory.
  147. NOTE that the default setup parameters of 1 channel and 1 lane per channel
  148. has a very poor 'pipeline throughput' since this essentially serializes
  149. IO requests (a new request will only be processed when the last one has
  150. finished), and since each request needs at least one roundtrip between
  151. the user- and IO-thread the throughput will be at most one request per
  152. frame. Search for LATENCY AND THROUGHPUT below for more information on
  153. how to increase throughput.
  154. NOTE that you can call sfetch_setup() on multiple threads, each thread
  155. will get its own thread-local sokol-fetch instance, which will work
  156. independently from sokol-fetch instances on other threads.
  157. void sfetch_shutdown(void)
  158. --------------------------
  159. Call sfetch_shutdown() at the end of the application to stop any
  160. IO threads and free all memory that was allocated in sfetch_setup().
  161. sfetch_handle_t sfetch_send(const sfetch_request_t* request)
  162. ------------------------------------------------------------
  163. Call sfetch_send() to start loading data, the function takes a pointer to an
  164. sfetch_request_t struct with request parameters and returns a
  165. sfetch_handle_t identifying the request for later calls. At least
  166. a path/URL and callback must be provided:
  167. sfetch_handle_t h = sfetch_send(&(sfetch_request_t){
  168. .path = "my_file.txt",
  169. .callback = my_response_callback
  170. });
  171. sfetch_send() will return an invalid handle if no request can be allocated
  172. from the internal pool because all available request items are 'in-flight'.
  173. The sfetch_request_t struct contains the following parameters (optional
  174. parameters that are not provided must be zero-initialized):
  175. - path (const char*, required)
  176. Pointer to an UTF-8 encoded C string describing the filesystem
  177. path or HTTP URL. The string will be copied into an internal data
  178. structure, and passed "as is" (apart from any required
  179. encoding-conversions) to fopen(), CreateFileW() or
  180. the html fetch API call. The maximum length of the string is defined by
  181. the SFETCH_MAX_PATH configuration define, the default is 1024 bytes
  182. including the 0-terminator byte.
  183. - callback (sfetch_callback_t, required)
  184. Pointer to a response-callback function which is called when the
  185. request needs "user code attention". Search below for REQUEST
  186. STATES AND THE RESPONSE CALLBACK for detailed information about
  187. handling responses in the response callback.
  188. - channel (uint32_t, optional)
  189. Index of the IO channel where the request should be processed.
  190. Channels are used to parallelize and prioritize requests relative
  191. to each other. Search below for CHANNELS AND LANES for more
  192. information. The default channel is 0.
  193. - chunk_size (uint32_t, optional)
  194. The chunk_size member is used for streaming data incrementally
  195. in small chunks. After 'chunk_size' bytes have been loaded into
  196. to the streaming buffer, the response callback will be called
  197. with the buffer containing the fetched data for the current chunk.
  198. If chunk_size is 0 (the default), than the whole file will be loaded.
  199. Please search below for CHUNK SIZE AND HTTP COMPRESSION for
  200. important information how streaming works if the web server
  201. is serving compressed data.
  202. - buffer (sfetch_range_t)
  203. This is a optional pointer/size pair describing a chunk of memory where
  204. data will be loaded into (if no buffer is provided upfront, this
  205. must happen in the response callback). If a buffer is provided,
  206. it must be big enough to either hold the entire file (if chunk_size
  207. is zero), or the *uncompressed* data for one downloaded chunk
  208. (if chunk_size is > 0).
  209. - user_data (sfetch_range_t)
  210. The user_data ptr/size range struct describe an optional POD blob
  211. (plain-old-data) associated with the request which will be copied(!)
  212. into an internal memory block. The maximum default size of this
  213. memory block is 128 bytes (but can be overridden by defining
  214. SFETCH_MAX_USERDATA_UINT64 before including the notification, note
  215. that this define is in "number of uint64_t", not number of bytes).
  216. The user-data block is 8-byte aligned, and will be copied via
  217. memcpy() (so don't put any C++ "smart members" in there).
  218. NOTE that request handles are strictly thread-local and only unique
  219. within the thread the handle was created on, and all function calls
  220. involving a request handle must happen on that same thread.
  221. bool sfetch_handle_valid(sfetch_handle_t request)
  222. -------------------------------------------------
  223. This checks if the provided request handle is valid, and is associated with
  224. a currently active request. It will return false if:
  225. - sfetch_send() returned an invalid handle because it couldn't allocate
  226. a new request from the internal request pool (because they're all
  227. in flight)
  228. - the request associated with the handle is no longer alive (because
  229. it either finished successfully, or the request failed for some
  230. reason)
  231. void sfetch_dowork(void)
  232. ------------------------
  233. Call sfetch_dowork(void) in regular intervals (for instance once per frame)
  234. on the same thread as sfetch_setup() to "turn the gears". If you are sending
  235. requests but never hear back from them in the response callback function, then
  236. the most likely reason is that you forgot to add the call to sfetch_dowork()
  237. in the per-frame function.
  238. sfetch_dowork() roughly performs the following work:
  239. - any new requests that have been sent with sfetch_send() since the
  240. last call to sfetch_dowork() will be dispatched to their IO channels
  241. and assigned a free lane. If all lanes on that channel are occupied
  242. by requests 'in flight', incoming requests must wait until
  243. a lane becomes available
  244. - for all new requests which have been enqueued on a channel which
  245. don't already have a buffer assigned the response callback will be
  246. called with (response->dispatched == true) so that the response
  247. callback can inspect the dynamically assigned lane and bind a buffer
  248. to the request (search below for CHANNELS AND LANE for more info)
  249. - a state transition from "user side" to "IO thread side" happens for
  250. each new request that has been dispatched to a channel.
  251. - requests dispatched to a channel are either forwarded into that
  252. channel's worker thread (on native platforms), or cause an HTTP
  253. request to be sent via an asynchronous fetch() call (on the web
  254. platform)
  255. - for all requests which have finished their current IO operation a
  256. state transition from "IO thread side" to "user side" happens,
  257. and the response callback is called so that the fetched data
  258. can be processed.
  259. - requests which are completely finished (either because the entire
  260. file content has been loaded, or they are in the FAILED state) are
  261. freed (this just changes their state in the 'request pool', no actual
  262. memory is freed)
  263. - requests which are not yet finished are fed back into the
  264. 'incoming' queue of their channel, and the cycle starts again, this
  265. only happens for requests which perform data streaming (not load
  266. the entire file at once).
  267. void sfetch_cancel(sfetch_handle_t request)
  268. -------------------------------------------
  269. This cancels a request in the next sfetch_dowork() call and invokes the
  270. response callback with (response.failed == true) and (response.finished
  271. == true) to give user-code a chance to do any cleanup work for the
  272. request. If sfetch_cancel() is called for a request that is no longer
  273. alive, nothing bad will happen (the call will simply do nothing).
  274. void sfetch_pause(sfetch_handle_t request)
  275. ------------------------------------------
  276. This pauses an active request in the next sfetch_dowork() call and puts
  277. it into the PAUSED state. For all requests in PAUSED state, the response
  278. callback will be called in each call to sfetch_dowork() to give user-code
  279. a chance to CONTINUE the request (by calling sfetch_continue()). Pausing
  280. a request makes sense for dynamic rate-limiting in streaming scenarios
  281. (like video/audio streaming with a fixed number of streaming buffers. As
  282. soon as all available buffers are filled with download data, downloading
  283. more data must be prevented to allow video/audio playback to catch up and
  284. free up empty buffers for new download data.
  285. void sfetch_continue(sfetch_handle_t request)
  286. ---------------------------------------------
  287. Continues a paused request, counterpart to the sfetch_pause() function.
  288. void sfetch_bind_buffer(sfetch_handle_t request, sfetch_range_t buffer)
  289. ----------------------------------------------------------------------------------------
  290. This "binds" a new buffer (as pointer/size pair) to an active request. The
  291. function *must* be called from inside the response-callback, and there
  292. must not already be another buffer bound.
  293. void* sfetch_unbind_buffer(sfetch_handle_t request)
  294. ---------------------------------------------------
  295. This removes the current buffer binding from the request and returns
  296. a pointer to the previous buffer (useful if the buffer was dynamically
  297. allocated and it must be freed).
  298. sfetch_unbind_buffer() *must* be called from inside the response callback.
  299. The usual code sequence to bind a different buffer in the response
  300. callback might look like this:
  301. void response_callback(const sfetch_response_t* response) {
  302. if (response.fetched) {
  303. ...
  304. // switch to a different buffer (in the FETCHED state it is
  305. // guaranteed that the request has a buffer, otherwise it
  306. // would have gone into the FAILED state
  307. void* old_buf_ptr = sfetch_unbind_buffer(response.handle);
  308. free(old_buf_ptr);
  309. void* new_buf_ptr = malloc(new_buf_size);
  310. sfetch_bind_buffer(response.handle, new_buf_ptr, new_buf_size);
  311. }
  312. if (response.finished) {
  313. // unbind and free the currently associated buffer,
  314. // the buffer pointer could be null if the request has failed
  315. // NOTE that it is legal to call free() with a nullptr,
  316. // this happens if the request failed to open its file
  317. // and never goes into the OPENED state
  318. void* buf_ptr = sfetch_unbind_buffer(response.handle);
  319. free(buf_ptr);
  320. }
  321. }
  322. sfetch_desc_t sfetch_desc(void)
  323. -------------------------------
  324. sfetch_desc() returns a copy of the sfetch_desc_t struct passed to
  325. sfetch_setup(), with zero-initialized values replaced with
  326. their default values.
  327. int sfetch_max_userdata_bytes(void)
  328. -----------------------------------
  329. This returns the value of the SFETCH_MAX_USERDATA_UINT64 config
  330. define, but in number of bytes (so SFETCH_MAX_USERDATA_UINT64*8).
  331. int sfetch_max_path(void)
  332. -------------------------
  333. Returns the value of the SFETCH_MAX_PATH config define.
  334. REQUEST STATES AND THE RESPONSE CALLBACK
  335. ========================================
  336. A request goes through a number of states during its lifetime. Depending
  337. on the current state of a request, it will be 'owned' either by the
  338. "user-thread" (where the request was sent) or an IO thread.
  339. You can think of a request as "ping-ponging" between the IO thread and
  340. user thread, any actual IO work is done on the IO thread, while
  341. invocations of the response-callback happen on the user-thread.
  342. All state transitions and callback invocations happen inside the
  343. sfetch_dowork() function.
  344. An active request goes through the following states:
  345. ALLOCATED (user-thread)
  346. The request has been allocated in sfetch_send() and is
  347. waiting to be dispatched into its IO channel. When this
  348. happens, the request will transition into the DISPATCHED state.
  349. DISPATCHED (IO thread)
  350. The request has been dispatched into its IO channel, and a
  351. lane has been assigned to the request.
  352. If a buffer was provided in sfetch_send() the request will
  353. immediately transition into the FETCHING state and start loading
  354. data into the buffer.
  355. If no buffer was provided in sfetch_send(), the response
  356. callback will be called with (response->dispatched == true),
  357. so that the response callback can bind a buffer to the
  358. request. Binding the buffer in the response callback makes
  359. sense if the buffer isn't dynamically allocated, but instead
  360. a pre-allocated buffer must be selected from the request's
  361. channel and lane.
  362. Note that it isn't possible to get a file size in the response callback
  363. which would help with allocating a buffer of the right size, this is
  364. because it isn't possible in HTTP to query the file size before the
  365. entire file is downloaded (...when the web server serves files compressed).
  366. If opening the file failed, the request will transition into
  367. the FAILED state with the error code SFETCH_ERROR_FILE_NOT_FOUND.
  368. FETCHING (IO thread)
  369. While a request is in the FETCHING state, data will be loaded into
  370. the user-provided buffer.
  371. If no buffer was provided, the request will go into the FAILED
  372. state with the error code SFETCH_ERROR_NO_BUFFER.
  373. If a buffer was provided, but it is too small to contain the
  374. fetched data, the request will go into the FAILED state with
  375. error code SFETCH_ERROR_BUFFER_TOO_SMALL.
  376. If less data can be read from the file than expected, the request
  377. will go into the FAILED state with error code SFETCH_ERROR_UNEXPECTED_EOF.
  378. If loading data into the provided buffer works as expected, the
  379. request will go into the FETCHED state.
  380. FETCHED (user thread)
  381. The request goes into the FETCHED state either when the entire file
  382. has been loaded into the provided buffer (when request.chunk_size == 0),
  383. or a chunk has been loaded (and optionally decompressed) into the
  384. buffer (when request.chunk_size > 0).
  385. The response callback will be called so that the user-code can
  386. process the loaded data using the following sfetch_response_t struct members:
  387. - data.ptr: pointer to the start of fetched data
  388. - data.size: the number of bytes in the provided buffer
  389. - data_offset: the byte offset of the loaded data chunk in the
  390. overall file (this is only set to a non-zero value in a streaming
  391. scenario)
  392. Once all file data has been loaded, the 'finished' flag will be set
  393. in the response callback's sfetch_response_t argument.
  394. After the user callback returns, and all file data has been loaded
  395. (response.finished flag is set) the request has reached its end-of-life
  396. and will be recycled.
  397. Otherwise, if there's still data to load (because streaming was
  398. requested by providing a non-zero request.chunk_size), the request
  399. will switch back to the FETCHING state to load the next chunk of data.
  400. Note that it is ok to associate a different buffer or buffer-size
  401. with the request by calling sfetch_bind_buffer() in the response-callback.
  402. To check in the response callback for the FETCHED state, and
  403. independently whether the request is finished:
  404. void response_callback(const sfetch_response_t* response) {
  405. if (response->fetched) {
  406. // request is in FETCHED state, the loaded data is available
  407. // in .data.ptr, and the number of bytes that have been
  408. // loaded in .data.size:
  409. const void* data = response->data.ptr;
  410. size_t num_bytes = response->data.size;
  411. }
  412. if (response->finished) {
  413. // the finished flag is set either when all data
  414. // has been loaded, the request has been cancelled,
  415. // or the file operation has failed, this is where
  416. // any required per-request cleanup work should happen
  417. }
  418. }
  419. FAILED (user thread)
  420. A request will transition into the FAILED state in the following situations:
  421. - if the file doesn't exist or couldn't be opened for other
  422. reasons (SFETCH_ERROR_FILE_NOT_FOUND)
  423. - if no buffer is associated with the request in the FETCHING state
  424. (SFETCH_ERROR_NO_BUFFER)
  425. - if the provided buffer is too small to hold the entire file
  426. (if request.chunk_size == 0), or the (potentially decompressed)
  427. partial data chunk (SFETCH_ERROR_BUFFER_TOO_SMALL)
  428. - if less bytes could be read from the file then expected
  429. (SFETCH_ERROR_UNEXPECTED_EOF)
  430. - if a request has been cancelled via sfetch_cancel()
  431. (SFETCH_ERROR_CANCELLED)
  432. The response callback will be called once after a request goes into
  433. the FAILED state, with the 'response->finished' and
  434. 'response->failed' flags set to true.
  435. This gives the user-code a chance to cleanup any resources associated
  436. with the request.
  437. To check for the failed state in the response callback:
  438. void response_callback(const sfetch_response_t* response) {
  439. if (response->failed) {
  440. // specifically check for the failed state...
  441. }
  442. // or you can do a catch-all check via the finished-flag:
  443. if (response->finished) {
  444. if (response->failed) {
  445. // if more detailed error handling is needed:
  446. switch (response->error_code) {
  447. ...
  448. }
  449. }
  450. }
  451. }
  452. PAUSED (user thread)
  453. A request will transition into the PAUSED state after user-code
  454. calls the function sfetch_pause() on the request's handle. Usually
  455. this happens from within the response-callback in streaming scenarios
  456. when the data streaming needs to wait for a data decoder (like
  457. a video/audio player) to catch up.
  458. While a request is in PAUSED state, the response-callback will be
  459. called in each sfetch_dowork(), so that the user-code can either
  460. continue the request by calling sfetch_continue(), or cancel
  461. the request by calling sfetch_cancel().
  462. When calling sfetch_continue() on a paused request, the request will
  463. transition into the FETCHING state. Otherwise if sfetch_cancel() is
  464. called, the request will switch into the FAILED state.
  465. To check for the PAUSED state in the response callback:
  466. void response_callback(const sfetch_response_t* response) {
  467. if (response->paused) {
  468. // we can check here whether the request should
  469. // continue to load data:
  470. if (should_continue(response->handle)) {
  471. sfetch_continue(response->handle);
  472. }
  473. }
  474. }
  475. CHUNK SIZE AND HTTP COMPRESSION
  476. ===============================
  477. TL;DR: for streaming scenarios, the provided chunk-size must be smaller
  478. than the provided buffer-size because the web server may decide to
  479. serve the data compressed and the chunk-size must be given in 'compressed
  480. bytes' while the buffer receives 'uncompressed bytes'. It's not possible
  481. in HTTP to query the uncompressed size for a compressed download until
  482. that download has finished.
  483. With vanilla HTTP, it is not possible to query the actual size of a file
  484. without downloading the entire file first (the Content-Length response
  485. header only provides the compressed size). Furthermore, for HTTP
  486. range-requests, the range is given on the compressed data, not the
  487. uncompressed data. So if the web server decides to serve the data
  488. compressed, the content-length and range-request parameters don't
  489. correspond to the uncompressed data that's arriving in the sokol-fetch
  490. buffers, and there's no way from JS or WASM to either force uncompressed
  491. downloads (e.g. by setting the Accept-Encoding field), or access the
  492. compressed data.
  493. This has some implications for sokol_fetch.h, most notably that buffers
  494. can't be provided in the exactly right size, because that size can't
  495. be queried from HTTP before the data is actually downloaded.
  496. When downloading whole files at once, it is basically expected that you
  497. know the maximum files size upfront through other means (for instance
  498. through a separate meta-data-file which contains the file sizes and
  499. other meta-data for each file that needs to be loaded).
  500. For streaming downloads the situation is a bit more complicated. These
  501. use HTTP range-requests, and those ranges are defined on the (potentially)
  502. compressed data which the JS/WASM side doesn't have access to. However,
  503. the JS/WASM side only ever sees the uncompressed data, and it's not possible
  504. to query the uncompressed size of a range request before that range request
  505. has finished.
  506. If the provided buffer is too small to contain the uncompressed data,
  507. the request will fail with error code SFETCH_ERROR_BUFFER_TOO_SMALL.
  508. CHANNELS AND LANES
  509. ==================
  510. Channels and lanes are (somewhat artificial) concepts to manage
  511. parallelization, prioritization and rate-limiting.
  512. Channels can be used to parallelize message processing for better 'pipeline
  513. throughput', and to prioritize requests: user-code could reserve one
  514. channel for streaming downloads which need to run in parallel to other
  515. requests, another channel for "regular" downloads and yet another
  516. high-priority channel which would only be used for small files which need
  517. to start loading immediately.
  518. Each channel comes with its own IO thread and message queues for pumping
  519. messages in and out of the thread. The channel where a request is
  520. processed is selected manually when sending a message:
  521. sfetch_send(&(sfetch_request_t){
  522. .path = "my_file.txt",
  523. .callback = my_response_callback,
  524. .channel = 2
  525. });
  526. The number of channels is configured at startup in sfetch_setup() and
  527. cannot be changed afterwards.
  528. Channels are completely separate from each other, and a request will
  529. never "hop" from one channel to another.
  530. Each channel consists of a fixed number of "lanes" for automatic rate
  531. limiting:
  532. When a request is sent to a channel via sfetch_send(), a "free lane" will
  533. be picked and assigned to the request. The request will occupy this lane
  534. for its entire life time (also while it is paused). If all lanes of a
  535. channel are currently occupied, new requests will wait until a
  536. lane becomes unoccupied.
  537. Since the number of channels and lanes is known upfront, it is guaranteed
  538. that there will never be more than "num_channels * num_lanes" requests
  539. in flight at any one time.
  540. This guarantee eliminates unexpected load- and memory-spikes when
  541. many requests are sent in very short time, and it allows to pre-allocate
  542. a fixed number of memory buffers which can be reused for the entire
  543. "lifetime" of a sokol-fetch context.
  544. In the most simple scenario - when a maximum file size is known - buffers
  545. can be statically allocated like this:
  546. uint8_t buffer[NUM_CHANNELS][NUM_LANES][MAX_FILE_SIZE];
  547. Then in the user callback pick a buffer by channel and lane,
  548. and associate it with the request like this:
  549. void response_callback(const sfetch_response_t* response) {
  550. if (response->dispatched) {
  551. void* ptr = buffer[response->channel][response->lane];
  552. sfetch_bind_buffer(response->handle, ptr, MAX_FILE_SIZE);
  553. }
  554. ...
  555. }
  556. NOTES ON OPTIMIZING PIPELINE LATENCY AND THROUGHPUT
  557. ===================================================
  558. With the default configuration of 1 channel and 1 lane per channel,
  559. sokol_fetch.h will appear to have a shockingly bad loading performance
  560. if several files are loaded.
  561. This has two reasons:
  562. (1) all parallelization when loading data has been disabled. A new
  563. request will only be processed, when the last request has finished.
  564. (2) every invocation of the response-callback adds one frame of latency
  565. to the request, because callbacks will only be called from within
  566. sfetch_dowork()
  567. sokol-fetch takes a few shortcuts to improve step (2) and reduce
  568. the 'inherent latency' of a request:
  569. - if a buffer is provided upfront, the response-callback won't be
  570. called in the DISPATCHED state, but start right with the FETCHED state
  571. where data has already been loaded into the buffer
  572. - there is no separate CLOSED state where the callback is invoked
  573. separately when loading has finished (or the request has failed),
  574. instead the finished and failed flags will be set as part of
  575. the last FETCHED invocation
  576. This means providing a big-enough buffer to fit the entire file is the
  577. best case, the response callback will only be called once, ideally in
  578. the next frame (or two calls to sfetch_dowork()).
  579. If no buffer is provided upfront, one frame of latency is added because
  580. the response callback needs to be invoked in the DISPATCHED state so that
  581. the user code can bind a buffer.
  582. This means the best case for a request without an upfront-provided
  583. buffer is 2 frames (or 3 calls to sfetch_dowork()).
  584. That's about what can be done to improve the latency for a single request,
  585. but the really important step is to improve overall throughput. If you
  586. need to load thousands of files you don't want that to be completely
  587. serialized.
  588. The most important action to increase throughput is to increase the
  589. number of lanes per channel. This defines how many requests can be
  590. 'in flight' on a single channel at the same time. The guiding decision
  591. factor for how many lanes you can "afford" is the memory size you want
  592. to set aside for buffers. Each lane needs its own buffer so that
  593. the data loaded for one request doesn't scribble over the data
  594. loaded for another request.
  595. Here's a simple example of sending 4 requests without upfront buffer
  596. on a channel with 1, 2 and 4 lanes, each line is one frame:
  597. 1 LANE (8 frames):
  598. Lane 0:
  599. -------------
  600. REQ 0 DISPATCHED
  601. REQ 0 FETCHED
  602. REQ 1 DISPATCHED
  603. REQ 1 FETCHED
  604. REQ 2 DISPATCHED
  605. REQ 2 FETCHED
  606. REQ 3 DISPATCHED
  607. REQ 3 FETCHED
  608. Note how the request don't overlap, so they can all use the same buffer.
  609. 2 LANES (4 frames):
  610. Lane 0: Lane 1:
  611. ------------------------------------
  612. REQ 0 DISPATCHED REQ 1 DISPATCHED
  613. REQ 0 FETCHED REQ 1 FETCHED
  614. REQ 2 DISPATCHED REQ 3 DISPATCHED
  615. REQ 2 FETCHED REQ 3 FETCHED
  616. This reduces the overall time to 4 frames, but now you need 2 buffers so
  617. that requests don't scribble over each other.
  618. 4 LANES (2 frames):
  619. Lane 0: Lane 1: Lane 2: Lane 3:
  620. ----------------------------------------------------------------------------
  621. REQ 0 DISPATCHED REQ 1 DISPATCHED REQ 2 DISPATCHED REQ 3 DISPATCHED
  622. REQ 0 FETCHED REQ 1 FETCHED REQ 2 FETCHED REQ 3 FETCHED
  623. Now we're down to the same 'best-case' latency as sending a single
  624. request.
  625. Apart from the memory requirements for the streaming buffers (which is
  626. under your control), you can be generous with the number of lanes,
  627. they don't add any processing overhead.
  628. The last option for tweaking latency and throughput is channels. Each
  629. channel works independently from other channels, so while one
  630. channel is busy working through a large number of requests (or one
  631. very long streaming download), you can set aside a high-priority channel
  632. for requests that need to start as soon as possible.
  633. On platforms with threading support, each channel runs on its own
  634. thread, but this is mainly an implementation detail to work around
  635. the traditional blocking file IO functions, not for performance reasons.
  636. MEMORY ALLOCATION OVERRIDE
  637. ==========================
  638. You can override the memory allocation functions at initialization time
  639. like this:
  640. void* my_alloc(size_t size, void* user_data) {
  641. return malloc(size);
  642. }
  643. void my_free(void* ptr, void* user_data) {
  644. free(ptr);
  645. }
  646. ...
  647. sfetch_setup(&(sfetch_desc_t){
  648. // ...
  649. .allocator = {
  650. .alloc_fn = my_alloc,
  651. .free_fn = my_free,
  652. .user_data = ...,
  653. }
  654. });
  655. ...
  656. If no overrides are provided, malloc and free will be used.
  657. This only affects memory allocation calls done by sokol_fetch.h
  658. itself though, not any allocations in OS libraries.
  659. Memory allocation will only happen on the same thread where sfetch_setup()
  660. was called, so you don't need to worry about thread-safety.
  661. ERROR REPORTING AND LOGGING
  662. ===========================
  663. To get any logging information at all you need to provide a logging callback in the setup call,
  664. the easiest way is to use sokol_log.h:
  665. #include "sokol_log.h"
  666. sfetch_setup(&(sfetch_desc_t){
  667. // ...
  668. .logger.func = slog_func
  669. });
  670. To override logging with your own callback, first write a logging function like this:
  671. void my_log(const char* tag, // e.g. 'sfetch'
  672. uint32_t log_level, // 0=panic, 1=error, 2=warn, 3=info
  673. uint32_t log_item_id, // SFETCH_LOGITEM_*
  674. const char* message_or_null, // a message string, may be nullptr in release mode
  675. uint32_t line_nr, // line number in sokol_fetch.h
  676. const char* filename_or_null, // source filename, may be nullptr in release mode
  677. void* user_data)
  678. {
  679. ...
  680. }
  681. ...and then setup sokol-fetch like this:
  682. sfetch_setup(&(sfetch_desc_t){
  683. .logger = {
  684. .func = my_log,
  685. .user_data = my_user_data,
  686. }
  687. });
  688. The provided logging function must be reentrant (e.g. be callable from
  689. different threads).
  690. If you don't want to provide your own custom logger it is highly recommended to use
  691. the standard logger in sokol_log.h instead, otherwise you won't see any warnings or
  692. errors.
  693. FUTURE PLANS / V2.0 IDEA DUMP
  694. =============================
  695. - An optional polling API (as alternative to callback API)
  696. - Move buffer-management into the API? The "manual management"
  697. can be quite tricky especially for dynamic allocation scenarios,
  698. API support for buffer management would simplify cases like
  699. preventing that requests scribble over each other's buffers, or
  700. an automatic garbage collection for dynamically allocated buffers,
  701. or automatically falling back to dynamic allocation if static
  702. buffers aren't big enough.
  703. - Pluggable request handlers to load data from other "sources"
  704. (especially HTTP downloads on native platforms via e.g. libcurl
  705. would be useful)
  706. - I'm currently not happy how the user-data block is handled, this
  707. should getting and updating the user-data should be wrapped by
  708. API functions (similar to bind/unbind buffer)
  709. LICENSE
  710. =======
  711. zlib/libpng license
  712. Copyright (c) 2019 Andre Weissflog
  713. This software is provided 'as-is', without any express or implied warranty.
  714. In no event will the authors be held liable for any damages arising from the
  715. use of this software.
  716. Permission is granted to anyone to use this software for any purpose,
  717. including commercial applications, and to alter it and redistribute it
  718. freely, subject to the following restrictions:
  719. 1. The origin of this software must not be misrepresented; you must not
  720. claim that you wrote the original software. If you use this software in a
  721. product, an acknowledgment in the product documentation would be
  722. appreciated but is not required.
  723. 2. Altered source versions must be plainly marked as such, and must not
  724. be misrepresented as being the original software.
  725. 3. This notice may not be removed or altered from any source
  726. distribution.
  727. */
  728. #define SOKOL_FETCH_INCLUDED (1)
  729. #include <stddef.h> // size_t
  730. #include <stdint.h>
  731. #include <stdbool.h>
  732. #if defined(SOKOL_API_DECL) && !defined(SOKOL_FETCH_API_DECL)
  733. #define SOKOL_FETCH_API_DECL SOKOL_API_DECL
  734. #endif
  735. #ifndef SOKOL_FETCH_API_DECL
  736. #if defined(_WIN32) && defined(SOKOL_DLL) && defined(SOKOL_FETCH_IMPL)
  737. #define SOKOL_FETCH_API_DECL __declspec(dllexport)
  738. #elif defined(_WIN32) && defined(SOKOL_DLL)
  739. #define SOKOL_FETCH_API_DECL __declspec(dllimport)
  740. #else
  741. #define SOKOL_FETCH_API_DECL extern
  742. #endif
  743. #endif
  744. #ifdef __cplusplus
  745. extern "C" {
  746. #endif
  747. /*
  748. sfetch_log_item_t
  749. Log items are defined via X-Macros, and expanded to an
  750. enum 'sfetch_log_item', and in debug mode only,
  751. corresponding strings.
  752. Used as parameter in the logging callback.
  753. */
  754. #define _SFETCH_LOG_ITEMS \
  755. _SFETCH_LOGITEM_XMACRO(OK, "Ok") \
  756. _SFETCH_LOGITEM_XMACRO(MALLOC_FAILED, "memory allocation failed") \
  757. _SFETCH_LOGITEM_XMACRO(FILE_PATH_UTF8_DECODING_FAILED, "failed converting file path from UTF8 to wide") \
  758. _SFETCH_LOGITEM_XMACRO(SEND_QUEUE_FULL, "send queue full (adjust via sfetch_desc_t.max_requests)") \
  759. _SFETCH_LOGITEM_XMACRO(REQUEST_CHANNEL_INDEX_TOO_BIG, "channel index too big (adjust via sfetch_desc_t.num_channels)") \
  760. _SFETCH_LOGITEM_XMACRO(REQUEST_PATH_IS_NULL, "file path is nullptr (sfetch_request_t.path)") \
  761. _SFETCH_LOGITEM_XMACRO(REQUEST_PATH_TOO_LONG, "file path is too long (SFETCH_MAX_PATH)") \
  762. _SFETCH_LOGITEM_XMACRO(REQUEST_CALLBACK_MISSING, "no callback provided (sfetch_request_t.callback)") \
  763. _SFETCH_LOGITEM_XMACRO(REQUEST_CHUNK_SIZE_GREATER_BUFFER_SIZE, "chunk size is greater buffer size (sfetch_request_t.chunk_size vs .buffer.size)") \
  764. _SFETCH_LOGITEM_XMACRO(REQUEST_USERDATA_PTR_IS_SET_BUT_USERDATA_SIZE_IS_NULL, "user data ptr is set but user data size is null (sfetch_request_t.user_data.ptr vs .size)") \
  765. _SFETCH_LOGITEM_XMACRO(REQUEST_USERDATA_PTR_IS_NULL_BUT_USERDATA_SIZE_IS_NOT, "user data ptr is null but size is not (sfetch_request_t.user_data.ptr vs .size)") \
  766. _SFETCH_LOGITEM_XMACRO(REQUEST_USERDATA_SIZE_TOO_BIG, "user data size too big (see SFETCH_MAX_USERDATA_UINT64)") \
  767. _SFETCH_LOGITEM_XMACRO(CLAMPING_NUM_CHANNELS_TO_MAX_CHANNELS, "clamping num channels to SFETCH_MAX_CHANNELS") \
  768. _SFETCH_LOGITEM_XMACRO(REQUEST_POOL_EXHAUSTED, "request pool exhausted (tweak via sfetch_desc_t.max_requests)") \
  769. #define _SFETCH_LOGITEM_XMACRO(item,msg) SFETCH_LOGITEM_##item,
  770. typedef enum sfetch_log_item_t {
  771. _SFETCH_LOG_ITEMS
  772. } sfetch_log_item_t;
  773. #undef _SFETCH_LOGITEM_XMACRO
  774. /*
  775. sfetch_logger_t
  776. Used in sfetch_desc_t to provide a custom logging and error reporting
  777. callback to sokol-fetch.
  778. */
  779. typedef struct sfetch_logger_t {
  780. void (*func)(
  781. const char* tag, // always "sfetch"
  782. uint32_t log_level, // 0=panic, 1=error, 2=warning, 3=info
  783. uint32_t log_item_id, // SFETCH_LOGITEM_*
  784. const char* message_or_null, // a message string, may be nullptr in release mode
  785. uint32_t line_nr, // line number in sokol_fetch.h
  786. const char* filename_or_null, // source filename, may be nullptr in release mode
  787. void* user_data);
  788. void* user_data;
  789. } sfetch_logger_t;
  790. /*
  791. sfetch_range_t
  792. A pointer-size pair struct to pass memory ranges into and out of sokol-fetch.
  793. When initialized from a value type (array or struct) you can use the
  794. SFETCH_RANGE() helper macro to build an sfetch_range_t struct.
  795. */
  796. typedef struct sfetch_range_t {
  797. const void* ptr;
  798. size_t size;
  799. } sfetch_range_t;
  800. // disabling this for every includer isn't great, but the warnings are also quite pointless
  801. #if defined(_MSC_VER)
  802. #pragma warning(disable:4221) // /W4 only: nonstandard extension used: 'x': cannot be initialized using address of automatic variable 'y'
  803. #pragma warning(disable:4204) // VS2015: nonstandard extension used: non-constant aggregate initializer
  804. #endif
  805. #if defined(__cplusplus)
  806. #define SFETCH_RANGE(x) sfetch_range_t{ &x, sizeof(x) }
  807. #else
  808. #define SFETCH_RANGE(x) (sfetch_range_t){ &x, sizeof(x) }
  809. #endif
  810. /*
  811. sfetch_allocator_t
  812. Used in sfetch_desc_t to provide custom memory-alloc and -free functions
  813. to sokol_fetch.h. If memory management should be overridden, both the
  814. alloc and free function must be provided (e.g. it's not valid to
  815. override one function but not the other).
  816. */
  817. typedef struct sfetch_allocator_t {
  818. void* (*alloc_fn)(size_t size, void* user_data);
  819. void (*free_fn)(void* ptr, void* user_data);
  820. void* user_data;
  821. } sfetch_allocator_t;
  822. /* configuration values for sfetch_setup() */
  823. typedef struct sfetch_desc_t {
  824. uint32_t max_requests; // max number of active requests across all channels (default: 128)
  825. uint32_t num_channels; // number of channels to fetch requests in parallel (default: 1)
  826. uint32_t num_lanes; // max number of requests active on the same channel (default: 1)
  827. sfetch_allocator_t allocator; // optional memory allocation overrides (default: malloc/free)
  828. sfetch_logger_t logger; // optional log function overrides (default: NO LOGGING!)
  829. } sfetch_desc_t;
  830. /* a request handle to identify an active fetch request, returned by sfetch_send() */
  831. typedef struct sfetch_handle_t { uint32_t id; } sfetch_handle_t;
  832. /* error codes */
  833. typedef enum sfetch_error_t {
  834. SFETCH_ERROR_NO_ERROR,
  835. SFETCH_ERROR_FILE_NOT_FOUND,
  836. SFETCH_ERROR_NO_BUFFER,
  837. SFETCH_ERROR_BUFFER_TOO_SMALL,
  838. SFETCH_ERROR_UNEXPECTED_EOF,
  839. SFETCH_ERROR_INVALID_HTTP_STATUS,
  840. SFETCH_ERROR_CANCELLED,
  841. SFETCH_ERROR_JS_OTHER, // check browser console for detailed error info
  842. } sfetch_error_t;
  843. /* the response struct passed to the response callback */
  844. typedef struct sfetch_response_t {
  845. sfetch_handle_t handle; // request handle this response belongs to
  846. bool dispatched; // true when request is in DISPATCHED state (lane has been assigned)
  847. bool fetched; // true when request is in FETCHED state (fetched data is available)
  848. bool paused; // request is currently in paused state
  849. bool finished; // this is the last response for this request
  850. bool failed; // request has failed (always set together with 'finished')
  851. bool cancelled; // request was cancelled (always set together with 'finished')
  852. sfetch_error_t error_code; // more detailed error code when failed is true
  853. uint32_t channel; // the channel which processes this request
  854. uint32_t lane; // the lane this request occupies on its channel
  855. const char* path; // the original filesystem path of the request
  856. void* user_data; // pointer to read/write user-data area
  857. uint32_t data_offset; // current offset of fetched data chunk in the overall file data
  858. sfetch_range_t data; // the fetched data as ptr/size pair (data.ptr == buffer.ptr, data.size <= buffer.size)
  859. sfetch_range_t buffer; // the user-provided buffer which holds the fetched data
  860. } sfetch_response_t;
  861. /* request parameters passed to sfetch_send() */
  862. typedef struct sfetch_request_t {
  863. uint32_t channel; // index of channel this request is assigned to (default: 0)
  864. const char* path; // filesystem path or HTTP URL (required)
  865. void (*callback) (const sfetch_response_t*); // response callback function pointer (required)
  866. uint32_t chunk_size; // number of bytes to load per stream-block (optional)
  867. sfetch_range_t buffer; // a memory buffer where the data will be loaded into (optional)
  868. sfetch_range_t user_data; // ptr/size of a POD user data block which will be memcpy'd (optional)
  869. } sfetch_request_t;
  870. /* setup sokol-fetch (can be called on multiple threads) */
  871. SOKOL_FETCH_API_DECL void sfetch_setup(const sfetch_desc_t* desc);
  872. /* discard a sokol-fetch context */
  873. SOKOL_FETCH_API_DECL void sfetch_shutdown(void);
  874. /* return true if sokol-fetch has been setup */
  875. SOKOL_FETCH_API_DECL bool sfetch_valid(void);
  876. /* get the desc struct that was passed to sfetch_setup() */
  877. SOKOL_FETCH_API_DECL sfetch_desc_t sfetch_desc(void);
  878. /* return the max userdata size in number of bytes (SFETCH_MAX_USERDATA_UINT64 * sizeof(uint64_t)) */
  879. SOKOL_FETCH_API_DECL int sfetch_max_userdata_bytes(void);
  880. /* return the value of the SFETCH_MAX_PATH implementation config value */
  881. SOKOL_FETCH_API_DECL int sfetch_max_path(void);
  882. /* send a fetch-request, get handle to request back */
  883. SOKOL_FETCH_API_DECL sfetch_handle_t sfetch_send(const sfetch_request_t* request);
  884. /* return true if a handle is valid *and* the request is alive */
  885. SOKOL_FETCH_API_DECL bool sfetch_handle_valid(sfetch_handle_t h);
  886. /* do per-frame work, moves requests into and out of IO threads, and invokes response-callbacks */
  887. SOKOL_FETCH_API_DECL void sfetch_dowork(void);
  888. /* bind a data buffer to a request (request must not currently have a buffer bound, must be called from response callback */
  889. SOKOL_FETCH_API_DECL void sfetch_bind_buffer(sfetch_handle_t h, sfetch_range_t buffer);
  890. /* clear the 'buffer binding' of a request, returns previous buffer pointer (can be 0), must be called from response callback */
  891. SOKOL_FETCH_API_DECL void* sfetch_unbind_buffer(sfetch_handle_t h);
  892. /* cancel a request that's in flight (will call response callback with .cancelled + .finished) */
  893. SOKOL_FETCH_API_DECL void sfetch_cancel(sfetch_handle_t h);
  894. /* pause a request (will call response callback each frame with .paused) */
  895. SOKOL_FETCH_API_DECL void sfetch_pause(sfetch_handle_t h);
  896. /* continue a paused request */
  897. SOKOL_FETCH_API_DECL void sfetch_continue(sfetch_handle_t h);
  898. #ifdef __cplusplus
  899. } /* extern "C" */
  900. /* reference-based equivalents for c++ */
  901. inline void sfetch_setup(const sfetch_desc_t& desc) { return sfetch_setup(&desc); }
  902. inline sfetch_handle_t sfetch_send(const sfetch_request_t& request) { return sfetch_send(&request); }
  903. #endif
  904. #endif // SOKOL_FETCH_INCLUDED
  905. // ██ ███ ███ ██████ ██ ███████ ███ ███ ███████ ███ ██ ████████ █████ ████████ ██ ██████ ███ ██
  906. // ██ ████ ████ ██ ██ ██ ██ ████ ████ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██
  907. // ██ ██ ████ ██ ██████ ██ █████ ██ ████ ██ █████ ██ ██ ██ ██ ███████ ██ ██ ██ ██ ██ ██ ██
  908. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  909. // ██ ██ ██ ██ ███████ ███████ ██ ██ ███████ ██ ████ ██ ██ ██ ██ ██ ██████ ██ ████
  910. //
  911. // >>implementation
  912. #ifdef SOKOL_FETCH_IMPL
  913. #define SOKOL_FETCH_IMPL_INCLUDED (1)
  914. #if defined(SOKOL_MALLOC) || defined(SOKOL_CALLOC) || defined(SOKOL_FREE)
  915. #error "SOKOL_MALLOC/CALLOC/FREE macros are no longer supported, please use sfetch_desc_t.allocator to override memory allocation functions"
  916. #endif
  917. #include <stdlib.h> /* malloc, free */
  918. #include <string.h> /* memset, memcpy */
  919. #ifndef SFETCH_MAX_PATH
  920. #define SFETCH_MAX_PATH (1024)
  921. #endif
  922. #ifndef SFETCH_MAX_USERDATA_UINT64
  923. #define SFETCH_MAX_USERDATA_UINT64 (16)
  924. #endif
  925. #ifndef SFETCH_MAX_CHANNELS
  926. #define SFETCH_MAX_CHANNELS (16)
  927. #endif
  928. #ifndef SOKOL_API_IMPL
  929. #define SOKOL_API_IMPL
  930. #endif
  931. #ifndef SOKOL_DEBUG
  932. #ifndef NDEBUG
  933. #define SOKOL_DEBUG
  934. #endif
  935. #endif
  936. #ifndef SOKOL_ASSERT
  937. #include <assert.h>
  938. #define SOKOL_ASSERT(c) assert(c)
  939. #endif
  940. #ifndef _SOKOL_PRIVATE
  941. #if defined(__GNUC__) || defined(__clang__)
  942. #define _SOKOL_PRIVATE __attribute__((unused)) static
  943. #else
  944. #define _SOKOL_PRIVATE static
  945. #endif
  946. #endif
  947. #ifndef _SOKOL_UNUSED
  948. #define _SOKOL_UNUSED(x) (void)(x)
  949. #endif
  950. #if defined(__EMSCRIPTEN__)
  951. #include <emscripten/emscripten.h>
  952. #define _SFETCH_PLATFORM_EMSCRIPTEN (1)
  953. #define _SFETCH_PLATFORM_WINDOWS (0)
  954. #define _SFETCH_PLATFORM_POSIX (0)
  955. #define _SFETCH_HAS_THREADS (0)
  956. #elif defined(_WIN32)
  957. #ifndef WIN32_LEAN_AND_MEAN
  958. #define WIN32_LEAN_AND_MEAN
  959. #endif
  960. #ifndef NOMINMAX
  961. #define NOMINMAX
  962. #endif
  963. #include <windows.h>
  964. #define _SFETCH_PLATFORM_WINDOWS (1)
  965. #define _SFETCH_PLATFORM_EMSCRIPTEN (0)
  966. #define _SFETCH_PLATFORM_POSIX (0)
  967. #define _SFETCH_HAS_THREADS (1)
  968. #else
  969. #include <pthread.h>
  970. #include <stdio.h> /* fopen, fread, fseek, fclose */
  971. #define _SFETCH_PLATFORM_POSIX (1)
  972. #define _SFETCH_PLATFORM_EMSCRIPTEN (0)
  973. #define _SFETCH_PLATFORM_WINDOWS (0)
  974. #define _SFETCH_HAS_THREADS (1)
  975. #endif
  976. #ifdef _MSC_VER
  977. #pragma warning(push)
  978. #pragma warning(disable:4724) // potential mod by 0
  979. #endif
  980. // ███████ ████████ ██████ ██ ██ ██████ ████████ ███████
  981. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  982. // ███████ ██ ██████ ██ ██ ██ ██ ███████
  983. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  984. // ███████ ██ ██ ██ ██████ ██████ ██ ███████
  985. //
  986. // >>structs
  987. typedef struct _sfetch_path_t {
  988. char buf[SFETCH_MAX_PATH];
  989. } _sfetch_path_t;
  990. /* a thread with incoming and outgoing message queue syncing */
  991. #if _SFETCH_PLATFORM_POSIX
  992. typedef struct {
  993. pthread_t thread;
  994. pthread_cond_t incoming_cond;
  995. pthread_mutex_t incoming_mutex;
  996. pthread_mutex_t outgoing_mutex;
  997. pthread_mutex_t running_mutex;
  998. pthread_mutex_t stop_mutex;
  999. bool stop_requested;
  1000. bool valid;
  1001. } _sfetch_thread_t;
  1002. #elif _SFETCH_PLATFORM_WINDOWS
  1003. typedef struct {
  1004. HANDLE thread;
  1005. HANDLE incoming_event;
  1006. CRITICAL_SECTION incoming_critsec;
  1007. CRITICAL_SECTION outgoing_critsec;
  1008. CRITICAL_SECTION running_critsec;
  1009. CRITICAL_SECTION stop_critsec;
  1010. bool stop_requested;
  1011. bool valid;
  1012. } _sfetch_thread_t;
  1013. #endif
  1014. /* file handle abstraction */
  1015. #if _SFETCH_PLATFORM_POSIX
  1016. typedef FILE* _sfetch_file_handle_t;
  1017. #define _SFETCH_INVALID_FILE_HANDLE (0)
  1018. typedef void*(*_sfetch_thread_func_t)(void*);
  1019. #elif _SFETCH_PLATFORM_WINDOWS
  1020. typedef HANDLE _sfetch_file_handle_t;
  1021. #define _SFETCH_INVALID_FILE_HANDLE (INVALID_HANDLE_VALUE)
  1022. typedef LPTHREAD_START_ROUTINE _sfetch_thread_func_t;
  1023. #endif
  1024. /* user-side per-request state */
  1025. typedef struct {
  1026. bool pause; /* switch item to PAUSED state if true */
  1027. bool cont; /* switch item back to FETCHING if true */
  1028. bool cancel; /* cancel the request, switch into FAILED state */
  1029. /* transfer IO => user thread */
  1030. uint32_t fetched_offset; /* number of bytes fetched so far */
  1031. uint32_t fetched_size; /* size of last fetched chunk */
  1032. sfetch_error_t error_code;
  1033. bool finished;
  1034. /* user thread only */
  1035. size_t user_data_size;
  1036. uint64_t user_data[SFETCH_MAX_USERDATA_UINT64];
  1037. } _sfetch_item_user_t;
  1038. /* thread-side per-request state */
  1039. typedef struct {
  1040. /* transfer IO => user thread */
  1041. uint32_t fetched_offset;
  1042. uint32_t fetched_size;
  1043. sfetch_error_t error_code;
  1044. bool failed;
  1045. bool finished;
  1046. /* IO thread only */
  1047. #if _SFETCH_PLATFORM_EMSCRIPTEN
  1048. uint32_t http_range_offset;
  1049. #else
  1050. _sfetch_file_handle_t file_handle;
  1051. #endif
  1052. uint32_t content_size;
  1053. } _sfetch_item_thread_t;
  1054. /* a request goes through the following states, ping-ponging between IO and user thread */
  1055. typedef enum _sfetch_state_t {
  1056. _SFETCH_STATE_INITIAL, /* internal: request has just been initialized */
  1057. _SFETCH_STATE_ALLOCATED, /* internal: request has been allocated from internal pool */
  1058. _SFETCH_STATE_DISPATCHED, /* user thread: request has been dispatched to its IO channel */
  1059. _SFETCH_STATE_FETCHING, /* IO thread: waiting for data to be fetched */
  1060. _SFETCH_STATE_FETCHED, /* user thread: fetched data available */
  1061. _SFETCH_STATE_PAUSED, /* user thread: request has been paused via sfetch_pause() */
  1062. _SFETCH_STATE_FAILED, /* user thread: follow state or FETCHING if something went wrong */
  1063. } _sfetch_state_t;
  1064. /* an internal request item */
  1065. #define _SFETCH_INVALID_LANE (0xFFFFFFFF)
  1066. typedef struct {
  1067. sfetch_handle_t handle;
  1068. _sfetch_state_t state;
  1069. uint32_t channel;
  1070. uint32_t lane;
  1071. uint32_t chunk_size;
  1072. void (*callback) (const sfetch_response_t*);
  1073. sfetch_range_t buffer;
  1074. /* updated by IO-thread, off-limits to user thread */
  1075. _sfetch_item_thread_t thread;
  1076. /* accessible by user-thread, off-limits to IO thread */
  1077. _sfetch_item_user_t user;
  1078. /* big stuff at the end */
  1079. _sfetch_path_t path;
  1080. } _sfetch_item_t;
  1081. /* a pool of internal per-request items */
  1082. typedef struct {
  1083. uint32_t size;
  1084. uint32_t free_top;
  1085. _sfetch_item_t* items;
  1086. uint32_t* free_slots;
  1087. uint32_t* gen_ctrs;
  1088. bool valid;
  1089. } _sfetch_pool_t;
  1090. /* a ringbuffer for pool-slot ids */
  1091. typedef struct {
  1092. uint32_t head;
  1093. uint32_t tail;
  1094. uint32_t num;
  1095. uint32_t* buf;
  1096. } _sfetch_ring_t;
  1097. /* an IO channel with its own IO thread */
  1098. struct _sfetch_t;
  1099. typedef struct {
  1100. struct _sfetch_t* ctx; // back-pointer to thread-local _sfetch state pointer, since this isn't accessible from the IO threads
  1101. _sfetch_ring_t free_lanes;
  1102. _sfetch_ring_t user_sent;
  1103. _sfetch_ring_t user_incoming;
  1104. _sfetch_ring_t user_outgoing;
  1105. #if _SFETCH_HAS_THREADS
  1106. _sfetch_ring_t thread_incoming;
  1107. _sfetch_ring_t thread_outgoing;
  1108. _sfetch_thread_t thread;
  1109. #endif
  1110. void (*request_handler)(struct _sfetch_t* ctx, uint32_t slot_id);
  1111. bool valid;
  1112. } _sfetch_channel_t;
  1113. /* the sfetch global state */
  1114. typedef struct _sfetch_t {
  1115. bool setup;
  1116. bool valid;
  1117. bool in_callback;
  1118. sfetch_desc_t desc;
  1119. _sfetch_pool_t pool;
  1120. _sfetch_channel_t chn[SFETCH_MAX_CHANNELS];
  1121. } _sfetch_t;
  1122. #if _SFETCH_HAS_THREADS
  1123. #if defined(_MSC_VER)
  1124. static __declspec(thread) _sfetch_t* _sfetch;
  1125. #else
  1126. static __thread _sfetch_t* _sfetch;
  1127. #endif
  1128. #else
  1129. static _sfetch_t* _sfetch;
  1130. #endif
  1131. #define _sfetch_def(val, def) (((val) == 0) ? (def) : (val))
  1132. // ██ ██████ ██████ ██████ ██ ███ ██ ██████
  1133. // ██ ██ ██ ██ ██ ██ ████ ██ ██
  1134. // ██ ██ ██ ██ ███ ██ ███ ██ ██ ██ ██ ██ ███
  1135. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1136. // ███████ ██████ ██████ ██████ ██ ██ ████ ██████
  1137. //
  1138. // >>logging
  1139. #if defined(SOKOL_DEBUG)
  1140. #define _SFETCH_LOGITEM_XMACRO(item,msg) #item ": " msg,
  1141. static const char* _sfetch_log_messages[] = {
  1142. _SFETCH_LOG_ITEMS
  1143. };
  1144. #undef _SFETCH_LOGITEM_XMACRO
  1145. #endif // SOKOL_DEBUG
  1146. #define _SFETCH_PANIC(code) _sfetch_log(SFETCH_LOGITEM_ ##code, 0, __LINE__)
  1147. #define _SFETCH_ERROR(code) _sfetch_log(SFETCH_LOGITEM_ ##code, 1, __LINE__)
  1148. #define _SFETCH_WARN(code) _sfetch_log(SFETCH_LOGITEM_ ##code, 2, __LINE__)
  1149. #define _SFETCH_INFO(code) _sfetch_log(SFETCH_LOGITEM_ ##code, 3, __LINE__)
  1150. static void _sfetch_log(sfetch_log_item_t log_item, uint32_t log_level, uint32_t line_nr) {
  1151. if (_sfetch->desc.logger.func) {
  1152. #if defined(SOKOL_DEBUG)
  1153. const char* filename = __FILE__;
  1154. const char* message = _sfetch_log_messages[log_item];
  1155. #else
  1156. const char* filename = 0;
  1157. const char* message = 0;
  1158. #endif
  1159. _sfetch->desc.logger.func("sfetch", log_level, (uint32_t)log_item, message, line_nr, filename, _sfetch->desc.logger.user_data);
  1160. } else {
  1161. // for log level PANIC it would be 'undefined behaviour' to continue
  1162. if (log_level == 0) {
  1163. abort();
  1164. }
  1165. }
  1166. }
  1167. // ███ ███ ███████ ███ ███ ██████ ██████ ██ ██
  1168. // ████ ████ ██ ████ ████ ██ ██ ██ ██ ██ ██
  1169. // ██ ████ ██ █████ ██ ████ ██ ██ ██ ██████ ████
  1170. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1171. // ██ ██ ███████ ██ ██ ██████ ██ ██ ██
  1172. //
  1173. // >>memory
  1174. _SOKOL_PRIVATE void _sfetch_clear(void* ptr, size_t size) {
  1175. SOKOL_ASSERT(ptr && (size > 0));
  1176. memset(ptr, 0, size);
  1177. }
  1178. _SOKOL_PRIVATE void* _sfetch_malloc_with_allocator(const sfetch_allocator_t* allocator, size_t size) {
  1179. SOKOL_ASSERT(size > 0);
  1180. void* ptr;
  1181. if (allocator->alloc_fn) {
  1182. ptr = allocator->alloc_fn(size, allocator->user_data);
  1183. } else {
  1184. ptr = malloc(size);
  1185. }
  1186. if (0 == ptr) {
  1187. _SFETCH_PANIC(MALLOC_FAILED);
  1188. }
  1189. return ptr;
  1190. }
  1191. _SOKOL_PRIVATE void* _sfetch_malloc(size_t size) {
  1192. return _sfetch_malloc_with_allocator(&_sfetch->desc.allocator, size);
  1193. }
  1194. _SOKOL_PRIVATE void* _sfetch_malloc_clear(size_t size) {
  1195. void* ptr = _sfetch_malloc(size);
  1196. _sfetch_clear(ptr, size);
  1197. return ptr;
  1198. }
  1199. _SOKOL_PRIVATE void _sfetch_free(void* ptr) {
  1200. if (_sfetch->desc.allocator.free_fn) {
  1201. _sfetch->desc.allocator.free_fn(ptr, _sfetch->desc.allocator.user_data);
  1202. } else {
  1203. free(ptr);
  1204. }
  1205. }
  1206. _SOKOL_PRIVATE _sfetch_t* _sfetch_ctx(void) {
  1207. return _sfetch;
  1208. }
  1209. _SOKOL_PRIVATE void _sfetch_path_copy(_sfetch_path_t* dst, const char* src) {
  1210. SOKOL_ASSERT(dst);
  1211. if (src && (strlen(src) < SFETCH_MAX_PATH)) {
  1212. #if defined(_MSC_VER)
  1213. strncpy_s(dst->buf, SFETCH_MAX_PATH, src, (SFETCH_MAX_PATH-1));
  1214. #else
  1215. strncpy(dst->buf, src, SFETCH_MAX_PATH);
  1216. #endif
  1217. dst->buf[SFETCH_MAX_PATH-1] = 0;
  1218. } else {
  1219. _sfetch_clear(dst->buf, SFETCH_MAX_PATH);
  1220. }
  1221. }
  1222. _SOKOL_PRIVATE _sfetch_path_t _sfetch_path_make(const char* str) {
  1223. _sfetch_path_t res;
  1224. _sfetch_path_copy(&res, str);
  1225. return res;
  1226. }
  1227. // ███ ███ ███████ ███████ ███████ █████ ██████ ███████ ██████ ██ ██ ███████ ██ ██ ███████
  1228. // ████ ████ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1229. // ██ ████ ██ █████ ███████ ███████ ███████ ██ ███ █████ ██ ██ ██ ██ █████ ██ ██ █████
  1230. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ▄▄ ██ ██ ██ ██ ██ ██ ██
  1231. // ██ ██ ███████ ███████ ███████ ██ ██ ██████ ███████ ██████ ██████ ███████ ██████ ███████
  1232. // ▀▀
  1233. // >>message queue
  1234. _SOKOL_PRIVATE uint32_t _sfetch_ring_wrap(const _sfetch_ring_t* rb, uint32_t i) {
  1235. return i % rb->num;
  1236. }
  1237. _SOKOL_PRIVATE void _sfetch_ring_discard(_sfetch_ring_t* rb) {
  1238. SOKOL_ASSERT(rb);
  1239. if (rb->buf) {
  1240. _sfetch_free(rb->buf);
  1241. rb->buf = 0;
  1242. }
  1243. rb->head = 0;
  1244. rb->tail = 0;
  1245. rb->num = 0;
  1246. }
  1247. _SOKOL_PRIVATE bool _sfetch_ring_init(_sfetch_ring_t* rb, uint32_t num_slots) {
  1248. SOKOL_ASSERT(rb && (num_slots > 0));
  1249. SOKOL_ASSERT(0 == rb->buf);
  1250. rb->head = 0;
  1251. rb->tail = 0;
  1252. /* one slot reserved to detect full vs empty */
  1253. rb->num = num_slots + 1;
  1254. const size_t queue_size = rb->num * sizeof(sfetch_handle_t);
  1255. rb->buf = (uint32_t*) _sfetch_malloc_clear(queue_size);
  1256. if (rb->buf) {
  1257. return true;
  1258. } else {
  1259. _sfetch_ring_discard(rb);
  1260. return false;
  1261. }
  1262. }
  1263. _SOKOL_PRIVATE bool _sfetch_ring_full(const _sfetch_ring_t* rb) {
  1264. SOKOL_ASSERT(rb && rb->buf);
  1265. return _sfetch_ring_wrap(rb, rb->head + 1) == rb->tail;
  1266. }
  1267. _SOKOL_PRIVATE bool _sfetch_ring_empty(const _sfetch_ring_t* rb) {
  1268. SOKOL_ASSERT(rb && rb->buf);
  1269. return rb->head == rb->tail;
  1270. }
  1271. _SOKOL_PRIVATE uint32_t _sfetch_ring_count(const _sfetch_ring_t* rb) {
  1272. SOKOL_ASSERT(rb && rb->buf);
  1273. uint32_t count;
  1274. if (rb->head >= rb->tail) {
  1275. count = rb->head - rb->tail;
  1276. } else {
  1277. count = (rb->head + rb->num) - rb->tail;
  1278. }
  1279. SOKOL_ASSERT(count < rb->num);
  1280. return count;
  1281. }
  1282. _SOKOL_PRIVATE void _sfetch_ring_enqueue(_sfetch_ring_t* rb, uint32_t slot_id) {
  1283. SOKOL_ASSERT(rb && rb->buf);
  1284. SOKOL_ASSERT(!_sfetch_ring_full(rb));
  1285. SOKOL_ASSERT(rb->head < rb->num);
  1286. rb->buf[rb->head] = slot_id;
  1287. rb->head = _sfetch_ring_wrap(rb, rb->head + 1);
  1288. }
  1289. _SOKOL_PRIVATE uint32_t _sfetch_ring_dequeue(_sfetch_ring_t* rb) {
  1290. SOKOL_ASSERT(rb && rb->buf);
  1291. SOKOL_ASSERT(!_sfetch_ring_empty(rb));
  1292. SOKOL_ASSERT(rb->tail < rb->num);
  1293. uint32_t slot_id = rb->buf[rb->tail];
  1294. rb->tail = _sfetch_ring_wrap(rb, rb->tail + 1);
  1295. return slot_id;
  1296. }
  1297. _SOKOL_PRIVATE uint32_t _sfetch_ring_peek(const _sfetch_ring_t* rb, uint32_t index) {
  1298. SOKOL_ASSERT(rb && rb->buf);
  1299. SOKOL_ASSERT(!_sfetch_ring_empty(rb));
  1300. SOKOL_ASSERT(index < _sfetch_ring_count(rb));
  1301. uint32_t rb_index = _sfetch_ring_wrap(rb, rb->tail + index);
  1302. return rb->buf[rb_index];
  1303. }
  1304. // ██████ ███████ ██████ ██ ██ ███████ ███████ ████████ ██████ ██████ ██████ ██
  1305. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1306. // ██████ █████ ██ ██ ██ ██ █████ ███████ ██ ██████ ██ ██ ██ ██ ██
  1307. // ██ ██ ██ ██ ▄▄ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1308. // ██ ██ ███████ ██████ ██████ ███████ ███████ ██ ██ ██████ ██████ ███████
  1309. // ▀▀
  1310. // >>request pool
  1311. _SOKOL_PRIVATE uint32_t _sfetch_make_id(uint32_t index, uint32_t gen_ctr) {
  1312. return (gen_ctr<<16) | (index & 0xFFFF);
  1313. }
  1314. _SOKOL_PRIVATE sfetch_handle_t _sfetch_make_handle(uint32_t slot_id) {
  1315. sfetch_handle_t h;
  1316. h.id = slot_id;
  1317. return h;
  1318. }
  1319. _SOKOL_PRIVATE uint32_t _sfetch_slot_index(uint32_t slot_id) {
  1320. return slot_id & 0xFFFF;
  1321. }
  1322. _SOKOL_PRIVATE void _sfetch_item_init(_sfetch_item_t* item, uint32_t slot_id, const sfetch_request_t* request) {
  1323. SOKOL_ASSERT(item && (0 == item->handle.id));
  1324. SOKOL_ASSERT(request && request->path);
  1325. _sfetch_clear(item, sizeof(_sfetch_item_t));
  1326. item->handle.id = slot_id;
  1327. item->state = _SFETCH_STATE_INITIAL;
  1328. item->channel = request->channel;
  1329. item->chunk_size = request->chunk_size;
  1330. item->lane = _SFETCH_INVALID_LANE;
  1331. item->callback = request->callback;
  1332. item->buffer = request->buffer;
  1333. item->path = _sfetch_path_make(request->path);
  1334. #if !_SFETCH_PLATFORM_EMSCRIPTEN
  1335. item->thread.file_handle = _SFETCH_INVALID_FILE_HANDLE;
  1336. #endif
  1337. if (request->user_data.ptr &&
  1338. (request->user_data.size > 0) &&
  1339. (request->user_data.size <= (SFETCH_MAX_USERDATA_UINT64*8)))
  1340. {
  1341. item->user.user_data_size = request->user_data.size;
  1342. memcpy(item->user.user_data, request->user_data.ptr, request->user_data.size);
  1343. }
  1344. }
  1345. _SOKOL_PRIVATE void _sfetch_item_discard(_sfetch_item_t* item) {
  1346. SOKOL_ASSERT(item && (0 != item->handle.id));
  1347. _sfetch_clear(item, sizeof(_sfetch_item_t));
  1348. }
  1349. _SOKOL_PRIVATE void _sfetch_pool_discard(_sfetch_pool_t* pool) {
  1350. SOKOL_ASSERT(pool);
  1351. if (pool->free_slots) {
  1352. _sfetch_free(pool->free_slots);
  1353. pool->free_slots = 0;
  1354. }
  1355. if (pool->gen_ctrs) {
  1356. _sfetch_free(pool->gen_ctrs);
  1357. pool->gen_ctrs = 0;
  1358. }
  1359. if (pool->items) {
  1360. _sfetch_free(pool->items);
  1361. pool->items = 0;
  1362. }
  1363. pool->size = 0;
  1364. pool->free_top = 0;
  1365. pool->valid = false;
  1366. }
  1367. _SOKOL_PRIVATE bool _sfetch_pool_init(_sfetch_pool_t* pool, uint32_t num_items) {
  1368. SOKOL_ASSERT(pool && (num_items > 0) && (num_items < ((1<<16)-1)));
  1369. SOKOL_ASSERT(0 == pool->items);
  1370. /* NOTE: item slot 0 is reserved for the special "invalid" item index 0*/
  1371. pool->size = num_items + 1;
  1372. pool->free_top = 0;
  1373. const size_t items_size = pool->size * sizeof(_sfetch_item_t);
  1374. pool->items = (_sfetch_item_t*) _sfetch_malloc_clear(items_size);
  1375. /* generation counters indexable by pool slot index, slot 0 is reserved */
  1376. const size_t gen_ctrs_size = sizeof(uint32_t) * pool->size;
  1377. pool->gen_ctrs = (uint32_t*) _sfetch_malloc_clear(gen_ctrs_size);
  1378. SOKOL_ASSERT(pool->gen_ctrs);
  1379. /* NOTE: it's not a bug to only reserve num_items here */
  1380. const size_t free_slots_size = num_items * sizeof(int);
  1381. pool->free_slots = (uint32_t*) _sfetch_malloc_clear(free_slots_size);
  1382. if (pool->items && pool->free_slots) {
  1383. /* never allocate the 0-th item, this is the reserved 'invalid item' */
  1384. for (uint32_t i = pool->size - 1; i >= 1; i--) {
  1385. pool->free_slots[pool->free_top++] = i;
  1386. }
  1387. pool->valid = true;
  1388. } else {
  1389. /* allocation error */
  1390. _sfetch_pool_discard(pool);
  1391. }
  1392. return pool->valid;
  1393. }
  1394. _SOKOL_PRIVATE uint32_t _sfetch_pool_item_alloc(_sfetch_pool_t* pool, const sfetch_request_t* request) {
  1395. SOKOL_ASSERT(pool && pool->valid);
  1396. if (pool->free_top > 0) {
  1397. uint32_t slot_index = pool->free_slots[--pool->free_top];
  1398. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  1399. uint32_t slot_id = _sfetch_make_id(slot_index, ++pool->gen_ctrs[slot_index]);
  1400. _sfetch_item_init(&pool->items[slot_index], slot_id, request);
  1401. pool->items[slot_index].state = _SFETCH_STATE_ALLOCATED;
  1402. return slot_id;
  1403. } else {
  1404. /* pool exhausted, return the 'invalid handle' */
  1405. return _sfetch_make_id(0, 0);
  1406. }
  1407. }
  1408. _SOKOL_PRIVATE void _sfetch_pool_item_free(_sfetch_pool_t* pool, uint32_t slot_id) {
  1409. SOKOL_ASSERT(pool && pool->valid);
  1410. uint32_t slot_index = _sfetch_slot_index(slot_id);
  1411. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  1412. SOKOL_ASSERT(pool->items[slot_index].handle.id == slot_id);
  1413. #if defined(SOKOL_DEBUG)
  1414. /* debug check against double-free */
  1415. for (uint32_t i = 0; i < pool->free_top; i++) {
  1416. SOKOL_ASSERT(pool->free_slots[i] != slot_index);
  1417. }
  1418. #endif
  1419. _sfetch_item_discard(&pool->items[slot_index]);
  1420. pool->free_slots[pool->free_top++] = slot_index;
  1421. SOKOL_ASSERT(pool->free_top <= (pool->size - 1));
  1422. }
  1423. /* return pointer to item by handle without matching id check */
  1424. _SOKOL_PRIVATE _sfetch_item_t* _sfetch_pool_item_at(_sfetch_pool_t* pool, uint32_t slot_id) {
  1425. SOKOL_ASSERT(pool && pool->valid);
  1426. uint32_t slot_index = _sfetch_slot_index(slot_id);
  1427. SOKOL_ASSERT((slot_index > 0) && (slot_index < pool->size));
  1428. return &pool->items[slot_index];
  1429. }
  1430. /* return pointer to item by handle with matching id check */
  1431. _SOKOL_PRIVATE _sfetch_item_t* _sfetch_pool_item_lookup(_sfetch_pool_t* pool, uint32_t slot_id) {
  1432. SOKOL_ASSERT(pool && pool->valid);
  1433. if (0 != slot_id) {
  1434. _sfetch_item_t* item = _sfetch_pool_item_at(pool, slot_id);
  1435. if (item->handle.id == slot_id) {
  1436. return item;
  1437. }
  1438. }
  1439. return 0;
  1440. }
  1441. // ██████ ██████ ███████ ██ ██ ██
  1442. // ██ ██ ██ ██ ██ ██ ██ ██
  1443. // ██████ ██ ██ ███████ ██ ███
  1444. // ██ ██ ██ ██ ██ ██ ██
  1445. // ██ ██████ ███████ ██ ██ ██
  1446. //
  1447. // >>posix
  1448. #if _SFETCH_PLATFORM_POSIX
  1449. _SOKOL_PRIVATE _sfetch_file_handle_t _sfetch_file_open(const _sfetch_path_t* path) {
  1450. return fopen(path->buf, "rb");
  1451. }
  1452. _SOKOL_PRIVATE void _sfetch_file_close(_sfetch_file_handle_t h) {
  1453. fclose(h);
  1454. }
  1455. _SOKOL_PRIVATE bool _sfetch_file_handle_valid(_sfetch_file_handle_t h) {
  1456. return h != _SFETCH_INVALID_FILE_HANDLE;
  1457. }
  1458. _SOKOL_PRIVATE uint32_t _sfetch_file_size(_sfetch_file_handle_t h) {
  1459. fseek(h, 0, SEEK_END);
  1460. return (uint32_t) ftell(h);
  1461. }
  1462. _SOKOL_PRIVATE bool _sfetch_file_read(_sfetch_file_handle_t h, uint32_t offset, uint32_t num_bytes, void* ptr) {
  1463. fseek(h, (long)offset, SEEK_SET);
  1464. return num_bytes == fread(ptr, 1, num_bytes, h);
  1465. }
  1466. _SOKOL_PRIVATE bool _sfetch_thread_init(_sfetch_thread_t* thread, _sfetch_thread_func_t thread_func, void* thread_arg) {
  1467. SOKOL_ASSERT(thread && !thread->valid && !thread->stop_requested);
  1468. pthread_mutexattr_t attr;
  1469. pthread_mutexattr_init(&attr);
  1470. pthread_mutex_init(&thread->incoming_mutex, &attr);
  1471. pthread_mutexattr_destroy(&attr);
  1472. pthread_mutexattr_init(&attr);
  1473. pthread_mutex_init(&thread->outgoing_mutex, &attr);
  1474. pthread_mutexattr_destroy(&attr);
  1475. pthread_mutexattr_init(&attr);
  1476. pthread_mutex_init(&thread->running_mutex, &attr);
  1477. pthread_mutexattr_destroy(&attr);
  1478. pthread_mutexattr_init(&attr);
  1479. pthread_mutex_init(&thread->stop_mutex, &attr);
  1480. pthread_mutexattr_destroy(&attr);
  1481. pthread_condattr_t cond_attr;
  1482. pthread_condattr_init(&cond_attr);
  1483. pthread_cond_init(&thread->incoming_cond, &cond_attr);
  1484. pthread_condattr_destroy(&cond_attr);
  1485. /* FIXME: in debug mode, the threads should be named */
  1486. pthread_mutex_lock(&thread->running_mutex);
  1487. int res = pthread_create(&thread->thread, 0, thread_func, thread_arg);
  1488. thread->valid = (0 == res);
  1489. pthread_mutex_unlock(&thread->running_mutex);
  1490. return thread->valid;
  1491. }
  1492. _SOKOL_PRIVATE void _sfetch_thread_request_stop(_sfetch_thread_t* thread) {
  1493. pthread_mutex_lock(&thread->stop_mutex);
  1494. thread->stop_requested = true;
  1495. pthread_mutex_unlock(&thread->stop_mutex);
  1496. }
  1497. _SOKOL_PRIVATE bool _sfetch_thread_stop_requested(_sfetch_thread_t* thread) {
  1498. pthread_mutex_lock(&thread->stop_mutex);
  1499. bool stop_requested = thread->stop_requested;
  1500. pthread_mutex_unlock(&thread->stop_mutex);
  1501. return stop_requested;
  1502. }
  1503. _SOKOL_PRIVATE void _sfetch_thread_join(_sfetch_thread_t* thread) {
  1504. SOKOL_ASSERT(thread);
  1505. if (thread->valid) {
  1506. pthread_mutex_lock(&thread->incoming_mutex);
  1507. _sfetch_thread_request_stop(thread);
  1508. pthread_cond_signal(&thread->incoming_cond);
  1509. pthread_mutex_unlock(&thread->incoming_mutex);
  1510. pthread_join(thread->thread, 0);
  1511. thread->valid = false;
  1512. }
  1513. pthread_mutex_destroy(&thread->stop_mutex);
  1514. pthread_mutex_destroy(&thread->running_mutex);
  1515. pthread_mutex_destroy(&thread->incoming_mutex);
  1516. pthread_mutex_destroy(&thread->outgoing_mutex);
  1517. pthread_cond_destroy(&thread->incoming_cond);
  1518. }
  1519. /* called when the thread-func is entered, this blocks the thread func until
  1520. the _sfetch_thread_t object is fully initialized
  1521. */
  1522. _SOKOL_PRIVATE void _sfetch_thread_entered(_sfetch_thread_t* thread) {
  1523. pthread_mutex_lock(&thread->running_mutex);
  1524. }
  1525. /* called by the thread-func right before it is left */
  1526. _SOKOL_PRIVATE void _sfetch_thread_leaving(_sfetch_thread_t* thread) {
  1527. pthread_mutex_unlock(&thread->running_mutex);
  1528. }
  1529. _SOKOL_PRIVATE void _sfetch_thread_enqueue_incoming(_sfetch_thread_t* thread, _sfetch_ring_t* incoming, _sfetch_ring_t* src) {
  1530. /* called from user thread */
  1531. SOKOL_ASSERT(thread && thread->valid);
  1532. SOKOL_ASSERT(incoming && incoming->buf);
  1533. SOKOL_ASSERT(src && src->buf);
  1534. if (!_sfetch_ring_empty(src)) {
  1535. pthread_mutex_lock(&thread->incoming_mutex);
  1536. while (!_sfetch_ring_full(incoming) && !_sfetch_ring_empty(src)) {
  1537. _sfetch_ring_enqueue(incoming, _sfetch_ring_dequeue(src));
  1538. }
  1539. pthread_cond_signal(&thread->incoming_cond);
  1540. pthread_mutex_unlock(&thread->incoming_mutex);
  1541. }
  1542. }
  1543. _SOKOL_PRIVATE uint32_t _sfetch_thread_dequeue_incoming(_sfetch_thread_t* thread, _sfetch_ring_t* incoming) {
  1544. /* called from thread function */
  1545. SOKOL_ASSERT(thread && thread->valid);
  1546. SOKOL_ASSERT(incoming && incoming->buf);
  1547. pthread_mutex_lock(&thread->incoming_mutex);
  1548. while (_sfetch_ring_empty(incoming) && !thread->stop_requested) {
  1549. pthread_cond_wait(&thread->incoming_cond, &thread->incoming_mutex);
  1550. }
  1551. uint32_t item = 0;
  1552. if (!thread->stop_requested) {
  1553. item = _sfetch_ring_dequeue(incoming);
  1554. }
  1555. pthread_mutex_unlock(&thread->incoming_mutex);
  1556. return item;
  1557. }
  1558. _SOKOL_PRIVATE bool _sfetch_thread_enqueue_outgoing(_sfetch_thread_t* thread, _sfetch_ring_t* outgoing, uint32_t item) {
  1559. /* called from thread function */
  1560. SOKOL_ASSERT(thread && thread->valid);
  1561. SOKOL_ASSERT(outgoing && outgoing->buf);
  1562. SOKOL_ASSERT(0 != item);
  1563. pthread_mutex_lock(&thread->outgoing_mutex);
  1564. bool result = false;
  1565. if (!_sfetch_ring_full(outgoing)) {
  1566. _sfetch_ring_enqueue(outgoing, item);
  1567. }
  1568. pthread_mutex_unlock(&thread->outgoing_mutex);
  1569. return result;
  1570. }
  1571. _SOKOL_PRIVATE void _sfetch_thread_dequeue_outgoing(_sfetch_thread_t* thread, _sfetch_ring_t* outgoing, _sfetch_ring_t* dst) {
  1572. /* called from user thread */
  1573. SOKOL_ASSERT(thread && thread->valid);
  1574. SOKOL_ASSERT(outgoing && outgoing->buf);
  1575. SOKOL_ASSERT(dst && dst->buf);
  1576. pthread_mutex_lock(&thread->outgoing_mutex);
  1577. while (!_sfetch_ring_full(dst) && !_sfetch_ring_empty(outgoing)) {
  1578. _sfetch_ring_enqueue(dst, _sfetch_ring_dequeue(outgoing));
  1579. }
  1580. pthread_mutex_unlock(&thread->outgoing_mutex);
  1581. }
  1582. #endif /* _SFETCH_PLATFORM_POSIX */
  1583. // ██ ██ ██ ███ ██ ██████ ██████ ██ ██ ███████
  1584. // ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██ ██
  1585. // ██ █ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ █ ██ ███████
  1586. // ██ ███ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██ ██
  1587. // ███ ███ ██ ██ ████ ██████ ██████ ███ ███ ███████
  1588. //
  1589. // >>windows
  1590. #if _SFETCH_PLATFORM_WINDOWS
  1591. _SOKOL_PRIVATE bool _sfetch_win32_utf8_to_wide(const char* src, wchar_t* dst, int dst_num_bytes) {
  1592. SOKOL_ASSERT(src && dst && (dst_num_bytes > 1));
  1593. _sfetch_clear(dst, (size_t)dst_num_bytes);
  1594. const int dst_chars = dst_num_bytes / (int)sizeof(wchar_t);
  1595. const int dst_needed = MultiByteToWideChar(CP_UTF8, 0, src, -1, 0, 0);
  1596. if ((dst_needed > 0) && (dst_needed < dst_chars)) {
  1597. MultiByteToWideChar(CP_UTF8, 0, src, -1, dst, dst_chars);
  1598. return true;
  1599. } else {
  1600. /* input string doesn't fit into destination buffer */
  1601. return false;
  1602. }
  1603. }
  1604. _SOKOL_PRIVATE _sfetch_file_handle_t _sfetch_file_open(const _sfetch_path_t* path) {
  1605. wchar_t w_path[SFETCH_MAX_PATH];
  1606. if (!_sfetch_win32_utf8_to_wide(path->buf, w_path, sizeof(w_path))) {
  1607. _SFETCH_ERROR(FILE_PATH_UTF8_DECODING_FAILED);
  1608. return 0;
  1609. }
  1610. _sfetch_file_handle_t h = CreateFileW(
  1611. w_path, /* lpFileName */
  1612. GENERIC_READ, /* dwDesiredAccess */
  1613. FILE_SHARE_READ, /* dwShareMode */
  1614. NULL, /* lpSecurityAttributes */
  1615. OPEN_EXISTING, /* dwCreationDisposition */
  1616. FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN, /* dwFlagsAndAttributes */
  1617. NULL); /* hTemplateFile */
  1618. return h;
  1619. }
  1620. _SOKOL_PRIVATE void _sfetch_file_close(_sfetch_file_handle_t h) {
  1621. CloseHandle(h);
  1622. }
  1623. _SOKOL_PRIVATE bool _sfetch_file_handle_valid(_sfetch_file_handle_t h) {
  1624. return h != _SFETCH_INVALID_FILE_HANDLE;
  1625. }
  1626. _SOKOL_PRIVATE uint32_t _sfetch_file_size(_sfetch_file_handle_t h) {
  1627. return GetFileSize(h, NULL);
  1628. }
  1629. _SOKOL_PRIVATE bool _sfetch_file_read(_sfetch_file_handle_t h, uint32_t offset, uint32_t num_bytes, void* ptr) {
  1630. LARGE_INTEGER offset_li;
  1631. offset_li.QuadPart = offset;
  1632. BOOL seek_res = SetFilePointerEx(h, offset_li, NULL, FILE_BEGIN);
  1633. if (seek_res) {
  1634. DWORD bytes_read = 0;
  1635. BOOL read_res = ReadFile(h, ptr, (DWORD)num_bytes, &bytes_read, NULL);
  1636. return read_res && (bytes_read == num_bytes);
  1637. } else {
  1638. return false;
  1639. }
  1640. }
  1641. _SOKOL_PRIVATE bool _sfetch_thread_init(_sfetch_thread_t* thread, _sfetch_thread_func_t thread_func, void* thread_arg) {
  1642. SOKOL_ASSERT(thread && !thread->valid && !thread->stop_requested);
  1643. thread->incoming_event = CreateEventA(NULL, FALSE, FALSE, NULL);
  1644. SOKOL_ASSERT(NULL != thread->incoming_event);
  1645. InitializeCriticalSection(&thread->incoming_critsec);
  1646. InitializeCriticalSection(&thread->outgoing_critsec);
  1647. InitializeCriticalSection(&thread->running_critsec);
  1648. InitializeCriticalSection(&thread->stop_critsec);
  1649. EnterCriticalSection(&thread->running_critsec);
  1650. const SIZE_T stack_size = 512 * 1024;
  1651. thread->thread = CreateThread(NULL, stack_size, thread_func, thread_arg, 0, NULL);
  1652. thread->valid = (NULL != thread->thread);
  1653. LeaveCriticalSection(&thread->running_critsec);
  1654. return thread->valid;
  1655. }
  1656. _SOKOL_PRIVATE void _sfetch_thread_request_stop(_sfetch_thread_t* thread) {
  1657. EnterCriticalSection(&thread->stop_critsec);
  1658. thread->stop_requested = true;
  1659. LeaveCriticalSection(&thread->stop_critsec);
  1660. }
  1661. _SOKOL_PRIVATE bool _sfetch_thread_stop_requested(_sfetch_thread_t* thread) {
  1662. EnterCriticalSection(&thread->stop_critsec);
  1663. bool stop_requested = thread->stop_requested;
  1664. LeaveCriticalSection(&thread->stop_critsec);
  1665. return stop_requested;
  1666. }
  1667. _SOKOL_PRIVATE void _sfetch_thread_join(_sfetch_thread_t* thread) {
  1668. if (thread->valid) {
  1669. EnterCriticalSection(&thread->incoming_critsec);
  1670. _sfetch_thread_request_stop(thread);
  1671. BOOL set_event_res = SetEvent(thread->incoming_event);
  1672. _SOKOL_UNUSED(set_event_res);
  1673. SOKOL_ASSERT(set_event_res);
  1674. LeaveCriticalSection(&thread->incoming_critsec);
  1675. WaitForSingleObject(thread->thread, INFINITE);
  1676. CloseHandle(thread->thread);
  1677. thread->valid = false;
  1678. }
  1679. CloseHandle(thread->incoming_event);
  1680. DeleteCriticalSection(&thread->stop_critsec);
  1681. DeleteCriticalSection(&thread->running_critsec);
  1682. DeleteCriticalSection(&thread->outgoing_critsec);
  1683. DeleteCriticalSection(&thread->incoming_critsec);
  1684. }
  1685. _SOKOL_PRIVATE void _sfetch_thread_entered(_sfetch_thread_t* thread) {
  1686. EnterCriticalSection(&thread->running_critsec);
  1687. }
  1688. /* called by the thread-func right before it is left */
  1689. _SOKOL_PRIVATE void _sfetch_thread_leaving(_sfetch_thread_t* thread) {
  1690. LeaveCriticalSection(&thread->running_critsec);
  1691. }
  1692. _SOKOL_PRIVATE void _sfetch_thread_enqueue_incoming(_sfetch_thread_t* thread, _sfetch_ring_t* incoming, _sfetch_ring_t* src) {
  1693. /* called from user thread */
  1694. SOKOL_ASSERT(thread && thread->valid);
  1695. SOKOL_ASSERT(incoming && incoming->buf);
  1696. SOKOL_ASSERT(src && src->buf);
  1697. if (!_sfetch_ring_empty(src)) {
  1698. EnterCriticalSection(&thread->incoming_critsec);
  1699. while (!_sfetch_ring_full(incoming) && !_sfetch_ring_empty(src)) {
  1700. _sfetch_ring_enqueue(incoming, _sfetch_ring_dequeue(src));
  1701. }
  1702. LeaveCriticalSection(&thread->incoming_critsec);
  1703. BOOL set_event_res = SetEvent(thread->incoming_event);
  1704. _SOKOL_UNUSED(set_event_res);
  1705. SOKOL_ASSERT(set_event_res);
  1706. }
  1707. }
  1708. _SOKOL_PRIVATE uint32_t _sfetch_thread_dequeue_incoming(_sfetch_thread_t* thread, _sfetch_ring_t* incoming) {
  1709. /* called from thread function */
  1710. SOKOL_ASSERT(thread && thread->valid);
  1711. SOKOL_ASSERT(incoming && incoming->buf);
  1712. EnterCriticalSection(&thread->incoming_critsec);
  1713. while (_sfetch_ring_empty(incoming) && !thread->stop_requested) {
  1714. LeaveCriticalSection(&thread->incoming_critsec);
  1715. WaitForSingleObject(thread->incoming_event, INFINITE);
  1716. EnterCriticalSection(&thread->incoming_critsec);
  1717. }
  1718. uint32_t item = 0;
  1719. if (!thread->stop_requested) {
  1720. item = _sfetch_ring_dequeue(incoming);
  1721. }
  1722. LeaveCriticalSection(&thread->incoming_critsec);
  1723. return item;
  1724. }
  1725. _SOKOL_PRIVATE bool _sfetch_thread_enqueue_outgoing(_sfetch_thread_t* thread, _sfetch_ring_t* outgoing, uint32_t item) {
  1726. /* called from thread function */
  1727. SOKOL_ASSERT(thread && thread->valid);
  1728. SOKOL_ASSERT(outgoing && outgoing->buf);
  1729. EnterCriticalSection(&thread->outgoing_critsec);
  1730. bool result = false;
  1731. if (!_sfetch_ring_full(outgoing)) {
  1732. _sfetch_ring_enqueue(outgoing, item);
  1733. }
  1734. LeaveCriticalSection(&thread->outgoing_critsec);
  1735. return result;
  1736. }
  1737. _SOKOL_PRIVATE void _sfetch_thread_dequeue_outgoing(_sfetch_thread_t* thread, _sfetch_ring_t* outgoing, _sfetch_ring_t* dst) {
  1738. /* called from user thread */
  1739. SOKOL_ASSERT(thread && thread->valid);
  1740. SOKOL_ASSERT(outgoing && outgoing->buf);
  1741. SOKOL_ASSERT(dst && dst->buf);
  1742. EnterCriticalSection(&thread->outgoing_critsec);
  1743. while (!_sfetch_ring_full(dst) && !_sfetch_ring_empty(outgoing)) {
  1744. _sfetch_ring_enqueue(dst, _sfetch_ring_dequeue(outgoing));
  1745. }
  1746. LeaveCriticalSection(&thread->outgoing_critsec);
  1747. }
  1748. #endif /* _SFETCH_PLATFORM_WINDOWS */
  1749. // ██████ ██ ██ █████ ███ ██ ███ ██ ███████ ██ ███████
  1750. // ██ ██ ██ ██ ██ ████ ██ ████ ██ ██ ██ ██
  1751. // ██ ███████ ███████ ██ ██ ██ ██ ██ ██ █████ ██ ███████
  1752. // ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
  1753. // ██████ ██ ██ ██ ██ ██ ████ ██ ████ ███████ ███████ ███████
  1754. //
  1755. // >>channels
  1756. /* per-channel request handler for native platforms accessing the local filesystem */
  1757. #if _SFETCH_HAS_THREADS
  1758. _SOKOL_PRIVATE void _sfetch_request_handler(_sfetch_t* ctx, uint32_t slot_id) {
  1759. _sfetch_state_t state;
  1760. _sfetch_path_t* path;
  1761. _sfetch_item_thread_t* thread;
  1762. sfetch_range_t* buffer;
  1763. uint32_t chunk_size;
  1764. {
  1765. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  1766. if (!item) {
  1767. return;
  1768. }
  1769. state = item->state;
  1770. SOKOL_ASSERT((state == _SFETCH_STATE_FETCHING) ||
  1771. (state == _SFETCH_STATE_PAUSED) ||
  1772. (state == _SFETCH_STATE_FAILED));
  1773. path = &item->path;
  1774. thread = &item->thread;
  1775. buffer = &item->buffer;
  1776. chunk_size = item->chunk_size;
  1777. }
  1778. if (thread->failed) {
  1779. return;
  1780. }
  1781. if (state == _SFETCH_STATE_FETCHING) {
  1782. if ((buffer->ptr == 0) || (buffer->size == 0)) {
  1783. thread->error_code = SFETCH_ERROR_NO_BUFFER;
  1784. thread->failed = true;
  1785. } else {
  1786. /* open file if not happened yet */
  1787. if (!_sfetch_file_handle_valid(thread->file_handle)) {
  1788. SOKOL_ASSERT(path->buf[0]);
  1789. SOKOL_ASSERT(thread->fetched_offset == 0);
  1790. SOKOL_ASSERT(thread->fetched_size == 0);
  1791. thread->file_handle = _sfetch_file_open(path);
  1792. if (_sfetch_file_handle_valid(thread->file_handle)) {
  1793. thread->content_size = _sfetch_file_size(thread->file_handle);
  1794. } else {
  1795. thread->error_code = SFETCH_ERROR_FILE_NOT_FOUND;
  1796. thread->failed = true;
  1797. }
  1798. }
  1799. if (!thread->failed) {
  1800. uint32_t read_offset = 0;
  1801. uint32_t bytes_to_read = 0;
  1802. if (chunk_size == 0) {
  1803. /* load entire file */
  1804. if (thread->content_size <= buffer->size) {
  1805. bytes_to_read = thread->content_size;
  1806. read_offset = 0;
  1807. } else {
  1808. /* provided buffer to small to fit entire file */
  1809. thread->error_code = SFETCH_ERROR_BUFFER_TOO_SMALL;
  1810. thread->failed = true;
  1811. }
  1812. } else {
  1813. if (chunk_size <= buffer->size) {
  1814. bytes_to_read = chunk_size;
  1815. read_offset = thread->fetched_offset;
  1816. if ((read_offset + bytes_to_read) > thread->content_size) {
  1817. bytes_to_read = thread->content_size - read_offset;
  1818. }
  1819. } else {
  1820. /* provided buffer to small to fit next chunk */
  1821. thread->error_code = SFETCH_ERROR_BUFFER_TOO_SMALL;
  1822. thread->failed = true;
  1823. }
  1824. }
  1825. if (!thread->failed) {
  1826. if (_sfetch_file_read(thread->file_handle, read_offset, bytes_to_read, (void*)buffer->ptr)) {
  1827. thread->fetched_size = bytes_to_read;
  1828. thread->fetched_offset += bytes_to_read;
  1829. } else {
  1830. thread->error_code = SFETCH_ERROR_UNEXPECTED_EOF;
  1831. thread->failed = true;
  1832. }
  1833. }
  1834. }
  1835. }
  1836. SOKOL_ASSERT(thread->fetched_offset <= thread->content_size);
  1837. if (thread->failed || (thread->fetched_offset == thread->content_size)) {
  1838. if (_sfetch_file_handle_valid(thread->file_handle)) {
  1839. _sfetch_file_close(thread->file_handle);
  1840. thread->file_handle = _SFETCH_INVALID_FILE_HANDLE;
  1841. }
  1842. thread->finished = true;
  1843. }
  1844. }
  1845. /* ignore items in PAUSED or FAILED state */
  1846. }
  1847. #if _SFETCH_PLATFORM_WINDOWS
  1848. _SOKOL_PRIVATE DWORD WINAPI _sfetch_channel_thread_func(LPVOID arg) {
  1849. #else
  1850. _SOKOL_PRIVATE void* _sfetch_channel_thread_func(void* arg) {
  1851. #endif
  1852. _sfetch_channel_t* chn = (_sfetch_channel_t*) arg;
  1853. _sfetch_thread_entered(&chn->thread);
  1854. while (!_sfetch_thread_stop_requested(&chn->thread)) {
  1855. /* block until work arrives */
  1856. uint32_t slot_id = _sfetch_thread_dequeue_incoming(&chn->thread, &chn->thread_incoming);
  1857. /* slot_id will be invalid if the thread was woken up to join */
  1858. if (!_sfetch_thread_stop_requested(&chn->thread)) {
  1859. SOKOL_ASSERT(0 != slot_id);
  1860. chn->request_handler(chn->ctx, slot_id);
  1861. SOKOL_ASSERT(!_sfetch_ring_full(&chn->thread_outgoing));
  1862. _sfetch_thread_enqueue_outgoing(&chn->thread, &chn->thread_outgoing, slot_id);
  1863. }
  1864. }
  1865. _sfetch_thread_leaving(&chn->thread);
  1866. return 0;
  1867. }
  1868. #endif /* _SFETCH_HAS_THREADS */
  1869. #if _SFETCH_PLATFORM_EMSCRIPTEN
  1870. EM_JS(void, sfetch_js_send_head_request, (uint32_t slot_id, const char* path_cstr), {
  1871. const path_str = UTF8ToString(path_cstr);
  1872. fetch(path_str, { method: 'HEAD' }).then((response) => {
  1873. if (response.ok) {
  1874. const content_length = response.headers.get('Content-Length');
  1875. if (content_length === null) {
  1876. console.warn(`sokol_fetch.h: HEAD ${path_str} response has no Content-Length`);
  1877. __sfetch_emsc_failed_other(slot_id);
  1878. } else {
  1879. __sfetch_emsc_head_response(slot_id, Number(content_length));
  1880. }
  1881. } else {
  1882. __sfetch_emsc_failed_http_status(slot_id, response.status);
  1883. }
  1884. }).catch((err) => {
  1885. console.error(`sokol_fetch.h: HEAD ${path_str} failed with: `, err);
  1886. __sfetch_emsc_failed_other(slot_id);
  1887. });
  1888. })
  1889. /* if bytes_to_read != 0, a range-request will be sent, otherwise a normal request */
  1890. EM_JS(void, sfetch_js_send_get_request, (uint32_t slot_id, const char* path_cstr, uint32_t offset, uint32_t bytes_to_read, void* buf_ptr, uint32_t buf_size), {
  1891. const path_str = UTF8ToString(path_cstr);
  1892. const headers = new Headers();
  1893. const range_request = bytes_to_read > 0;
  1894. if (range_request) {
  1895. headers.append('Range', `bytes=${offset}-${offset+bytes_to_read-1}`);
  1896. }
  1897. fetch(path_str, { method: 'GET', headers }).then((response) => {
  1898. if (response.ok) {
  1899. response.arrayBuffer().then((data) => {
  1900. const u8_data = new Uint8Array(data);
  1901. if (u8_data.length <= buf_size) {
  1902. HEAPU8.set(u8_data, buf_ptr);
  1903. __sfetch_emsc_get_response(slot_id, bytes_to_read, u8_data.length);
  1904. } else {
  1905. __sfetch_emsc_failed_buffer_too_small(slot_id);
  1906. }
  1907. }).catch((err) => {
  1908. console.error(`sokol_fetch.h: GET ${path_str} failed with: `, err);
  1909. __sfetch_emsc_failed_other(slot_id);
  1910. });
  1911. } else {
  1912. __sfetch_emsc_failed_http_status(slot_id, response.status);
  1913. }
  1914. }).catch((err) => {
  1915. console.error(`sokol_fetch.h: GET ${path_str} failed with: `, err);
  1916. __sfetch_emsc_failed_other(slot_id);
  1917. });
  1918. })
  1919. /*=== emscripten specific C helper functions =================================*/
  1920. #ifdef __cplusplus
  1921. extern "C" {
  1922. #endif
  1923. void _sfetch_emsc_send_get_request(uint32_t slot_id, _sfetch_item_t* item) {
  1924. if ((item->buffer.ptr == 0) || (item->buffer.size == 0)) {
  1925. item->thread.error_code = SFETCH_ERROR_NO_BUFFER;
  1926. item->thread.failed = true;
  1927. } else {
  1928. uint32_t offset = 0;
  1929. uint32_t bytes_to_read = 0;
  1930. if (item->chunk_size > 0) {
  1931. /* send HTTP range request */
  1932. SOKOL_ASSERT(item->thread.content_size > 0);
  1933. SOKOL_ASSERT(item->thread.http_range_offset < item->thread.content_size);
  1934. bytes_to_read = item->thread.content_size - item->thread.http_range_offset;
  1935. if (bytes_to_read > item->chunk_size) {
  1936. bytes_to_read = item->chunk_size;
  1937. }
  1938. SOKOL_ASSERT(bytes_to_read > 0);
  1939. offset = item->thread.http_range_offset;
  1940. }
  1941. sfetch_js_send_get_request(slot_id, item->path.buf, offset, bytes_to_read, (void*)item->buffer.ptr, item->buffer.size);
  1942. }
  1943. }
  1944. /* called by JS when an initial HEAD request finished successfully (only when streaming chunks) */
  1945. EMSCRIPTEN_KEEPALIVE void _sfetch_emsc_head_response(uint32_t slot_id, uint32_t content_length) {
  1946. _sfetch_t* ctx = _sfetch_ctx();
  1947. if (ctx && ctx->valid) {
  1948. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  1949. if (item) {
  1950. SOKOL_ASSERT(item->buffer.ptr && (item->buffer.size > 0));
  1951. item->thread.content_size = content_length;
  1952. _sfetch_emsc_send_get_request(slot_id, item);
  1953. }
  1954. }
  1955. }
  1956. /* called by JS when a followup GET request finished successfully */
  1957. EMSCRIPTEN_KEEPALIVE void _sfetch_emsc_get_response(uint32_t slot_id, uint32_t range_fetched_size, uint32_t content_fetched_size) {
  1958. _sfetch_t* ctx = _sfetch_ctx();
  1959. if (ctx && ctx->valid) {
  1960. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  1961. if (item) {
  1962. item->thread.fetched_size = content_fetched_size;
  1963. item->thread.fetched_offset += content_fetched_size;
  1964. item->thread.http_range_offset += range_fetched_size;
  1965. if (item->chunk_size == 0) {
  1966. item->thread.finished = true;
  1967. } else if (item->thread.http_range_offset >= item->thread.content_size) {
  1968. item->thread.finished = true;
  1969. }
  1970. _sfetch_ring_enqueue(&ctx->chn[item->channel].user_outgoing, slot_id);
  1971. }
  1972. }
  1973. }
  1974. /* called by JS when an error occurred */
  1975. EMSCRIPTEN_KEEPALIVE void _sfetch_emsc_failed_http_status(uint32_t slot_id, uint32_t http_status) {
  1976. _sfetch_t* ctx = _sfetch_ctx();
  1977. if (ctx && ctx->valid) {
  1978. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  1979. if (item) {
  1980. if (http_status == 404) {
  1981. item->thread.error_code = SFETCH_ERROR_FILE_NOT_FOUND;
  1982. } else {
  1983. item->thread.error_code = SFETCH_ERROR_INVALID_HTTP_STATUS;
  1984. }
  1985. item->thread.failed = true;
  1986. item->thread.finished = true;
  1987. _sfetch_ring_enqueue(&ctx->chn[item->channel].user_outgoing, slot_id);
  1988. }
  1989. }
  1990. }
  1991. EMSCRIPTEN_KEEPALIVE void _sfetch_emsc_failed_buffer_too_small(uint32_t slot_id) {
  1992. _sfetch_t* ctx = _sfetch_ctx();
  1993. if (ctx && ctx->valid) {
  1994. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  1995. if (item) {
  1996. item->thread.error_code = SFETCH_ERROR_BUFFER_TOO_SMALL;
  1997. item->thread.failed = true;
  1998. item->thread.finished = true;
  1999. _sfetch_ring_enqueue(&ctx->chn[item->channel].user_outgoing, slot_id);
  2000. }
  2001. }
  2002. }
  2003. EMSCRIPTEN_KEEPALIVE void _sfetch_emsc_failed_other(uint32_t slot_id) {
  2004. _sfetch_t* ctx = _sfetch_ctx();
  2005. if (ctx && ctx->valid) {
  2006. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  2007. if (item) {
  2008. item->thread.error_code = SFETCH_ERROR_JS_OTHER;
  2009. item->thread.failed = true;
  2010. item->thread.finished = true;
  2011. _sfetch_ring_enqueue(&ctx->chn[item->channel].user_outgoing, slot_id);
  2012. }
  2013. }
  2014. }
  2015. #ifdef __cplusplus
  2016. } /* extern "C" */
  2017. #endif
  2018. _SOKOL_PRIVATE void _sfetch_request_handler(_sfetch_t* ctx, uint32_t slot_id) {
  2019. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, slot_id);
  2020. if (!item) {
  2021. return;
  2022. }
  2023. if (item->state == _SFETCH_STATE_FETCHING) {
  2024. if ((item->chunk_size > 0) && (item->thread.content_size == 0)) {
  2025. /* if streaming download is requested, and the content-length isn't known
  2026. yet, need to send a HEAD request first
  2027. */
  2028. sfetch_js_send_head_request(slot_id, item->path.buf);
  2029. } else {
  2030. /* otherwise, this is either a request to load the entire file, or
  2031. to load the next streaming chunk
  2032. */
  2033. _sfetch_emsc_send_get_request(slot_id, item);
  2034. }
  2035. } else {
  2036. /* just move all other items (e.g. paused or cancelled)
  2037. into the outgoing queue, so they won't get lost
  2038. */
  2039. _sfetch_ring_enqueue(&ctx->chn[item->channel].user_outgoing, slot_id);
  2040. }
  2041. if (item->thread.failed) {
  2042. item->thread.finished = true;
  2043. }
  2044. }
  2045. #endif /* _SFETCH_PLATFORM_EMSCRIPTEN */
  2046. _SOKOL_PRIVATE void _sfetch_channel_discard(_sfetch_channel_t* chn) {
  2047. SOKOL_ASSERT(chn);
  2048. #if _SFETCH_HAS_THREADS
  2049. if (chn->valid) {
  2050. _sfetch_thread_join(&chn->thread);
  2051. }
  2052. _sfetch_ring_discard(&chn->thread_incoming);
  2053. _sfetch_ring_discard(&chn->thread_outgoing);
  2054. #endif
  2055. _sfetch_ring_discard(&chn->free_lanes);
  2056. _sfetch_ring_discard(&chn->user_sent);
  2057. _sfetch_ring_discard(&chn->user_incoming);
  2058. _sfetch_ring_discard(&chn->user_outgoing);
  2059. _sfetch_ring_discard(&chn->free_lanes);
  2060. chn->valid = false;
  2061. }
  2062. _SOKOL_PRIVATE bool _sfetch_channel_init(_sfetch_channel_t* chn, _sfetch_t* ctx, uint32_t num_items, uint32_t num_lanes, void (*request_handler)(_sfetch_t* ctx, uint32_t)) {
  2063. SOKOL_ASSERT(chn && (num_items > 0) && request_handler);
  2064. SOKOL_ASSERT(!chn->valid);
  2065. bool valid = true;
  2066. chn->request_handler = request_handler;
  2067. chn->ctx = ctx;
  2068. valid &= _sfetch_ring_init(&chn->free_lanes, num_lanes);
  2069. for (uint32_t lane = 0; lane < num_lanes; lane++) {
  2070. _sfetch_ring_enqueue(&chn->free_lanes, lane);
  2071. }
  2072. valid &= _sfetch_ring_init(&chn->user_sent, num_items);
  2073. valid &= _sfetch_ring_init(&chn->user_incoming, num_lanes);
  2074. valid &= _sfetch_ring_init(&chn->user_outgoing, num_lanes);
  2075. #if _SFETCH_HAS_THREADS
  2076. valid &= _sfetch_ring_init(&chn->thread_incoming, num_lanes);
  2077. valid &= _sfetch_ring_init(&chn->thread_outgoing, num_lanes);
  2078. #endif
  2079. if (valid) {
  2080. chn->valid = true;
  2081. #if _SFETCH_HAS_THREADS
  2082. _sfetch_thread_init(&chn->thread, _sfetch_channel_thread_func, chn);
  2083. #endif
  2084. return true;
  2085. } else {
  2086. _sfetch_channel_discard(chn);
  2087. return false;
  2088. }
  2089. }
  2090. /* put a request into the channels sent-queue, this is where all new requests
  2091. are stored until a lane becomes free.
  2092. */
  2093. _SOKOL_PRIVATE bool _sfetch_channel_send(_sfetch_channel_t* chn, uint32_t slot_id) {
  2094. SOKOL_ASSERT(chn && chn->valid);
  2095. if (!_sfetch_ring_full(&chn->user_sent)) {
  2096. _sfetch_ring_enqueue(&chn->user_sent, slot_id);
  2097. return true;
  2098. } else {
  2099. _SFETCH_ERROR(SEND_QUEUE_FULL);
  2100. return false;
  2101. }
  2102. }
  2103. _SOKOL_PRIVATE void _sfetch_invoke_response_callback(_sfetch_item_t* item) {
  2104. sfetch_response_t response;
  2105. _sfetch_clear(&response, sizeof(response));
  2106. response.handle = item->handle;
  2107. response.dispatched = (item->state == _SFETCH_STATE_DISPATCHED);
  2108. response.fetched = (item->state == _SFETCH_STATE_FETCHED);
  2109. response.paused = (item->state == _SFETCH_STATE_PAUSED);
  2110. response.finished = item->user.finished;
  2111. response.failed = (item->state == _SFETCH_STATE_FAILED);
  2112. response.cancelled = item->user.cancel;
  2113. response.error_code = item->user.error_code;
  2114. response.channel = item->channel;
  2115. response.lane = item->lane;
  2116. response.path = item->path.buf;
  2117. response.user_data = item->user.user_data;
  2118. response.data_offset = item->user.fetched_offset - item->user.fetched_size;
  2119. response.data.ptr = item->buffer.ptr;
  2120. response.data.size = item->user.fetched_size;
  2121. response.buffer = item->buffer;
  2122. item->callback(&response);
  2123. }
  2124. _SOKOL_PRIVATE void _sfetch_cancel_item(_sfetch_item_t* item) {
  2125. item->state = _SFETCH_STATE_FAILED;
  2126. item->user.finished = true;
  2127. item->user.error_code = SFETCH_ERROR_CANCELLED;
  2128. }
  2129. /* per-frame channel stuff: move requests in and out of the IO threads, call response callbacks */
  2130. _SOKOL_PRIVATE void _sfetch_channel_dowork(_sfetch_channel_t* chn, _sfetch_pool_t* pool) {
  2131. /* move items from sent- to incoming-queue permitting free lanes */
  2132. const uint32_t num_sent = _sfetch_ring_count(&chn->user_sent);
  2133. const uint32_t avail_lanes = _sfetch_ring_count(&chn->free_lanes);
  2134. const uint32_t num_move = (num_sent < avail_lanes) ? num_sent : avail_lanes;
  2135. for (uint32_t i = 0; i < num_move; i++) {
  2136. const uint32_t slot_id = _sfetch_ring_dequeue(&chn->user_sent);
  2137. _sfetch_item_t* item = _sfetch_pool_item_lookup(pool, slot_id);
  2138. SOKOL_ASSERT(item);
  2139. SOKOL_ASSERT(item->state == _SFETCH_STATE_ALLOCATED);
  2140. // if the item was cancelled early, kick it out immediately
  2141. if (item->user.cancel) {
  2142. _sfetch_cancel_item(item);
  2143. _sfetch_invoke_response_callback(item);
  2144. _sfetch_pool_item_free(pool, slot_id);
  2145. continue;
  2146. }
  2147. item->state = _SFETCH_STATE_DISPATCHED;
  2148. item->lane = _sfetch_ring_dequeue(&chn->free_lanes);
  2149. // if no buffer provided yet, invoke response callback to do so
  2150. if (0 == item->buffer.ptr) {
  2151. _sfetch_invoke_response_callback(item);
  2152. }
  2153. _sfetch_ring_enqueue(&chn->user_incoming, slot_id);
  2154. }
  2155. /* prepare incoming items for being moved into the IO thread */
  2156. const uint32_t num_incoming = _sfetch_ring_count(&chn->user_incoming);
  2157. for (uint32_t i = 0; i < num_incoming; i++) {
  2158. const uint32_t slot_id = _sfetch_ring_peek(&chn->user_incoming, i);
  2159. _sfetch_item_t* item = _sfetch_pool_item_lookup(pool, slot_id);
  2160. SOKOL_ASSERT(item);
  2161. SOKOL_ASSERT(item->state != _SFETCH_STATE_INITIAL);
  2162. SOKOL_ASSERT(item->state != _SFETCH_STATE_FETCHING);
  2163. /* transfer input params from user- to thread-data */
  2164. if (item->user.pause) {
  2165. item->state = _SFETCH_STATE_PAUSED;
  2166. item->user.pause = false;
  2167. }
  2168. if (item->user.cont) {
  2169. if (item->state == _SFETCH_STATE_PAUSED) {
  2170. item->state = _SFETCH_STATE_FETCHED;
  2171. }
  2172. item->user.cont = false;
  2173. }
  2174. if (item->user.cancel) {
  2175. _sfetch_cancel_item(item);
  2176. }
  2177. switch (item->state) {
  2178. case _SFETCH_STATE_DISPATCHED:
  2179. case _SFETCH_STATE_FETCHED:
  2180. item->state = _SFETCH_STATE_FETCHING;
  2181. break;
  2182. default: break;
  2183. }
  2184. }
  2185. #if _SFETCH_HAS_THREADS
  2186. /* move new items into the IO threads and processed items out of IO threads */
  2187. _sfetch_thread_enqueue_incoming(&chn->thread, &chn->thread_incoming, &chn->user_incoming);
  2188. _sfetch_thread_dequeue_outgoing(&chn->thread, &chn->thread_outgoing, &chn->user_outgoing);
  2189. #else
  2190. /* without threading just directly dequeue items from the user_incoming queue and
  2191. call the request handler, the user_outgoing queue will be filled as the
  2192. asynchronous HTTP requests sent by the request handler are completed
  2193. */
  2194. while (!_sfetch_ring_empty(&chn->user_incoming)) {
  2195. uint32_t slot_id = _sfetch_ring_dequeue(&chn->user_incoming);
  2196. _sfetch_request_handler(chn->ctx, slot_id);
  2197. }
  2198. #endif
  2199. /* drain the outgoing queue, prepare items for invoking the response
  2200. callback, and finally call the response callback, free finished items
  2201. */
  2202. while (!_sfetch_ring_empty(&chn->user_outgoing)) {
  2203. const uint32_t slot_id = _sfetch_ring_dequeue(&chn->user_outgoing);
  2204. SOKOL_ASSERT(slot_id);
  2205. _sfetch_item_t* item = _sfetch_pool_item_lookup(pool, slot_id);
  2206. SOKOL_ASSERT(item && item->callback);
  2207. SOKOL_ASSERT(item->state != _SFETCH_STATE_INITIAL);
  2208. SOKOL_ASSERT(item->state != _SFETCH_STATE_ALLOCATED);
  2209. SOKOL_ASSERT(item->state != _SFETCH_STATE_DISPATCHED);
  2210. SOKOL_ASSERT(item->state != _SFETCH_STATE_FETCHED);
  2211. /* transfer output params from thread- to user-data */
  2212. item->user.fetched_offset = item->thread.fetched_offset;
  2213. item->user.fetched_size = item->thread.fetched_size;
  2214. if (item->user.cancel) {
  2215. _sfetch_cancel_item(item);
  2216. } else {
  2217. item->user.error_code = item->thread.error_code;
  2218. }
  2219. if (item->thread.finished) {
  2220. item->user.finished = true;
  2221. }
  2222. /* state transition */
  2223. if (item->thread.failed) {
  2224. item->state = _SFETCH_STATE_FAILED;
  2225. } else if (item->state == _SFETCH_STATE_FETCHING) {
  2226. item->state = _SFETCH_STATE_FETCHED;
  2227. }
  2228. _sfetch_invoke_response_callback(item);
  2229. /* when the request is finished, free the lane for another request,
  2230. otherwise feed it back into the incoming queue
  2231. */
  2232. if (item->user.finished) {
  2233. _sfetch_ring_enqueue(&chn->free_lanes, item->lane);
  2234. _sfetch_pool_item_free(pool, slot_id);
  2235. } else {
  2236. _sfetch_ring_enqueue(&chn->user_incoming, slot_id);
  2237. }
  2238. }
  2239. }
  2240. _SOKOL_PRIVATE bool _sfetch_validate_request(_sfetch_t* ctx, const sfetch_request_t* req) {
  2241. if (req->channel >= ctx->desc.num_channels) {
  2242. _SFETCH_ERROR(REQUEST_CHANNEL_INDEX_TOO_BIG);
  2243. return false;
  2244. }
  2245. if (!req->path) {
  2246. _SFETCH_ERROR(REQUEST_PATH_IS_NULL);
  2247. return false;
  2248. }
  2249. if (strlen(req->path) >= (SFETCH_MAX_PATH-1)) {
  2250. _SFETCH_ERROR(REQUEST_PATH_TOO_LONG);
  2251. return false;
  2252. }
  2253. if (!req->callback) {
  2254. _SFETCH_ERROR(REQUEST_CALLBACK_MISSING);
  2255. return false;
  2256. }
  2257. if (req->chunk_size > req->buffer.size) {
  2258. _SFETCH_ERROR(REQUEST_CHUNK_SIZE_GREATER_BUFFER_SIZE);
  2259. return false;
  2260. }
  2261. if (req->user_data.ptr && (req->user_data.size == 0)) {
  2262. _SFETCH_ERROR(REQUEST_USERDATA_PTR_IS_SET_BUT_USERDATA_SIZE_IS_NULL);
  2263. return false;
  2264. }
  2265. if (!req->user_data.ptr && (req->user_data.size > 0)) {
  2266. _SFETCH_ERROR(REQUEST_USERDATA_PTR_IS_NULL_BUT_USERDATA_SIZE_IS_NOT);
  2267. return false;
  2268. }
  2269. if (req->user_data.size > SFETCH_MAX_USERDATA_UINT64 * sizeof(uint64_t)) {
  2270. _SFETCH_ERROR(REQUEST_USERDATA_SIZE_TOO_BIG);
  2271. return false;
  2272. }
  2273. return true;
  2274. }
  2275. _SOKOL_PRIVATE sfetch_desc_t _sfetch_desc_defaults(const sfetch_desc_t* desc) {
  2276. SOKOL_ASSERT((desc->allocator.alloc_fn && desc->allocator.free_fn) || (!desc->allocator.alloc_fn && !desc->allocator.free_fn));
  2277. sfetch_desc_t res = *desc;
  2278. res.max_requests = _sfetch_def(desc->max_requests, 128);
  2279. res.num_channels = _sfetch_def(desc->num_channels, 1);
  2280. res.num_lanes = _sfetch_def(desc->num_lanes, 1);
  2281. return res;
  2282. }
  2283. // ██████ ██ ██ ██████ ██ ██ ██████
  2284. // ██ ██ ██ ██ ██ ██ ██ ██ ██
  2285. // ██████ ██ ██ ██████ ██ ██ ██
  2286. // ██ ██ ██ ██ ██ ██ ██ ██
  2287. // ██ ██████ ██████ ███████ ██ ██████
  2288. //
  2289. // >>public
  2290. SOKOL_API_IMPL void sfetch_setup(const sfetch_desc_t* desc_) {
  2291. SOKOL_ASSERT(desc_);
  2292. SOKOL_ASSERT(0 == _sfetch);
  2293. sfetch_desc_t desc = _sfetch_desc_defaults(desc_);
  2294. _sfetch = (_sfetch_t*) _sfetch_malloc_with_allocator(&desc.allocator, sizeof(_sfetch_t));
  2295. SOKOL_ASSERT(_sfetch);
  2296. _sfetch_t* ctx = _sfetch_ctx();
  2297. _sfetch_clear(ctx, sizeof(_sfetch_t));
  2298. ctx->desc = desc;
  2299. ctx->setup = true;
  2300. ctx->valid = true;
  2301. /* replace zero-init items with default values */
  2302. if (ctx->desc.num_channels > SFETCH_MAX_CHANNELS) {
  2303. ctx->desc.num_channels = SFETCH_MAX_CHANNELS;
  2304. _SFETCH_WARN(CLAMPING_NUM_CHANNELS_TO_MAX_CHANNELS);
  2305. }
  2306. /* setup the global request item pool */
  2307. ctx->valid &= _sfetch_pool_init(&ctx->pool, ctx->desc.max_requests);
  2308. /* setup IO channels (one thread per channel) */
  2309. for (uint32_t i = 0; i < ctx->desc.num_channels; i++) {
  2310. ctx->valid &= _sfetch_channel_init(&ctx->chn[i], ctx, ctx->desc.max_requests, ctx->desc.num_lanes, _sfetch_request_handler);
  2311. }
  2312. }
  2313. SOKOL_API_IMPL void sfetch_shutdown(void) {
  2314. _sfetch_t* ctx = _sfetch_ctx();
  2315. SOKOL_ASSERT(ctx && ctx->setup);
  2316. ctx->valid = false;
  2317. /* IO threads must be shutdown first */
  2318. for (uint32_t i = 0; i < ctx->desc.num_channels; i++) {
  2319. if (ctx->chn[i].valid) {
  2320. _sfetch_channel_discard(&ctx->chn[i]);
  2321. }
  2322. }
  2323. _sfetch_pool_discard(&ctx->pool);
  2324. ctx->setup = false;
  2325. _sfetch_free(ctx);
  2326. _sfetch = 0;
  2327. }
  2328. SOKOL_API_IMPL bool sfetch_valid(void) {
  2329. _sfetch_t* ctx = _sfetch_ctx();
  2330. return ctx && ctx->valid;
  2331. }
  2332. SOKOL_API_IMPL sfetch_desc_t sfetch_desc(void) {
  2333. _sfetch_t* ctx = _sfetch_ctx();
  2334. SOKOL_ASSERT(ctx && ctx->valid);
  2335. return ctx->desc;
  2336. }
  2337. SOKOL_API_IMPL int sfetch_max_userdata_bytes(void) {
  2338. return SFETCH_MAX_USERDATA_UINT64 * 8;
  2339. }
  2340. SOKOL_API_IMPL int sfetch_max_path(void) {
  2341. return SFETCH_MAX_PATH;
  2342. }
  2343. SOKOL_API_IMPL bool sfetch_handle_valid(sfetch_handle_t h) {
  2344. _sfetch_t* ctx = _sfetch_ctx();
  2345. SOKOL_ASSERT(ctx && ctx->valid);
  2346. /* shortcut invalid handle */
  2347. if (h.id == 0) {
  2348. return false;
  2349. }
  2350. return 0 != _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2351. }
  2352. SOKOL_API_IMPL sfetch_handle_t sfetch_send(const sfetch_request_t* request) {
  2353. _sfetch_t* ctx = _sfetch_ctx();
  2354. SOKOL_ASSERT(ctx && ctx->setup);
  2355. const sfetch_handle_t invalid_handle = _sfetch_make_handle(0);
  2356. if (!ctx->valid) {
  2357. return invalid_handle;
  2358. }
  2359. if (!_sfetch_validate_request(ctx, request)) {
  2360. return invalid_handle;
  2361. }
  2362. SOKOL_ASSERT(request->channel < ctx->desc.num_channels);
  2363. uint32_t slot_id = _sfetch_pool_item_alloc(&ctx->pool, request);
  2364. if (0 == slot_id) {
  2365. _SFETCH_WARN(REQUEST_POOL_EXHAUSTED);
  2366. return invalid_handle;
  2367. }
  2368. if (!_sfetch_channel_send(&ctx->chn[request->channel], slot_id)) {
  2369. /* send failed because the channels sent-queue overflowed */
  2370. _sfetch_pool_item_free(&ctx->pool, slot_id);
  2371. return invalid_handle;
  2372. }
  2373. return _sfetch_make_handle(slot_id);
  2374. }
  2375. SOKOL_API_IMPL void sfetch_dowork(void) {
  2376. _sfetch_t* ctx = _sfetch_ctx();
  2377. SOKOL_ASSERT(ctx && ctx->setup);
  2378. if (!ctx->valid) {
  2379. return;
  2380. }
  2381. /* we're pumping each channel 2x so that unfinished request items coming out the
  2382. IO threads can be moved back into the IO-thread immediately without
  2383. having to wait a frame
  2384. */
  2385. ctx->in_callback = true;
  2386. for (int pass = 0; pass < 2; pass++) {
  2387. for (uint32_t chn_index = 0; chn_index < ctx->desc.num_channels; chn_index++) {
  2388. _sfetch_channel_dowork(&ctx->chn[chn_index], &ctx->pool);
  2389. }
  2390. }
  2391. ctx->in_callback = false;
  2392. }
  2393. SOKOL_API_IMPL void sfetch_bind_buffer(sfetch_handle_t h, sfetch_range_t buffer) {
  2394. _sfetch_t* ctx = _sfetch_ctx();
  2395. SOKOL_ASSERT(ctx && ctx->valid);
  2396. SOKOL_ASSERT(ctx->in_callback);
  2397. SOKOL_ASSERT(buffer.ptr && (buffer.size > 0));
  2398. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2399. if (item) {
  2400. SOKOL_ASSERT((0 == item->buffer.ptr) && (0 == item->buffer.size));
  2401. item->buffer = buffer;
  2402. }
  2403. }
  2404. SOKOL_API_IMPL void* sfetch_unbind_buffer(sfetch_handle_t h) {
  2405. _sfetch_t* ctx = _sfetch_ctx();
  2406. SOKOL_ASSERT(ctx && ctx->valid);
  2407. SOKOL_ASSERT(ctx->in_callback);
  2408. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2409. if (item) {
  2410. void* prev_buf_ptr = (void*)item->buffer.ptr;
  2411. item->buffer.ptr = 0;
  2412. item->buffer.size = 0;
  2413. return prev_buf_ptr;
  2414. } else {
  2415. return 0;
  2416. }
  2417. }
  2418. SOKOL_API_IMPL void sfetch_pause(sfetch_handle_t h) {
  2419. _sfetch_t* ctx = _sfetch_ctx();
  2420. SOKOL_ASSERT(ctx && ctx->valid);
  2421. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2422. if (item) {
  2423. item->user.pause = true;
  2424. item->user.cont = false;
  2425. }
  2426. }
  2427. SOKOL_API_IMPL void sfetch_continue(sfetch_handle_t h) {
  2428. _sfetch_t* ctx = _sfetch_ctx();
  2429. SOKOL_ASSERT(ctx && ctx->valid);
  2430. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2431. if (item) {
  2432. item->user.cont = true;
  2433. item->user.pause = false;
  2434. }
  2435. }
  2436. SOKOL_API_IMPL void sfetch_cancel(sfetch_handle_t h) {
  2437. _sfetch_t* ctx = _sfetch_ctx();
  2438. SOKOL_ASSERT(ctx && ctx->valid);
  2439. _sfetch_item_t* item = _sfetch_pool_item_lookup(&ctx->pool, h.id);
  2440. if (item) {
  2441. item->user.cont = false;
  2442. item->user.pause = false;
  2443. item->user.cancel = true;
  2444. }
  2445. }
  2446. #ifdef _MSC_VER
  2447. #pragma warning(pop)
  2448. #endif
  2449. #endif /* SOKOL_FETCH_IMPL */