sokol_fetch.h 99 KB

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