@geastack/host 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/host/fetch.cpp CHANGED
@@ -32,6 +32,7 @@
32
32
  #include "esp_tls.h"
33
33
  #include "freertos/FreeRTOS.h"
34
34
  #include "freertos/idf_additions.h"
35
+ #include "freertos/queue.h"
35
36
  #include "freertos/task.h"
36
37
  #if GEA_EMBEDDED_ENABLE_HTTPS
37
38
  #include "esp_crt_bundle.h"
@@ -86,6 +87,13 @@ struct BodyAccumulator {
86
87
 
87
88
  void reset() { size = 0; } // keep the buffer allocated for reuse across tiles
88
89
 
90
+ void release() {
91
+ gea::framework::memory::Allocator::free(buffer);
92
+ buffer = nullptr;
93
+ capacity = 0;
94
+ size = 0;
95
+ }
96
+
89
97
  void append(const char *data, int len) {
90
98
  if (len <= 0) return;
91
99
  std::size_t need = size + static_cast<std::size_t>(len);
@@ -351,6 +359,12 @@ class FetchHost {
351
359
  static gea::host::FetchResponse fetch(const std::string &url, const gea::host::FetchRequestInit &init) {
352
360
  return FetchResponseBuilder(url, init).get();
353
361
  }
362
+ // Closes the calling task's keep-alive connection and frees its response buffer. A task that is about
363
+ // to exit must call this: both are thread_local, so nothing else would ever close or free them.
364
+ static void releaseTaskState() {
365
+ dropCachedClient();
366
+ g_body.release();
367
+ }
354
368
  };
355
369
 
356
370
  // Streaming multipart upload over a RAW TLS socket (esp_tls), NOT esp_http_client:
@@ -945,10 +959,51 @@ void runAsyncFetchJob(const std::shared_ptr<AsyncFetchJob> &job) {
945
959
  }
946
960
 
947
961
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
948
- void asyncFetchTask(void *raw) {
949
- std::unique_ptr<std::shared_ptr<AsyncFetchJob>> holder(static_cast<std::shared_ptr<AsyncFetchJob> *>(raw));
950
- runAsyncFetchJob(*holder);
951
- vTaskDeleteWithCaps(nullptr);
962
+ constexpr uint32_t kAsyncFetchStackBytes = 32768;
963
+ constexpr UBaseType_t kAsyncFetchQueueDepth = 16;
964
+ constexpr int kAsyncFetchWorkers = 2;
965
+
966
+ // A small pool of long-lived workers runs the async fetches. A task per request needed a fresh contiguous
967
+ // 32 KB stack each time, which a long-running app with fragmented PSRAM eventually cannot find: the
968
+ // request then never starts. The workers' stacks are taken once, at the first request, and a second
969
+ // worker keeps short requests moving while a long upload or download holds the first.
970
+ void asyncFetchWorker(void *raw) {
971
+ auto queue = static_cast<QueueHandle_t>(raw);
972
+ for (;;) {
973
+ std::shared_ptr<AsyncFetchJob> *payload = nullptr;
974
+ if (xQueueReceive(queue, &payload, portMAX_DELAY) != pdTRUE) continue;
975
+ std::unique_ptr<std::shared_ptr<AsyncFetchJob>> holder(payload);
976
+ runAsyncFetchJob(*holder);
977
+ // Drop the job (request body and response) and the keep-alive connection and response buffer
978
+ // between requests, so an idle worker holds no socket and no large buffer.
979
+ holder.reset();
980
+ gea::framework::host::FetchHost::releaseTaskState();
981
+ }
982
+ }
983
+
984
+ // Starts the workers on first use; null while none can be started (the next request tries again).
985
+ QueueHandle_t asyncFetchQueue() {
986
+ static std::mutex startMutex;
987
+ static QueueHandle_t queue = nullptr;
988
+ std::lock_guard<std::mutex> lock(startMutex);
989
+ if (queue) return queue;
990
+
991
+ QueueHandle_t created = xQueueCreate(kAsyncFetchQueueDepth, sizeof(std::shared_ptr<AsyncFetchJob> *));
992
+ if (!created) return nullptr;
993
+
994
+ int started = 0;
995
+ for (int i = 0; i < kAsyncFetchWorkers; ++i) {
996
+ const BaseType_t ok = xTaskCreateWithCaps(asyncFetchWorker, "gea_fetch", kAsyncFetchStackBytes, created, 5,
997
+ nullptr, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
998
+ if (ok == pdPASS) ++started;
999
+ }
1000
+ if (started == 0) {
1001
+ vQueueDelete(created);
1002
+ return nullptr;
1003
+ }
1004
+
1005
+ queue = created;
1006
+ return queue;
952
1007
  }
953
1008
  #endif
954
1009
 
@@ -962,13 +1017,12 @@ double spawnAsyncJob(const std::shared_ptr<AsyncFetchJob> &job) {
962
1017
 
963
1018
  #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED)
964
1019
  auto *payload = new std::shared_ptr<AsyncFetchJob>(job);
965
- const BaseType_t ok = xTaskCreateWithCaps(
966
- asyncFetchTask, "gea_fetch", 32768, payload, 5, nullptr, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
967
- if (ok != pdPASS) {
1020
+ QueueHandle_t queue = asyncFetchQueue();
1021
+ if (!queue || xQueueSend(queue, &payload, 0) != pdTRUE) {
968
1022
  delete payload;
969
1023
  std::lock_guard<std::mutex> lock(asyncFetchMutex());
970
1024
  asyncFetchJobs().erase(id);
971
- ESP_LOGE("gea::host::fetch", "async fetch task create failed; internal largest=%u psram largest=%u",
1025
+ ESP_LOGE("gea::host::fetch", "async fetch not queued (worker missing or queue full); internal largest=%u psram largest=%u",
972
1026
  static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)),
973
1027
  static_cast<unsigned>(heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)));
974
1028
  return 0;
package/host/media.cpp CHANGED
@@ -9,6 +9,7 @@
9
9
  #include <deque>
10
10
  #include <mutex>
11
11
  #include <string>
12
+ #include <sys/stat.h>
12
13
  #include <unordered_map>
13
14
  #include <vector>
14
15
 
@@ -21,7 +22,6 @@
21
22
  #if defined(_WIN32)
22
23
  #include <direct.h>
23
24
  #else
24
- #include <sys/stat.h>
25
25
  #include <sys/types.h>
26
26
  #endif
27
27
 
@@ -55,6 +55,7 @@ struct RecorderState {
55
55
  FILE *file = nullptr;
56
56
  std::size_t samplesWritten = 0;
57
57
  bool writeFailed = false;
58
+ bool defaultPath = false;
58
59
  };
59
60
 
60
61
  std::unordered_map<NativeMediaStreamHandle, StreamState> &streamTable() {
@@ -101,6 +102,7 @@ std::string formatHandleId(const char *prefix, std::uint32_t handle) {
101
102
  constexpr std::size_t kCaptureChunkSamples = 2048;
102
103
  constexpr std::size_t kMaxRingBufferSamples = 16 * kCaptureChunkSamples;
103
104
  constexpr std::size_t kRecorderFlushSamples = kCaptureChunkSamples;
105
+ constexpr unsigned kMaxDefaultRecordingNames = 1000;
104
106
  constexpr double kDefaultRecorderSampleRate = 16000.0;
105
107
 
106
108
  #ifdef ESP_PLATFORM
@@ -224,11 +226,50 @@ double writeWavFile(const std::string &path, const std::vector<std::int16_t> &sa
224
226
  return static_cast<double>(44u + actualDataBytes);
225
227
  }
226
228
 
227
- bool openRecorderFile(RecorderState &recorder) {
229
+ bool recordingPathAssigned(const std::string &path) {
230
+ for (const auto &entry : recorderTable()) {
231
+ if (entry.second.path == path) return true;
232
+ }
233
+ return false;
234
+ }
235
+
236
+ // Recorder handles restart at 1 on every boot, so a name derived from the handle alone would overwrite
237
+ // a recording left from before the reboot. Picks the first name no recorder holds and that is definitely
238
+ // absent from the card; empty when there is none, so recording fails instead of overwriting.
239
+ // Call with mediaMutex() held, so two recorders cannot pick the same name.
240
+ std::string nextDefaultRecordingPath(NativeMediaRecorderHandle handle) {
241
+ gea::platform::storage::ensureMounted();
242
+ char buf[96];
243
+ const auto first = static_cast<unsigned>(handle);
244
+ for (unsigned number = first; number < first + kMaxDefaultRecordingNames; ++number) {
245
+ std::snprintf(buf, sizeof(buf), "/sdcard/recordings/recording_%03u.wav", number);
246
+ if (recordingPathAssigned(buf)) continue;
247
+
248
+ struct stat info;
249
+ if (stat(buf, &info) != 0 && errno == ENOENT) return buf;
250
+ }
251
+ return {};
252
+ }
253
+
254
+ // A default name is claimed by creating the file ("x" fails if it exists), so it never replaces a file that
255
+ // appeared after the name was picked, or this recorder's previous recording; it moves on to the next name.
256
+ std::FILE *openRecorderOutput(RecorderState &recorder, NativeMediaRecorderHandle handle) {
257
+ if (!recorder.defaultPath) return std::fopen(recorder.path.c_str(), "wb");
258
+
259
+ for (;;) {
260
+ std::FILE *file = std::fopen(recorder.path.c_str(), "wbx");
261
+ if (file || errno != EEXIST) return file;
262
+
263
+ recorder.path = nextDefaultRecordingPath(handle);
264
+ if (recorder.path.empty()) return nullptr;
265
+ }
266
+ }
267
+
268
+ bool openRecorderFile(RecorderState &recorder, NativeMediaRecorderHandle handle) {
228
269
  if (recorder.path.empty()) return false;
229
270
  gea::platform::storage::ensureMounted();
230
271
  makeParentDirs(recorder.path);
231
- recorder.file = std::fopen(recorder.path.c_str(), "wb");
272
+ recorder.file = openRecorderOutput(recorder, handle);
232
273
  recorder.samplesWritten = 0;
233
274
  recorder.writeFailed = false;
234
275
  if (!recorder.file) {
@@ -283,6 +324,7 @@ void appendRecorderPcm(RecorderState &recorder, const std::int16_t *samples, std
283
324
 
284
325
  double finalizeRecorderFile(RecorderState &recorder) {
285
326
  flushRecorderPcm(recorder);
327
+ std::vector<std::int16_t>().swap(recorder.pcm); // the entry outlives the recording; free its staging
286
328
  if (!recorder.file) return 0.0;
287
329
  const auto dataBytes = wavDataBytesForSamples(recorder.samplesWritten);
288
330
  const bool patched = patchWavHeader(recorder.file, dataBytes);
@@ -410,26 +452,20 @@ NativeMediaStreamHandle get_user_media_audio() {
410
452
  NativeMediaRecorderHandle create_recorder(NativeMediaStreamHandle stream, const std::string &path, const std::string &mimeType) {
411
453
  const auto recorderHandle = nextRecorderHandle()++;
412
454
  const auto trackHandle = stream_audio_track(stream);
413
- std::string effectivePath = path;
414
- if (effectivePath.empty()) {
415
- char buf[96];
416
- std::snprintf(buf, sizeof(buf), "/sdcard/recordings/recording_%03u.wav", static_cast<unsigned>(recorderHandle));
417
- effectivePath = buf;
418
- }
419
- {
420
- std::lock_guard<std::mutex> lock(mediaMutex());
421
- recorderTable()[recorderHandle] = RecorderState{
422
- formatHandleId("recorder", recorderHandle),
423
- stream,
424
- trackHandle,
425
- "inactive",
426
- effectivePath,
427
- mimeType.empty() ? std::string("audio/wav") : mimeType,
428
- {},
429
- kDefaultRecorderSampleRate,
430
- 1.0,
431
- };
432
- }
455
+ std::lock_guard<std::mutex> lock(mediaMutex());
456
+ const std::string effectivePath = path.empty() ? nextDefaultRecordingPath(recorderHandle) : path;
457
+ recorderTable()[recorderHandle] = RecorderState{
458
+ formatHandleId("recorder", recorderHandle),
459
+ stream,
460
+ trackHandle,
461
+ "inactive",
462
+ effectivePath,
463
+ mimeType.empty() ? std::string("audio/wav") : mimeType,
464
+ {},
465
+ kDefaultRecorderSampleRate,
466
+ 1.0,
467
+ };
468
+ recorderTable()[recorderHandle].defaultPath = path.empty();
433
469
  return recorderHandle;
434
470
  }
435
471
 
@@ -453,7 +489,7 @@ void recorder_start(NativeMediaRecorderHandle handle) {
453
489
  it->second.pcm.clear();
454
490
  it->second.samplesWritten = 0;
455
491
  it->second.writeFailed = false;
456
- if (openRecorderFile(it->second)) {
492
+ if (openRecorderFile(it->second, handle)) {
457
493
  it->second.state = "recording";
458
494
  } else {
459
495
  it->second.state = "inactive";
@@ -549,6 +585,8 @@ void MediaStreamTrack::stop() const {
549
585
  shouldDetach = it->second.readyState != "ended";
550
586
  it->second.readyState = "ended";
551
587
  it->second.enabled = false;
588
+ // The entry stays for readyState lookups; the up-to-64 KB PCM ring buffer is freed now.
589
+ std::deque<std::int16_t>().swap(it->second.ringBuffer);
552
590
  for (auto &entry : recorderTable()) {
553
591
  if (entry.second.track == nativeHandle && entry.second.state == "recording") {
554
592
  entry.second.state = "inactive";
@@ -134,24 +134,42 @@ std::string recorder_mime_type(NativeMediaRecorderHandle handle);
134
134
  void recorder_start(NativeMediaRecorderHandle handle);
135
135
  GeaAudioBlob recorder_stop(NativeMediaRecorderHandle handle);
136
136
 
137
- template <typename Options>
138
- std::string recorder_path_from_options(const Options &options) {
139
- if constexpr (requires { options.path; }) {
140
- return std::string(options.path);
137
+ // Recorder options arrive as a plain struct, or from an app as a generated record that geatsc passes
138
+ // as gea::Optional<gea::Ref<Record>> with gea::Optional<std::string> fields. recorder_option unwraps
139
+ // each layer, so `new MediaRecorder(stream, { path })` from TS is honoured.
140
+ template <typename Value>
141
+ std::string option_string(const Value &value, const std::string &fallback) {
142
+ if constexpr (requires { value.has_value(); *value; }) {
143
+ return value.has_value() ? std::string(*value) : fallback;
141
144
  } else {
142
- return {};
145
+ return std::string(value);
143
146
  }
144
147
  }
145
148
 
146
- template <typename Options>
147
- std::string recorder_mime_from_options(const Options &options) {
148
- if constexpr (requires { options.mimeType; }) {
149
- return std::string(options.mimeType);
149
+ template <typename Options, typename Field>
150
+ std::string recorder_option(const Options &options, Field field, const std::string &fallback) {
151
+ if constexpr (requires { options.has_value(); *options; }) {
152
+ return options.has_value() ? recorder_option(*options, field, fallback) : fallback;
153
+ } else if constexpr (requires { options.get(); *options; }) {
154
+ return options.get() ? recorder_option(*options, field, fallback) : fallback;
155
+ } else if constexpr (requires { field(options); }) {
156
+ return option_string(field(options), fallback);
150
157
  } else {
151
- return "audio/wav";
158
+ return fallback;
152
159
  }
153
160
  }
154
161
 
162
+ template <typename Options>
163
+ std::string recorder_path_from_options(const Options &options) {
164
+ return recorder_option(options, [](const auto &record) -> decltype(record.path) { return record.path; }, {});
165
+ }
166
+
167
+ template <typename Options>
168
+ std::string recorder_mime_from_options(const Options &options) {
169
+ return recorder_option(
170
+ options, [](const auto &record) -> decltype(record.mimeType) { return record.mimeType; }, "audio/wav");
171
+ }
172
+
155
173
  // Overload accepting a MediaStreamConstraints-shaped record (from
156
174
  // `navigator.mediaDevices.getUserMedia({...})`). The fields aren't acted on
157
175
  // yet — there's no per-device picker on the embedded target — but accepting
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@geastack/host",
3
- "version": "0.1.8",
3
+ "version": "0.1.9",
4
4
  "description": "GeaStack host bindings and platform service sources.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {