@geastack/host 0.1.28 → 0.1.29

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/README.md CHANGED
@@ -32,12 +32,23 @@ Apple builds also compile the Objective-C++ backends listed by the source
32
32
  manifest's `objcxxSources()`: the CoreBluetooth GATT central
33
33
  (`host/bluetooth_central_apple.mm`), Security.framework P-256
34
34
  (`host/crypto_apple.mm`), the AudioToolbox Opus decoder (`host/opus_apple.mm`),
35
- the app data directory (`host/files_apple.mm`) and macOS menu bar mode
36
- (`host/menu_bar_apple.mm`). Each links its system framework through a Mach-O
37
- linker option, so targets need no framework list. Other hosts fall back to the
38
- weak defaults in `host/crypto.cpp`, `host/opus.cpp`, `host/files.cpp` and
35
+ the app data directory (`host/files_apple.mm`), macOS menus
36
+ (`host/menu_apple.mm`) and macOS menu bar mode (`host/menu_bar_apple.mm`).
37
+ Each links its system framework through a Mach-O linker option, so targets
38
+ need no framework list. Other hosts fall back to the weak defaults in
39
+ `host/crypto.cpp`, `host/opus.cpp`, `host/files.cpp`, `host/menu.cpp` and
39
40
  `host/menu_bar.cpp`.
40
41
 
42
+ `Menu` (`host/menu.h`) is the flat handle API under the TS `Menu` and
43
+ `MenuItem` classes: `create`, `item(label, key, modifiers, role, onClick)`,
44
+ `separator`, `append`, `clear`, the item setters, `setSubmenu` and `release`.
45
+ On macOS each menu is an NSMenu and each item an NSMenuItem; a click queues
46
+ the item's handle and `menu::runCallbacks()`, pumped by `Application::frame`
47
+ next to the GPIO callbacks, runs its `onClick` on the next frame. Handles are
48
+ never reused, so a click for a released item is dropped.
49
+ `MenuBar.setMenu(handle)` (-1 for the built-in Quit menu) picks the status
50
+ item's right-click menu.
51
+
41
52
  ## License
42
53
 
43
54
  Apache-2.0. See `LICENSE`.
package/audio_runtime.cpp CHANGED
@@ -7,6 +7,7 @@
7
7
  #include <algorithm>
8
8
  #include <atomic>
9
9
  #include <climits>
10
+ #include <limits>
10
11
  #include <cmath>
11
12
  #include <cstdint>
12
13
  #include <cstdio>
@@ -726,9 +727,25 @@ bool playPcmSync(const std::int16_t *samples, std::size_t sampleCount, int sampl
726
727
  return true;
727
728
  }
728
729
 
730
+ // The last file started through AudioSystem::playFile/playFileFrom. Playback
731
+ // here is synchronous (the call returns once the file has been written out),
732
+ // so a file that played through is finished when the call returns.
733
+ struct FilePlayback {
734
+ double position = 0;
735
+ bool finished = false;
736
+ };
737
+ FilePlayback filePlayback;
738
+
739
+ struct EmbeddedWav {
740
+ unsigned channels = 0;
741
+ std::uint32_t rate = 0;
742
+ const unsigned char *pcm = nullptr;
743
+ std::size_t pcmBytes = 0;
744
+ };
745
+
729
746
  // Play imported WAV assets without opening a filesystem path or writing into
730
747
  // read-only flash. Codec software volume may modify its input buffer.
731
- bool playEmbeddedWav(const unsigned char* bytes, std::size_t length) {
748
+ bool parseEmbeddedWav(const unsigned char* bytes, std::size_t length, EmbeddedWav &wav) {
732
749
  if (length < 12 || std::memcmp(bytes, "RIFF", 4) || std::memcmp(bytes + 8, "WAVE", 4)) return false;
733
750
  const auto le16 = [](const unsigned char* p) { return unsigned(p[0]) | unsigned(p[1]) << 8; };
734
751
  const auto le32 = [](const unsigned char *p) {
@@ -760,6 +777,27 @@ bool playEmbeddedWav(const unsigned char* bytes, std::size_t length) {
760
777
  pcmBytes % (channels * 2)) {
761
778
  return false;
762
779
  }
780
+ wav.channels = channels;
781
+ wav.rate = rate;
782
+ wav.pcm = pcm;
783
+ wav.pcmBytes = pcmBytes;
784
+ return true;
785
+ }
786
+
787
+ double embeddedWavSeconds(const unsigned char* bytes, std::size_t length) {
788
+ EmbeddedWav wav;
789
+ if (!parseEmbeddedWav(bytes, length, wav)) return std::numeric_limits<double>::quiet_NaN();
790
+ return static_cast<double>(wav.pcmBytes / (wav.channels * 2)) / wav.rate;
791
+ }
792
+
793
+ bool playEmbeddedWav(const unsigned char* bytes, std::size_t length, double startSeconds = 0) {
794
+ EmbeddedWav wav;
795
+ if (!parseEmbeddedWav(bytes, length, wav)) return false;
796
+ const auto le16 = [](const unsigned char* p) { return unsigned(p[0]) | unsigned(p[1]) << 8; };
797
+ const unsigned channels = wav.channels;
798
+ const std::uint32_t rate = wav.rate;
799
+ const unsigned char *pcm = wav.pcm;
800
+ const std::size_t pcmBytes = wav.pcmBytes;
763
801
  ExclusivePlaybackScope playbackScope;
764
802
  if (!audio::OutputDriver::open(static_cast<int>(rate), 2, 16)) {
765
803
  return false;
@@ -767,7 +805,8 @@ bool playEmbeddedWav(const unsigned char* bytes, std::size_t length) {
767
805
  OutputCloseScope closeOutput{true};
768
806
  std::vector<std::int16_t> stereo(kPlaybackChunkFrames * 2);
769
807
  const auto frameCount = pcmBytes / (channels * 2);
770
- for (std::size_t frame = 0; frame < frameCount;) {
808
+ const auto skip = startSeconds > 0 ? static_cast<std::size_t>(std::llround(startSeconds * rate)) : std::size_t{0};
809
+ for (std::size_t frame = std::min<std::size_t>(skip, frameCount); frame < frameCount;) {
771
810
  const auto count = std::min<std::size_t>(kPlaybackChunkFrames, frameCount - frame);
772
811
  for (std::size_t index = 0; index < count; ++index) {
773
812
  const auto *source = pcm + (frame + index) * channels * 2;
@@ -789,23 +828,22 @@ bool playEmbeddedWav(const unsigned char* bytes, std::size_t length) {
789
828
  // which OOM-crashed on long recordings — a 20-minute 16 kHz mono clip is
790
829
  // ~38 MB, far past available PSRAM. Parses the header (must be PCM 16-bit),
791
830
  // then reads+plays the data chunk incrementally.
792
- bool streamPcm16File(const std::string &path) {
793
- if (path.empty() || !gea::platform::storage::ensureMounted()) {
794
- return false;
795
- }
796
- FILE *file = std::fopen(path.c_str(), "rb");
797
- if (!file) {
798
- return false;
799
- }
831
+ struct Pcm16WavLayout {
832
+ std::uint16_t channels = 1;
833
+ std::uint32_t sampleRate = 0;
834
+ long dataStart = -1;
835
+ std::uint32_t dataSize = 0;
836
+ };
800
837
 
801
- bool ok = false;
802
- do {
838
+ // Walk the RIFF chunks of a 16-bit PCM WAV up to its data chunk.
839
+ bool readPcm16WavLayout(FILE *file, Pcm16WavLayout &layout) {
840
+ {
803
841
  if (!readTag(file, "RIFF")) {
804
- break;
842
+ return false;
805
843
  }
806
844
  (void)readLe32(file);
807
845
  if (!readTag(file, "WAVE")) {
808
- break;
846
+ return false;
809
847
  }
810
848
 
811
849
  std::uint16_t audioFormat = 0;
@@ -842,11 +880,48 @@ bool streamPcm16File(const std::string &path) {
842
880
  }
843
881
 
844
882
  if (audioFormat != 1 || bitsPerSample != 16 || dataStart < 0 || dataSize < 2)
883
+ return false;
884
+ layout.channels = channels == 0 ? 1 : channels;
885
+ layout.sampleRate = sampleRate == 0 ? kSampleRate : sampleRate;
886
+ layout.dataStart = dataStart;
887
+ layout.dataSize = dataSize;
888
+ return true;
889
+ }
890
+ }
891
+
892
+ double pcm16FileSeconds(const std::string &path) {
893
+ const double unknown = std::numeric_limits<double>::quiet_NaN();
894
+ if (path.empty() || !gea::platform::storage::ensureMounted()) return unknown;
895
+ FILE *file = std::fopen(gea::platform::storage::hostPath(path).c_str(), "rb");
896
+ if (!file) return unknown;
897
+ Pcm16WavLayout layout;
898
+ const bool ok = readPcm16WavLayout(file, layout);
899
+ std::fclose(file);
900
+ if (!ok) return unknown;
901
+ return static_cast<double>(layout.dataSize / (sizeof(std::int16_t) * layout.channels)) / layout.sampleRate;
902
+ }
903
+
904
+ bool streamPcm16File(const std::string &path, double startSeconds = 0) {
905
+ if (path.empty() || !gea::platform::storage::ensureMounted()) {
906
+ return false;
907
+ }
908
+ FILE *file = std::fopen(gea::platform::storage::hostPath(path).c_str(), "rb");
909
+ if (!file) {
910
+ return false;
911
+ }
912
+
913
+ bool ok = false;
914
+ do {
915
+ Pcm16WavLayout layout;
916
+ if (!readPcm16WavLayout(file, layout))
845
917
  break;
846
- if (channels == 0)
847
- channels = 1;
848
- const int outSampleRate = sampleRate == 0 ? kSampleRate : static_cast<int>(sampleRate);
849
- if (std::fseek(file, dataStart, SEEK_SET) != 0)
918
+ const std::uint16_t channels = layout.channels;
919
+ const int outSampleRate = static_cast<int>(layout.sampleRate);
920
+ const std::size_t totalFrames = layout.dataSize / (sizeof(std::int16_t) * channels);
921
+ const std::size_t skip = std::min<std::size_t>(
922
+ totalFrames,
923
+ startSeconds > 0 ? static_cast<std::size_t>(std::llround(startSeconds * outSampleRate)) : 0);
924
+ if (std::fseek(file, layout.dataStart + static_cast<long>(skip * sizeof(std::int16_t) * channels), SEEK_SET) != 0)
850
925
  break;
851
926
 
852
927
  ExclusivePlaybackScope playbackScope;
@@ -855,7 +930,7 @@ bool streamPcm16File(const std::string &path) {
855
930
  OutputCloseScope closeOutput{true};
856
931
 
857
932
  const std::size_t ch = static_cast<std::size_t>(channels);
858
- std::size_t framesLeft = dataSize / (sizeof(std::int16_t) * ch);
933
+ std::size_t framesLeft = totalFrames - skip;
859
934
  std::vector<std::int16_t> in(kPlaybackChunkFrames * ch);
860
935
  std::vector<std::int16_t> stereo(kPlaybackChunkFrames * 2);
861
936
  bool wrote = true;
@@ -973,29 +1048,56 @@ void audio::AudioSystem::setVolume(int volumePercent) {
973
1048
  AudioEngine::instance().setVolume(volumePercent);
974
1049
  }
975
1050
 
976
- bool audio::AudioSystem::playFile(const std::string &path) {
1051
+ namespace {
1052
+ bool lookupEmbeddedAsset(const std::string &path, const unsigned char *&bytes, unsigned long &length) {
1053
+ const auto *loaded = gea::framework::program::loaded();
1054
+ return loaded ? (loaded->assetLookup && loaded->assetLookup(path.c_str(), &bytes, &length))
1055
+ : (gea_embedded_asset_lookup && gea_embedded_asset_lookup(path.c_str(), &bytes, &length));
1056
+ }
1057
+ } // namespace
1058
+
1059
+ bool audio::AudioSystem::playFile(const std::string &path) { return playFileFrom(path, 0); }
1060
+
1061
+ // Synchronous: returns once the file has been written out from `seconds` on,
1062
+ // so a successful call leaves the file finished at its end.
1063
+ bool audio::AudioSystem::playFileFrom(const std::string &path, double seconds) {
1064
+ filePlayback = FilePlayback{};
1065
+ const double length = playbackDuration(path);
977
1066
  // Stream from disk in bounded chunks — never load the whole file (a long
978
1067
  // recording is tens of MB and would exhaust PSRAM).
979
1068
  const unsigned char* embedded = nullptr;
980
1069
  unsigned long embeddedBytes = 0;
981
- const auto *loaded = gea::framework::program::loaded();
982
- const bool bundled = loaded ? (loaded->assetLookup && loaded->assetLookup(path.c_str(), &embedded, &embeddedBytes))
983
- : (gea_embedded_asset_lookup && gea_embedded_asset_lookup(path.c_str(), &embedded, &embeddedBytes));
984
- if (bundled) {
985
- return playEmbeddedWav(embedded, embeddedBytes);
1070
+ bool ok = false;
1071
+ if (lookupEmbeddedAsset(path, embedded, embeddedBytes)) {
1072
+ ok = playEmbeddedWav(embedded, embeddedBytes, seconds);
1073
+ } else {
1074
+ ok = streamPcm16File(path, seconds);
1075
+ if (!ok) ESP_LOGW("gea_audio", "Unable to play WAV file: %s", path.c_str());
986
1076
  }
987
- if (!streamPcm16File(path)) {
988
- ESP_LOGW("gea_audio", "Unable to play WAV file: %s", path.c_str());
989
- return false;
1077
+ if (ok) {
1078
+ filePlayback.finished = true;
1079
+ filePlayback.position = std::isfinite(length) ? length : 0;
990
1080
  }
991
- return true;
1081
+ return ok;
992
1082
  }
993
1083
 
1084
+ double audio::AudioSystem::playbackPosition() { return filePlayback.position; }
1085
+
1086
+ double audio::AudioSystem::playbackDuration(const std::string &path) {
1087
+ const unsigned char* embedded = nullptr;
1088
+ unsigned long embeddedBytes = 0;
1089
+ if (lookupEmbeddedAsset(path, embedded, embeddedBytes)) return embeddedWavSeconds(embedded, embeddedBytes);
1090
+ return pcm16FileSeconds(path);
1091
+ }
1092
+
1093
+ bool audio::AudioSystem::playbackFinished() { return filePlayback.finished; }
1094
+
994
1095
  bool audio::AudioSystem::playPcm(const std::int16_t *samples, std::size_t sampleCount, int sampleRate, int channels) {
995
1096
  return playPcmSync(samples, sampleCount, sampleRate, channels);
996
1097
  }
997
1098
 
998
1099
  void audio::AudioSystem::stopPlayback() {
1100
+ filePlayback.finished = false;
999
1101
  AudioEngine::instance().stopPlayback();
1000
1102
  }
1001
1103
  void audio::AudioSystem::flushPlayback() {
package/host/audio.cpp CHANGED
@@ -8,6 +8,7 @@
8
8
  #include <mutex>
9
9
  #include <chrono>
10
10
  #include "gea/embedded-host.h"
11
+ #include "platform/file_cache.h"
11
12
  #include "ui/document.h" // host/audio.cpp HTMLAudioElement bridge (entangled — moves to elements)
12
13
 
13
14
  #include <atomic>
@@ -32,6 +33,12 @@ __attribute__((weak)) void AudioSystem::stopPcmStream(std::uint64_t) {}
32
33
  __attribute__((weak)) bool AudioSystem::pcmStreamSettled(std::uint64_t) { return false; }
33
34
  __attribute__((weak)) double AudioSystem::processingLatency() { return 0; }
34
35
  __attribute__((weak)) double AudioSystem::outputLatency() { return 0; }
36
+ // Backends without a seekable file player: play from the start, report no
37
+ // position, an unknown length and no end.
38
+ __attribute__((weak)) bool AudioSystem::playFileFrom(const std::string &path, double) { return playFile(path); }
39
+ __attribute__((weak)) double AudioSystem::playbackPosition() { return 0; }
40
+ __attribute__((weak)) double AudioSystem::playbackDuration(const std::string &) { return std::numeric_limits<double>::quiet_NaN(); }
41
+ __attribute__((weak)) bool AudioSystem::playbackFinished() { return false; }
35
42
  }
36
43
 
37
44
  namespace gea::framework::host {
@@ -286,7 +293,70 @@ struct HTMLAudioElement::State {
286
293
  std::shared_ptr<media::TrackPcmReader> reader;
287
294
  std::shared_ptr<AudioLevelMeter> level = std::make_shared<AudioLevelMeter>();
288
295
  bool autoplay = false, paused = true, freshSource = true, draining = false;
289
- ~State() { if (output) gea::platform::audio::AudioSystem::stopPcmStream(output); }
296
+ // File playback (`src`). The platform plays one file at a time, so the
297
+ // element that started it last owns the live position; every other element
298
+ // reads its held `position`.
299
+ double position = 0;
300
+ bool ended = false;
301
+ std::string fileSrc;
302
+ bool lengthKnown = false;
303
+ double length = std::numeric_limits<double>::quiet_NaN();
304
+
305
+ static State*& fileOwner() {
306
+ static State* owner = nullptr;
307
+ return owner;
308
+ }
309
+ bool playingFile() const { return !paused && !output && !source.nativeHandle && fileOwner() == this; }
310
+ double fileLength() {
311
+ if (fileSrc.empty()) return std::numeric_limits<double>::quiet_NaN();
312
+ if (!lengthKnown) {
313
+ length = gea::platform::audio::AudioSystem::playbackDuration(gea::platform::storage::hostPath(fileSrc));
314
+ lengthKnown = true;
315
+ }
316
+ return length;
317
+ }
318
+ double clampToLength(double seconds) {
319
+ if (!(seconds > 0)) return 0;
320
+ const double total = fileLength();
321
+ return std::isfinite(total) && seconds > total ? total : seconds;
322
+ }
323
+ // The platform's file finished: this element ends where the file does.
324
+ void syncFile() {
325
+ if (!playingFile() || !gea::platform::audio::AudioSystem::playbackFinished()) return;
326
+ position = clampToLength(gea::platform::audio::AudioSystem::playbackPosition());
327
+ const double total = fileLength();
328
+ if (std::isfinite(total)) position = total;
329
+ paused = true;
330
+ ended = true;
331
+ fileOwner() = nullptr;
332
+ }
333
+ // Hold the live position and give up the platform player, stopping it
334
+ // only when asked (another element taking it over replaces it instead).
335
+ void releaseFile(bool stop) {
336
+ if (fileOwner() != this) return;
337
+ syncFile();
338
+ if (playingFile()) {
339
+ position = clampToLength(gea::platform::audio::AudioSystem::playbackPosition());
340
+ if (stop) gea::platform::audio::AudioSystem::stopPlayback();
341
+ paused = true;
342
+ }
343
+ fileOwner() = nullptr;
344
+ }
345
+ // A new src starts over: no position, no end, length unread.
346
+ void observeSrc(const std::string& current) {
347
+ if (current == fileSrc) return;
348
+ releaseFile(true);
349
+ fileSrc = current;
350
+ position = 0;
351
+ ended = false;
352
+ lengthKnown = false;
353
+ }
354
+ ~State() {
355
+ if (output) gea::platform::audio::AudioSystem::stopPcmStream(output);
356
+ // A dropped element keeps sounding (`new Audio(src).play()` is a common
357
+ // fire-and-forget); it only stops owning the position.
358
+ if (fileOwner() == this) fileOwner() = nullptr;
359
+ }
290
360
  };
291
361
 
292
362
  HTMLAudioElement HTMLAudioElement::create() {
@@ -321,6 +391,7 @@ void HTMLAudioElement::setSrc(const std::string &src) {
321
391
  if (!state_) throw std::logic_error("null HTMLAudioElement");
322
392
  if (state_->nodeId >= 0) gea::embedded::ui::NodeHandle(state_->nodeId).setAttribute("src", src.c_str());
323
393
  state_->src = src;
394
+ state_->observeSrc(src);
324
395
  }
325
396
 
326
397
  bool HTMLAudioElement::play() const {
@@ -346,8 +417,20 @@ bool HTMLAudioElement::play() const {
346
417
  state_->paused = false;
347
418
  return true;
348
419
  }
349
- const bool ok = gea::platform::audio::AudioSystem::playFile(src());
420
+ state_->observeSrc(src());
421
+ state_->syncFile();
422
+ if (state_->playingFile()) return true;
423
+ if (state_->ended) {
424
+ state_->position = 0;
425
+ state_->ended = false;
426
+ }
427
+ if (auto* owner = State::fileOwner(); owner && owner != state_.get()) owner->releaseFile(false);
428
+ // Re-read the length on the next query: the file may have been rewritten.
429
+ state_->lengthKnown = false;
430
+ const bool ok = gea::platform::audio::AudioSystem::playFileFrom(
431
+ gea::platform::storage::hostPath(state_->fileSrc), state_->position);
350
432
  state_->paused = !ok;
433
+ if (ok) State::fileOwner() = state_.get();
351
434
  return ok;
352
435
  }
353
436
 
@@ -362,7 +445,7 @@ void HTMLAudioElement::pause() const {
362
445
  #endif
363
446
  gea::platform::audio::AudioSystem::stopPcmStream(state_->output);
364
447
  state_->output = 0;
365
- } else if (!state_->paused && !state_->source.nativeHandle) gea::platform::audio::AudioSystem::stopPlayback();
448
+ } else if (!state_->source.nativeHandle) state_->releaseFile(true);
366
449
  // Discard the cancelled reply at the interruption boundary, not when
367
450
  // play() later resumes: new RTP can precede its SCTP response event.
368
451
  if (state_->reader) state_->reader->discardBuffered();
@@ -407,7 +490,52 @@ void HTMLAudioElement::setSrcObject(MediaStream stream) const {
407
490
  if (stream.nativeHandle && resume) (void)play();
408
491
  }
409
492
  bool HTMLAudioElement::autoplay() const { return state_ && state_->autoplay; }
410
- bool HTMLAudioElement::paused() const { return !state_ || state_->paused; }
493
+ bool HTMLAudioElement::paused() const {
494
+ if (!state_) return true;
495
+ state_->syncFile();
496
+ return state_->paused;
497
+ }
498
+ double HTMLAudioElement::currentTime() const {
499
+ if (!state_ || state_->source.nativeHandle) return 0;
500
+ state_->observeSrc(src());
501
+ state_->syncFile();
502
+ if (state_->playingFile())
503
+ return state_->clampToLength(gea::platform::audio::AudioSystem::playbackPosition());
504
+ return state_->position;
505
+ }
506
+ void HTMLAudioElement::setCurrentTime(double seconds) const {
507
+ if (!state_) throw std::logic_error("null HTMLAudioElement");
508
+ if (std::isnan(seconds) || state_->source.nativeHandle) return;
509
+ state_->observeSrc(src());
510
+ state_->syncFile();
511
+ const double target = state_->clampToLength(seconds);
512
+ const double total = state_->fileLength();
513
+ const bool atEnd = std::isfinite(total) && target >= total;
514
+ state_->position = target;
515
+ state_->ended = atEnd;
516
+ if (!state_->playingFile()) return;
517
+ if (atEnd) {
518
+ gea::platform::audio::AudioSystem::stopPlayback();
519
+ state_->paused = true;
520
+ State::fileOwner() = nullptr;
521
+ } else if (!gea::platform::audio::AudioSystem::playFileFrom(
522
+ gea::platform::storage::hostPath(state_->fileSrc), target)) {
523
+ state_->paused = true;
524
+ State::fileOwner() = nullptr;
525
+ }
526
+ }
527
+ double HTMLAudioElement::duration() const {
528
+ if (!state_) return std::numeric_limits<double>::quiet_NaN();
529
+ if (state_->source.nativeHandle) return std::numeric_limits<double>::infinity();
530
+ state_->observeSrc(src());
531
+ return state_->fileLength();
532
+ }
533
+ bool HTMLAudioElement::ended() const {
534
+ if (!state_) return false;
535
+ state_->observeSrc(src());
536
+ state_->syncFile();
537
+ return state_->ended;
538
+ }
411
539
  void HTMLAudioElement::setAutoplay(bool enabled) const {
412
540
  if (!state_) throw std::logic_error("null HTMLAudioElement");
413
541
  state_->autoplay = enabled;
package/host/fetch.cpp CHANGED
@@ -728,8 +728,11 @@ gea::host::FetchResponse gea::host::downloadFile(const std::string &url, const s
728
728
 
729
729
  #include <algorithm>
730
730
  #include <cctype>
731
+ #include <cstdio>
731
732
  #include <cstdlib>
732
733
  #include <sstream>
734
+
735
+ #include "platform/file_cache.h"
733
736
  #ifndef __EMSCRIPTEN__
734
737
  #include <thread>
735
738
  #endif
@@ -912,18 +915,60 @@ gea::host::FetchResponse gea::host::fetch(const std::string &url, const FetchReq
912
915
  return gea::framework::host::FetchHost::fetch(url, init);
913
916
  }
914
917
 
915
- // Off-device (browser/sim/tests): no streaming upload from a device file path.
918
+ #ifdef __EMSCRIPTEN__
919
+ // The browser has no device files to stream.
916
920
  gea::host::FetchResponse gea::host::uploadFile(const std::string &, const std::string &,
917
921
  const std::string &, const std::string &,
918
922
  const std::string &, const std::string &) {
919
923
  return gea::host::FetchResponse{};
920
924
  }
921
925
 
922
- // Off-device: no streaming download to a device file path.
923
926
  gea::host::FetchResponse gea::host::downloadFile(const std::string &, const std::string &,
924
927
  const std::string &) {
925
928
  return gea::host::FetchResponse{};
926
929
  }
930
+ #else
931
+ // A desktop host has the memory to hold the file, so both go through the
932
+ // ordinary fetch backend; the path is resolved like every other file path.
933
+ gea::host::FetchResponse gea::host::uploadFile(const std::string &url, const std::string &authorization,
934
+ const std::string &contentType, const std::string &prefix,
935
+ const std::string &filePath, const std::string &suffix) {
936
+ gea::host::FetchResponse result{};
937
+ std::FILE *file = std::fopen(gea::platform::storage::hostPath(filePath).c_str(), "rb");
938
+ if (!file) {
939
+ result.status = -11; // same code as a board that cannot open the file
940
+ return result;
941
+ }
942
+ gea::host::FetchRequestInit init;
943
+ init.method = "POST";
944
+ init.headers["Accept"] = "*/*";
945
+ if (!authorization.empty()) init.headers["Authorization"] = authorization;
946
+ if (!contentType.empty()) init.headers["Content-Type"] = contentType;
947
+ init.body = prefix;
948
+ char chunk[64 * 1024];
949
+ std::size_t got = 0;
950
+ while ((got = std::fread(chunk, 1, sizeof(chunk), file)) > 0) init.body.append(chunk, got);
951
+ std::fclose(file);
952
+ init.body += suffix;
953
+ return gea::host::fetch(url, init);
954
+ }
955
+
956
+ gea::host::FetchResponse gea::host::downloadFile(const std::string &url, const std::string &authorization,
957
+ const std::string &destPath) {
958
+ gea::host::FetchRequestInit init;
959
+ init.headers["Accept"] = "*/*";
960
+ if (!authorization.empty()) init.headers["Authorization"] = authorization;
961
+ gea::host::FetchResponse result = gea::host::fetch(url, init);
962
+ if (!result.ok) return result;
963
+ gea::host::FetchResponse written = result;
964
+ written.body.clear();
965
+ std::FILE *file = std::fopen(gea::platform::storage::hostPath(destPath).c_str(), "wb");
966
+ const bool saved = file && std::fwrite(result.body.data(), 1, result.body.size(), file) == result.body.size();
967
+ if (file) std::fclose(file);
968
+ if (!saved) written.ok = false;
969
+ return written;
970
+ }
971
+ #endif
927
972
 
928
973
  #endif // ESP_PLATFORM && network capability
929
974
 
package/host/files.cpp CHANGED
@@ -16,6 +16,7 @@
16
16
  #include <unistd.h>
17
17
  #endif
18
18
 
19
+ #include "platform/file_cache.h"
19
20
  #include "platform/internal_stack.h"
20
21
 
21
22
  namespace gea::host {
@@ -51,6 +52,9 @@ bool seek(std::FILE *file, double offset) {
51
52
  #endif
52
53
  }
53
54
 
55
+ // Where `path` lives on this host (a desktop app's "/sdcard" is a folder of its own).
56
+ std::string at(const std::string &path) { return gea::platform::storage::hostPath(path); }
57
+
54
58
  template <typename Action>
55
59
  auto onStack(Action action) -> decltype(action()) {
56
60
  decltype(action()) result{};
@@ -70,20 +74,20 @@ std::string FilesFacade::dataDirectory() const {
70
74
  }
71
75
 
72
76
  bool FilesFacade::makeDirectory(const std::string &path) const {
73
- return onStack([&] { return makeAll(path); });
77
+ return onStack([&] { return makeAll(at(path)); });
74
78
  }
75
79
 
76
80
  bool FilesFacade::exists(const std::string &path) const {
77
81
  return onStack([&] {
78
82
  struct stat info {};
79
- return !path.empty() && ::stat(path.c_str(), &info) == 0;
83
+ return !path.empty() && ::stat(at(path).c_str(), &info) == 0;
80
84
  });
81
85
  }
82
86
 
83
87
  double FilesFacade::size(const std::string &path) const {
84
88
  return onStack([&] {
85
89
  struct stat info {};
86
- if (path.empty() || ::stat(path.c_str(), &info) != 0 || S_ISDIR(info.st_mode)) return -1.0;
90
+ if (path.empty() || ::stat(at(path).c_str(), &info) != 0 || S_ISDIR(info.st_mode)) return -1.0;
87
91
  return static_cast<double>(info.st_size);
88
92
  });
89
93
  }
@@ -92,7 +96,7 @@ std::vector<std::uint8_t> FilesFacade::read(const std::string &path, double offs
92
96
  return onStack([&] {
93
97
  std::vector<std::uint8_t> bytes;
94
98
  if (path.empty() || offset < 0 || length <= 0) return bytes;
95
- std::FILE *file = std::fopen(path.c_str(), "rb");
99
+ std::FILE *file = std::fopen(at(path).c_str(), "rb");
96
100
  if (!file) return bytes;
97
101
  if (seek(file, offset)) {
98
102
  bytes.resize(static_cast<std::size_t>(length));
@@ -105,7 +109,7 @@ std::vector<std::uint8_t> FilesFacade::read(const std::string &path, double offs
105
109
 
106
110
  bool FilesFacade::append(const std::string &path, const std::vector<std::uint8_t> &bytes) const {
107
111
  return onStack([&] {
108
- std::FILE *file = path.empty() ? nullptr : std::fopen(path.c_str(), "ab");
112
+ std::FILE *file = path.empty() ? nullptr : std::fopen(at(path).c_str(), "ab");
109
113
  if (!file) return false;
110
114
  const std::size_t written = bytes.empty() ? 0 : std::fwrite(bytes.data(), 1, bytes.size(), file);
111
115
  const bool closed = std::fclose(file) == 0;
@@ -116,8 +120,9 @@ bool FilesFacade::append(const std::string &path, const std::vector<std::uint8_t
116
120
  bool FilesFacade::writeAt(const std::string &path, double offset, const std::vector<std::uint8_t> &bytes) const {
117
121
  return onStack([&] {
118
122
  if (path.empty() || offset < 0) return false;
119
- std::FILE *file = std::fopen(path.c_str(), "r+b");
120
- if (!file) file = std::fopen(path.c_str(), "w+b");
123
+ const std::string host = at(path);
124
+ std::FILE *file = std::fopen(host.c_str(), "r+b");
125
+ if (!file) file = std::fopen(host.c_str(), "w+b");
121
126
  if (!file) return false;
122
127
  bool ok = seek(file, offset);
123
128
  if (ok && !bytes.empty()) ok = std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size();
@@ -129,28 +134,28 @@ bool FilesFacade::truncate(const std::string &path, double size) const {
129
134
  return onStack([&] {
130
135
  if (path.empty() || size < 0) return false;
131
136
  #if defined(_WIN32)
132
- std::FILE *file = std::fopen(path.c_str(), "r+b");
137
+ std::FILE *file = std::fopen(at(path).c_str(), "r+b");
133
138
  if (!file) return false;
134
139
  const bool ok = _chsize_s(_fileno(file), static_cast<long long>(size)) == 0;
135
140
  std::fclose(file);
136
141
  return ok;
137
142
  #else
138
- return ::truncate(path.c_str(), static_cast<off_t>(size)) == 0;
143
+ return ::truncate(at(path).c_str(), static_cast<off_t>(size)) == 0;
139
144
  #endif
140
145
  });
141
146
  }
142
147
 
143
148
  bool FilesFacade::remove(const std::string &path) const {
144
- return onStack([&] { return !path.empty() && std::remove(path.c_str()) == 0; });
149
+ return onStack([&] { return !path.empty() && std::remove(at(path).c_str()) == 0; });
145
150
  }
146
151
 
147
152
  bool FilesFacade::rename(const std::string &from, const std::string &to) const {
148
153
  return onStack([&] {
149
154
  if (from.empty() || to.empty()) return false;
150
155
  #if defined(_WIN32)
151
- std::remove(to.c_str());
156
+ std::remove(at(to).c_str());
152
157
  #endif
153
- return std::rename(from.c_str(), to.c_str()) == 0;
158
+ return std::rename(at(from).c_str(), at(to).c_str()) == 0;
154
159
  });
155
160
  }
156
161