sokol_fetch.h 100 KB

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