@geastack/host 0.1.10 → 0.1.12

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.
Files changed (47) hide show
  1. package/audio_runtime.cpp +97 -3
  2. package/host/audio.cpp +395 -10
  3. package/host/audio_worklet.cpp +611 -0
  4. package/host/fetch.cpp +17 -0
  5. package/host/media.cpp +308 -27
  6. package/host/mjpeg.cpp +205 -0
  7. package/host/rtc.cpp +458 -48
  8. package/host/rtc_esp.cpp +897 -75
  9. package/host/rtc_objects.inc +246 -0
  10. package/host/timers.cpp +18 -0
  11. package/host/video.cpp +152 -0
  12. package/host/websocket.cpp +623 -72
  13. package/host/worker.cpp +621 -0
  14. package/include/gea/audio-worklet-runtime.h +165 -0
  15. package/include/gea/base64-runtime.h +26 -0
  16. package/include/gea/embedded-host.h +1 -0
  17. package/include/gea/worker-runtime.h +189 -0
  18. package/include/host/audio.h +94 -6
  19. package/include/host/audio_level.h +37 -0
  20. package/include/host/audio_worklet.h +103 -0
  21. package/include/host/h264_layout.h +170 -0
  22. package/include/host/media.h +67 -0
  23. package/include/host/mjpeg.h +23 -0
  24. package/include/host/mjpeg_parser.h +126 -0
  25. package/include/host/pcm_stream.h +122 -0
  26. package/include/host/rtc.h +38 -20
  27. package/include/host/rtc_h264.h +76 -0
  28. package/include/host/rtc_ice_candidate.h +141 -0
  29. package/include/host/rtc_opus.h +136 -0
  30. package/include/host/rtc_receive_sdp.h +245 -0
  31. package/include/host/rtc_rtp.h +170 -0
  32. package/include/host/rtc_sdp.h +71 -0
  33. package/include/host/rtc_types.h +166 -0
  34. package/include/host/rtc_vp8.h +115 -0
  35. package/include/host/rtc_vp8_capture.h +129 -0
  36. package/include/host/rtc_vp8_decoder.h +169 -0
  37. package/include/host/rtc_vp8_receiver.h +55 -0
  38. package/include/host/timers.h +3 -2
  39. package/include/host/video.h +39 -0
  40. package/include/host/video_color.h +90 -0
  41. package/include/host/video_frame_pool.h +50 -0
  42. package/include/host/video_pixels.h +178 -0
  43. package/include/host/websocket.h +20 -1
  44. package/include/host/websocket_message.h +66 -0
  45. package/include/host/worker.h +131 -0
  46. package/package.json +1 -1
  47. package/services/diagnostics.cpp +120 -19
package/host/media.cpp CHANGED
@@ -1,5 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  #include "host/media.h"
3
+ #include "host/pcm_stream.h"
3
4
 
4
5
  #include <algorithm>
5
6
  #include <atomic>
@@ -8,9 +9,12 @@
8
9
  #include <cstdio>
9
10
  #include <deque>
10
11
  #include <mutex>
12
+ #include <optional>
11
13
  #include <string>
14
+ #include <stdexcept>
12
15
  #include <sys/stat.h>
13
16
  #include <unordered_map>
17
+ #include <utility>
14
18
  #include <vector>
15
19
 
16
20
  #include "platform/file_cache.h"
@@ -29,17 +33,69 @@ namespace gea::host {
29
33
 
30
34
  namespace {
31
35
 
36
+ struct PcmCursor {
37
+ std::uint64_t next = 0;
38
+ std::uint64_t dropped = 0;
39
+ std::optional<std::uint64_t> end;
40
+ };
41
+
42
+ using PcmBuffer = std::deque<std::int16_t, pcm::QueueAllocator<std::int16_t>>;
43
+
32
44
  struct TrackState {
33
45
  std::string id;
34
46
  std::string kind = "audio";
35
47
  std::string readyState = "live";
36
48
  bool enabled = true;
37
- std::deque<std::int16_t> ringBuffer;
49
+ PcmBuffer ringBuffer;
50
+ bool capture = true;
51
+ std::uint64_t bufferStart = 0;
52
+ PcmCursor transportCursor;
53
+ bool transportCursorActive = false;
54
+ std::uint64_t nextReader = 1;
55
+ std::unordered_map<std::uint64_t, PcmCursor> readers;
56
+ std::shared_ptr<const media::VideoFrame> videoFrame;
57
+ std::uint64_t videoSequence = 0;
38
58
  };
39
59
 
60
+ void clearTrackPcm(TrackState &track) {
61
+ track.bufferStart += track.ringBuffer.size();
62
+ PcmBuffer().swap(track.ringBuffer);
63
+ track.transportCursor.next = track.bufferStart;
64
+ for (auto &[id, reader] : track.readers) reader.next = track.bufferStart;
65
+ }
66
+
67
+ void trimTrackPcm(TrackState &track) {
68
+ if (!track.transportCursorActive && track.readers.empty()) return;
69
+ auto consumed = track.transportCursorActive ? track.transportCursor.next : track.bufferStart + track.ringBuffer.size();
70
+ for (const auto &[id, reader] : track.readers) consumed = std::min(consumed, reader.next);
71
+ while (!track.ringBuffer.empty() && track.bufferStart < consumed) {
72
+ track.ringBuffer.pop_front();
73
+ ++track.bufferStart;
74
+ }
75
+ }
76
+
77
+ std::size_t readTrackPcm(TrackState &track, PcmCursor &cursor, std::int16_t *samples, std::size_t count) {
78
+ if (!samples || !count) return 0;
79
+ if (cursor.next < track.bufferStart) {
80
+ cursor.dropped += track.bufferStart - cursor.next;
81
+ cursor.next = track.bufferStart;
82
+ }
83
+ const auto offset = static_cast<std::size_t>(cursor.next - track.bufferStart);
84
+ if (cursor.end) {
85
+ if (cursor.next >= *cursor.end) return 0;
86
+ count = std::min(count, static_cast<std::size_t>(*cursor.end - cursor.next));
87
+ }
88
+ const auto copied = std::min(count, track.ringBuffer.size() - offset);
89
+ for (std::size_t i = 0; i < copied; ++i) samples[i] = track.ringBuffer[offset + i];
90
+ cursor.next += copied;
91
+ trimTrackPcm(track);
92
+ return copied;
93
+ }
94
+
40
95
  struct StreamState {
41
96
  std::string id;
42
- NativeMediaTrackHandle audioTrack = 0;
97
+ std::vector<NativeMediaTrackHandle> tracks;
98
+ NativeMediaTrackHandle ownedTrack = 0;
43
99
  };
44
100
 
45
101
  struct RecorderState {
@@ -100,7 +156,9 @@ std::string formatHandleId(const char *prefix, std::uint32_t handle) {
100
156
  }
101
157
 
102
158
  constexpr std::size_t kCaptureChunkSamples = 2048;
103
- constexpr std::size_t kMaxRingBufferSamples = 16 * kCaptureChunkSamples;
159
+ // Eight seconds at the capture driver's 16 kHz. Storage grows only when a
160
+ // consumer falls behind and uses PSRAM rather than starving I2S DMA memory.
161
+ constexpr std::size_t kMaxRingBufferSamples = 8 * 16000;
104
162
  constexpr std::size_t kRecorderFlushSamples = kCaptureChunkSamples;
105
163
  constexpr unsigned kMaxDefaultRecordingNames = 1000;
106
164
  constexpr double kDefaultRecorderSampleRate = 16000.0;
@@ -376,52 +434,120 @@ __attribute__((weak)) void platform_attach_track(NativeMediaTrackHandle) {}
376
434
  __attribute__((weak)) void platform_detach_track(NativeMediaTrackHandle) {}
377
435
  #endif
378
436
 
379
- NativeMediaStreamHandle create_stream() {
437
+ NativeMediaStreamHandle create_audio_stream(bool capture) {
380
438
  auto streamHandle = nextStreamHandle()++;
381
439
  auto trackHandle = nextTrackHandle()++;
382
440
  {
383
441
  std::lock_guard<std::mutex> lock(mediaMutex());
384
442
  trackTable()[trackHandle] = TrackState{
385
- formatHandleId("track", trackHandle), "audio", "live", true, {}};
443
+ formatHandleId("track", trackHandle), "audio", "live", true, {}, capture};
386
444
  streamTable()[streamHandle] = StreamState{
387
- formatHandleId("stream", streamHandle), trackHandle};
445
+ formatHandleId("stream", streamHandle), {trackHandle}, trackHandle};
388
446
  }
389
- platform_attach_track(trackHandle);
447
+ if (capture) platform_attach_track(trackHandle);
448
+ return streamHandle;
449
+ }
450
+ NativeMediaStreamHandle create_stream() { return create_audio_stream(true); }
451
+ NativeMediaStreamHandle create_remote_stream() { return create_audio_stream(false); }
452
+
453
+ NativeMediaStreamHandle create_remote_video_stream() {
454
+ const auto streamHandle = nextStreamHandle()++;
455
+ const auto trackHandle = nextTrackHandle()++;
456
+ std::lock_guard<std::mutex> lock(mediaMutex());
457
+ trackTable()[trackHandle] = TrackState{
458
+ formatHandleId("track", trackHandle), "video", "live", true, {}, false};
459
+ streamTable()[streamHandle] = StreamState{
460
+ formatHandleId("stream", streamHandle), {trackHandle}, trackHandle};
390
461
  return streamHandle;
391
462
  }
392
463
 
464
+ bool publish_video_frame(NativeMediaTrackHandle handle, std::shared_ptr<VideoFrame> frame) {
465
+ if (!frame || !frame->width || !frame->height || frame->width > 1920 || frame->height > 1080 ||
466
+ frame->rgb565.size() != std::size_t(frame->width) * frame->height) return false;
467
+ std::lock_guard<std::mutex> lock(mediaMutex());
468
+ auto it = trackTable().find(handle);
469
+ if (it == trackTable().end() || it->second.kind != "video" ||
470
+ !it->second.enabled || it->second.readyState != "live") return false;
471
+ frame->sequence = ++it->second.videoSequence;
472
+ it->second.videoFrame = std::move(frame);
473
+ return true;
474
+ }
475
+
476
+ std::shared_ptr<const VideoFrame> latest_video_frame(NativeMediaTrackHandle handle) {
477
+ std::lock_guard<std::mutex> lock(mediaMutex());
478
+ auto it = trackTable().find(handle);
479
+ return it == trackTable().end() ? nullptr : it->second.videoFrame;
480
+ }
481
+
482
+ NativeMediaStreamHandle create_stream_from_tracks(const std::vector<MediaStreamTrack> &tracks) {
483
+ std::lock_guard<std::mutex> lock(mediaMutex());
484
+ std::vector<NativeMediaTrackHandle> members;
485
+ for (const auto &track : tracks) {
486
+ if (trackTable().find(track.nativeHandle) == trackTable().end())
487
+ throw std::invalid_argument("MediaStream requires valid media tracks");
488
+ if (std::find(members.begin(), members.end(), track.nativeHandle) == members.end())
489
+ members.push_back(track.nativeHandle);
490
+ }
491
+ const auto handle = nextStreamHandle()++;
492
+ streamTable()[handle] = StreamState{formatHandleId("stream", handle), std::move(members), 0};
493
+ return handle;
494
+ }
495
+
393
496
  NativeMediaTrackHandle stream_audio_track(NativeMediaStreamHandle handle) {
394
497
  std::lock_guard<std::mutex> lock(mediaMutex());
395
498
  auto it = streamTable().find(handle);
396
- return it == streamTable().end() ? 0 : it->second.audioTrack;
499
+ if (it == streamTable().end()) return 0;
500
+ for (auto handle : it->second.tracks) {
501
+ const auto track = trackTable().find(handle);
502
+ if (track != trackTable().end() && track->second.kind == "audio") return handle;
503
+ }
504
+ return 0;
397
505
  }
398
506
 
399
507
  void destroy_stream(NativeMediaStreamHandle handle) {
400
508
  NativeMediaTrackHandle trackHandle = 0;
509
+ bool capture = false;
401
510
  {
402
511
  std::lock_guard<std::mutex> lock(mediaMutex());
403
512
  auto it = streamTable().find(handle);
404
513
  if (it == streamTable().end()) return;
405
- trackHandle = it->second.audioTrack;
514
+ trackHandle = it->second.ownedTrack;
515
+ auto track = trackTable().find(trackHandle);
516
+ capture = track != trackTable().end() && track->second.capture && track->second.enabled && track->second.readyState != "ended";
406
517
  for (auto &entry : recorderTable()) {
407
518
  if (entry.second.track == trackHandle && entry.second.state == "recording") {
408
519
  finalizeRecorderFile(entry.second);
409
520
  entry.second.state = "inactive";
410
521
  }
411
522
  }
412
- trackTable().erase(trackHandle);
523
+ // Destroying a container must not destroy tracks shared with another
524
+ // stream. The transport/capture owner ends its source, retaining ended
525
+ // track identity while another container still names it.
526
+ if (track != trackTable().end()) {
527
+ track->second.readyState = "ended";
528
+ clearTrackPcm(track->second);
529
+ track->second.videoFrame.reset();
530
+ const bool shared = std::any_of(streamTable().begin(), streamTable().end(), [&](const auto &entry) {
531
+ return entry.first != handle && std::find(entry.second.tracks.begin(), entry.second.tracks.end(), trackHandle) != entry.second.tracks.end();
532
+ });
533
+ if (!shared) trackTable().erase(track);
534
+ }
413
535
  streamTable().erase(it);
414
536
  }
415
- if (trackHandle) platform_detach_track(trackHandle);
537
+ if (trackHandle && capture) platform_detach_track(trackHandle);
416
538
  }
417
539
 
418
540
  void track_inject_pcm(NativeMediaTrackHandle handle, const std::int16_t *samples, std::size_t count) {
541
+ if (!samples || !count) return;
419
542
  std::lock_guard<std::mutex> lock(mediaMutex());
420
543
  auto it = trackTable().find(handle);
421
- if (it == trackTable().end() || !it->second.enabled) return;
544
+ if (!samples || it == trackTable().end() || it->second.kind != "audio" || !it->second.enabled || it->second.readyState == "ended") return;
422
545
  auto &buffer = it->second.ringBuffer;
423
546
  for (std::size_t i = 0; i < count; ++i) {
424
- if (buffer.size() >= kMaxRingBufferSamples) buffer.pop_front();
547
+ if (buffer.size() >= kMaxRingBufferSamples) {
548
+ buffer.pop_front();
549
+ ++it->second.bufferStart;
550
+ }
425
551
  buffer.push_back(samples[i]);
426
552
  }
427
553
  for (auto &entry : recorderTable()) {
@@ -436,13 +562,97 @@ std::size_t track_read_pcm(NativeMediaTrackHandle handle, std::int16_t *samples,
436
562
  std::lock_guard<std::mutex> lock(mediaMutex());
437
563
  auto it = trackTable().find(handle);
438
564
  if (it == trackTable().end()) return 0;
439
- auto &buffer = it->second.ringBuffer;
440
- std::size_t copied = 0;
441
- while (copied < max_samples && !buffer.empty()) {
442
- samples[copied++] = buffer.front();
443
- buffer.pop_front();
565
+ if (!it->second.transportCursorActive) {
566
+ it->second.transportCursorActive = true;
567
+ it->second.transportCursor.next = it->second.bufferStart;
444
568
  }
445
- return copied;
569
+ return readTrackPcm(it->second, it->second.transportCursor, samples, max_samples);
570
+ }
571
+
572
+ TrackPcmReader::TrackPcmReader(NativeMediaTrackHandle track, bool includeBuffered) {
573
+ std::lock_guard<std::mutex> lock(mediaMutex());
574
+ auto it = trackTable().find(track);
575
+ if (it == trackTable().end() || it->second.readyState == "ended") return;
576
+ track_ = track;
577
+ reader_ = it->second.nextReader++;
578
+ it->second.readers.emplace(reader_, PcmCursor{it->second.bufferStart + (includeBuffered ? 0 : it->second.ringBuffer.size()), 0});
579
+ trimTrackPcm(it->second);
580
+ }
581
+
582
+ TrackPcmReader::~TrackPcmReader() { release(); }
583
+
584
+ TrackPcmReader::TrackPcmReader(TrackPcmReader &&other) noexcept
585
+ : track_(std::exchange(other.track_, 0)), reader_(std::exchange(other.reader_, 0)) {}
586
+
587
+ TrackPcmReader &TrackPcmReader::operator=(TrackPcmReader &&other) noexcept {
588
+ if (this != &other) {
589
+ release();
590
+ track_ = std::exchange(other.track_, 0);
591
+ reader_ = std::exchange(other.reader_, 0);
592
+ }
593
+ return *this;
594
+ }
595
+
596
+ void TrackPcmReader::release() {
597
+ std::lock_guard<std::mutex> lock(mediaMutex());
598
+ auto it = trackTable().find(track_);
599
+ if (it != trackTable().end()) {
600
+ it->second.readers.erase(reader_);
601
+ trimTrackPcm(it->second);
602
+ }
603
+ track_ = 0;
604
+ reader_ = 0;
605
+ }
606
+
607
+ std::size_t TrackPcmReader::read(std::int16_t *samples, std::size_t count) {
608
+ std::lock_guard<std::mutex> lock(mediaMutex());
609
+ auto it = trackTable().find(track_);
610
+ if (it == trackTable().end()) return 0;
611
+ auto cursor = it->second.readers.find(reader_);
612
+ if (cursor == it->second.readers.end()) return 0;
613
+ return readTrackPcm(it->second, cursor->second, samples, count);
614
+ }
615
+
616
+ std::uint64_t TrackPcmReader::droppedSamples() const {
617
+ std::lock_guard<std::mutex> lock(mediaMutex());
618
+ const auto it = trackTable().find(track_);
619
+ if (it == trackTable().end()) return 0;
620
+ const auto cursor = it->second.readers.find(reader_);
621
+ if (cursor == it->second.readers.end()) return 0;
622
+ return cursor->second.dropped + (cursor->second.next < it->second.bufferStart ? it->second.bufferStart - cursor->second.next : 0);
623
+ }
624
+
625
+ std::size_t TrackPcmReader::pendingSamples() const {
626
+ std::lock_guard<std::mutex> lock(mediaMutex());
627
+ const auto it = trackTable().find(track_);
628
+ if (it == trackTable().end()) return 0;
629
+ const auto cursor = it->second.readers.find(reader_);
630
+ if (cursor == it->second.readers.end()) return 0;
631
+ auto end = it->second.bufferStart + it->second.ringBuffer.size();
632
+ if (cursor->second.end) end = std::min(end, *cursor->second.end);
633
+ const auto next = std::max(cursor->second.next, it->second.bufferStart);
634
+ return end > next ? end - next : 0;
635
+ }
636
+
637
+ void TrackPcmReader::discardBuffered() {
638
+ std::lock_guard<std::mutex> lock(mediaMutex());
639
+ const auto it = trackTable().find(track_);
640
+ if (it == trackTable().end()) return;
641
+ const auto cursor = it->second.readers.find(reader_);
642
+ if (cursor == it->second.readers.end()) return;
643
+ cursor->second.next = it->second.bufferStart + it->second.ringBuffer.size();
644
+ cursor->second.end.reset();
645
+ trimTrackPcm(it->second);
646
+ }
647
+
648
+ void TrackPcmReader::beginDrain() {
649
+ std::lock_guard<std::mutex> lock(mediaMutex());
650
+ const auto it = trackTable().find(track_);
651
+ if (it == trackTable().end()) return;
652
+ const auto cursor = it->second.readers.find(reader_);
653
+ if (cursor == it->second.readers.end() || cursor->second.end) return;
654
+ // Snapshot once: an RTP track keeps delivering silence between replies.
655
+ cursor->second.end = it->second.bufferStart + it->second.ringBuffer.size();
446
656
  }
447
657
 
448
658
  NativeMediaStreamHandle get_user_media_audio() {
@@ -571,9 +781,23 @@ bool MediaStreamTrack::enabled() const {
571
781
  }
572
782
 
573
783
  void MediaStreamTrack::setEnabled(bool value) const {
574
- std::lock_guard<std::mutex> lock(mediaMutex());
575
- auto it = trackTable().find(nativeHandle);
576
- if (it != trackTable().end()) it->second.enabled = value;
784
+ bool capture = false;
785
+ {
786
+ std::lock_guard<std::mutex> lock(mediaMutex());
787
+ auto it = trackTable().find(nativeHandle);
788
+ if (it == trackTable().end() || it->second.readyState == "ended" || it->second.enabled == value) return;
789
+ capture = it->second.capture;
790
+ it->second.enabled = value;
791
+ if (!value) {
792
+ clearTrackPcm(it->second);
793
+ it->second.videoFrame.reset();
794
+ }
795
+ }
796
+ // Outside the media lock: the capture task itself injects PCM under that lock.
797
+ if (capture) {
798
+ if (value) media::platform_attach_track(nativeHandle);
799
+ else media::platform_detach_track(nativeHandle);
800
+ }
577
801
  }
578
802
 
579
803
  void MediaStreamTrack::stop() const {
@@ -582,11 +806,12 @@ void MediaStreamTrack::stop() const {
582
806
  std::lock_guard<std::mutex> lock(mediaMutex());
583
807
  auto it = trackTable().find(nativeHandle);
584
808
  if (it != trackTable().end()) {
585
- shouldDetach = it->second.readyState != "ended";
809
+ shouldDetach = it->second.capture && it->second.enabled && it->second.readyState != "ended";
586
810
  it->second.readyState = "ended";
587
811
  it->second.enabled = false;
588
812
  // 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);
813
+ clearTrackPcm(it->second);
814
+ it->second.videoFrame.reset();
590
815
  for (auto &entry : recorderTable()) {
591
816
  if (entry.second.track == nativeHandle && entry.second.state == "recording") {
592
817
  entry.second.state = "inactive";
@@ -606,12 +831,68 @@ std::string MediaStream::id() const {
606
831
  std::vector<MediaStreamTrack> MediaStream::getAudioTracks() const {
607
832
  std::lock_guard<std::mutex> lock(mediaMutex());
608
833
  auto it = streamTable().find(nativeHandle);
609
- if (it == streamTable().end() || it->second.audioTrack == 0) return {};
610
- return {MediaStreamTrack(it->second.audioTrack)};
834
+ std::vector<MediaStreamTrack> result;
835
+ if (it != streamTable().end()) for (auto handle : it->second.tracks) {
836
+ const auto track = trackTable().find(handle);
837
+ if (track != trackTable().end() && track->second.kind == "audio") result.emplace_back(handle);
838
+ }
839
+ return result;
611
840
  }
612
841
 
613
842
  std::vector<MediaStreamTrack> MediaStream::getTracks() const {
614
- return getAudioTracks();
843
+ std::lock_guard<std::mutex> lock(mediaMutex());
844
+ const auto it = streamTable().find(nativeHandle);
845
+ std::vector<MediaStreamTrack> result;
846
+ if (it != streamTable().end()) for (auto handle : it->second.tracks) result.emplace_back(handle);
847
+ return result;
848
+ }
849
+
850
+ std::vector<MediaStreamTrack> MediaStream::getVideoTracks() const {
851
+ std::lock_guard<std::mutex> lock(mediaMutex());
852
+ const auto it = streamTable().find(nativeHandle);
853
+ std::vector<MediaStreamTrack> result;
854
+ if (it != streamTable().end()) for (auto handle : it->second.tracks) {
855
+ const auto track = trackTable().find(handle);
856
+ if (track != trackTable().end() && track->second.kind == "video") result.emplace_back(handle);
857
+ }
858
+ return result;
859
+ }
860
+
861
+ MediaStreamTrack MediaStream::getTrackById(const std::string &id) const {
862
+ std::lock_guard<std::mutex> lock(mediaMutex());
863
+ const auto it = streamTable().find(nativeHandle);
864
+ if (it != streamTable().end()) for (auto handle : it->second.tracks) {
865
+ const auto track = trackTable().find(handle);
866
+ if (track != trackTable().end() && track->second.id == id) return MediaStreamTrack(handle);
867
+ }
868
+ return {};
869
+ }
870
+
871
+ bool MediaStream::active() const {
872
+ std::lock_guard<std::mutex> lock(mediaMutex());
873
+ const auto it = streamTable().find(nativeHandle);
874
+ if (it != streamTable().end()) for (auto handle : it->second.tracks) {
875
+ const auto track = trackTable().find(handle);
876
+ if (track != trackTable().end() && track->second.readyState == "live") return true;
877
+ }
878
+ return false;
879
+ }
880
+
881
+ void MediaStream::addTrack(MediaStreamTrack track) const {
882
+ std::lock_guard<std::mutex> lock(mediaMutex());
883
+ const auto it = streamTable().find(nativeHandle);
884
+ if (it == streamTable().end() || trackTable().find(track.nativeHandle) == trackTable().end())
885
+ throw std::invalid_argument("addTrack requires a valid stream and track");
886
+ auto &members = it->second.tracks;
887
+ if (std::find(members.begin(), members.end(), track.nativeHandle) == members.end()) members.push_back(track.nativeHandle);
888
+ }
889
+
890
+ void MediaStream::removeTrack(MediaStreamTrack track) const {
891
+ std::lock_guard<std::mutex> lock(mediaMutex());
892
+ const auto it = streamTable().find(nativeHandle);
893
+ if (it == streamTable().end()) throw std::invalid_argument("removeTrack requires a valid stream");
894
+ auto &members = it->second.tracks;
895
+ members.erase(std::remove(members.begin(), members.end(), track.nativeHandle), members.end());
615
896
  }
616
897
 
617
898
  } // namespace gea::host
package/host/mjpeg.cpp ADDED
@@ -0,0 +1,205 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ #include "host/mjpeg.h"
3
+ #include "host/mjpeg_parser.h"
4
+ #include "host/video_frame_pool.h"
5
+ #include "pixel.h"
6
+ #include <atomic>
7
+ #include <mutex>
8
+ #include <optional>
9
+ #include <stdexcept>
10
+
11
+ // The generated application archive is linked after managed prebuilt codecs.
12
+ // Resolve this object before those libraries (as with the GPIO bindings), so
13
+ // the late HTMLVideoElement caller does not strand JPEG symbols behind them.
14
+ extern "C" void gea_mjpeg_link_bindings() {}
15
+
16
+ #if defined(ESP_PLATFORM) && !defined(GEA_EMBEDDED_WIFI_DISABLED) && __has_include("esp_jpeg_dec.h")
17
+ #include "esp_http_client.h"
18
+ #include "esp_jpeg_dec.h"
19
+ #include "esp_log.h"
20
+ #include "esp_timer.h"
21
+ #include "freertos/FreeRTOS.h"
22
+ #include "freertos/idf_additions.h"
23
+ #include "freertos/semphr.h"
24
+ #include "freertos/task.h"
25
+ #if GEA_EMBEDDED_ENABLE_HTTPS
26
+ #include "esp_crt_bundle.h"
27
+ #endif
28
+ #define GEA_HAS_MJPEG_STREAM 1
29
+ #endif
30
+
31
+ namespace gea::host::video {
32
+ struct MjpegStream::State {
33
+ MediaStream source{media::create_remote_video_stream()};
34
+ std::atomic<bool> running{true};
35
+ ~State() {
36
+ #ifdef GEA_HAS_MJPEG_STREAM
37
+ if (wake) vSemaphoreDelete(wake);
38
+ #endif
39
+ media::destroy_stream(source.nativeHandle);
40
+ }
41
+ #ifdef GEA_HAS_MJPEG_STREAM
42
+ std::string url;
43
+ SemaphoreHandle_t wake = nullptr;
44
+ std::mutex mutex;
45
+ std::optional<JpegPacket> newest;
46
+ std::atomic<unsigned> received{0}, replaced{0};
47
+
48
+ void receive() {
49
+ esp_http_client_config_t config{};
50
+ config.url = url.c_str();
51
+ config.timeout_ms = 1000;
52
+ config.buffer_size = 4096;
53
+ config.disable_auto_redirect = true;
54
+ #if GEA_EMBEDDED_ENABLE_HTTPS
55
+ config.crt_bundle_attach = esp_crt_bundle_attach;
56
+ #endif
57
+ auto client = esp_http_client_init(&config);
58
+ if (!client) throw std::runtime_error("MJPEG HTTP allocation failed");
59
+ struct Cleanup {
60
+ esp_http_client_handle_t client;
61
+ ~Cleanup() { esp_http_client_cleanup(client); }
62
+ } cleanup{client};
63
+ if (esp_http_client_open(client, 0) != ESP_OK ||
64
+ esp_http_client_fetch_headers(client) < 0 || esp_http_client_get_status_code(client) != 200)
65
+ throw std::runtime_error("MJPEG HTTP connection rejected");
66
+ MjpegParser parser;
67
+ std::array<uint8_t, 4096> bytes{};
68
+ auto lastData = esp_timer_get_time();
69
+ bool receivedData = false;
70
+ while (running) {
71
+ const int size = esp_http_client_read(client, reinterpret_cast<char*>(bytes.data()), bytes.size());
72
+ if (!running) break;
73
+ if (size == -ESP_ERR_HTTP_EAGAIN && esp_timer_get_time() - lastData <
74
+ (receivedData ? 15000000 : 150000000)) continue;
75
+ if (size <= 0) throw std::runtime_error("MJPEG HTTP stream ended");
76
+ lastData = esp_timer_get_time();
77
+ receivedData = true;
78
+ if (!parser.push(std::span(bytes.data(), size_t(size)), [&](JpegPacket packet) {
79
+ {
80
+ std::lock_guard lock(mutex);
81
+ if (newest) ++replaced;
82
+ newest = std::move(packet);
83
+ ++received;
84
+ }
85
+ xSemaphoreGive(wake);
86
+ })) throw std::runtime_error("MJPEG malformed or oversized multipart frame");
87
+ // Receiving owns no decode/display work and cannot build a frame queue.
88
+ taskYIELD();
89
+ }
90
+ }
91
+
92
+ void decode() {
93
+ jpeg_dec_config_t config = DEFAULT_JPEG_DEC_CONFIG();
94
+ config.output_type = GEA_EMBEDDED_PIXEL_PANEL_ENDIAN ?
95
+ JPEG_PIXEL_FORMAT_RGB565_BE : JPEG_PIXEL_FORMAT_RGB565_LE;
96
+ jpeg_dec_handle_t decoder = nullptr;
97
+ struct Cleanup {
98
+ jpeg_dec_handle_t& decoder;
99
+ ~Cleanup() { if (decoder) jpeg_dec_close(decoder); }
100
+ } cleanup{decoder};
101
+ media::VideoFramePool frames;
102
+ const auto track = source.getVideoTracks().front().nativeHandle;
103
+ unsigned decoded = 0, raw = 0;
104
+ int64_t report = esp_timer_get_time(), totalDecode = 0;
105
+ while (running) {
106
+ xSemaphoreTake(wake, pdMS_TO_TICKS(100));
107
+ if (!running) break;
108
+ std::optional<JpegPacket> packet;
109
+ { std::lock_guard lock(mutex); packet.swap(newest); }
110
+ if (!packet) continue;
111
+ const auto started = esp_timer_get_time();
112
+ auto frame = std::move(packet->rawFrame);
113
+ if (frame) {
114
+ ++raw;
115
+ } else {
116
+ // RGB565 never instantiates a JPEG decoder or a second pixel buffer.
117
+ if (!decoder && jpeg_dec_open(&config, &decoder) != JPEG_ERR_OK)
118
+ throw std::runtime_error("MJPEG SIMD decoder allocation failed");
119
+ jpeg_dec_io_t io{};
120
+ io.inbuf = packet->bytes.data();
121
+ io.inbuf_len = int(packet->bytes.size());
122
+ jpeg_dec_header_info_t header{};
123
+ if (jpeg_dec_parse_header(decoder, &io, &header) != JPEG_ERR_OK ||
124
+ !header.width || !header.height || header.width > 512 || header.height > 512)
125
+ throw std::runtime_error("MJPEG rejected JPEG dimensions/header");
126
+ int outputBytes = 0;
127
+ if (jpeg_dec_get_outbuf_len(decoder, &outputBytes) != JPEG_ERR_OK ||
128
+ outputBytes != int(size_t(header.width) * header.height * sizeof(uint16_t)))
129
+ throw std::runtime_error("MJPEG unexpected decoder output size");
130
+ frame = frames.acquire(header.width, header.height);
131
+ if (!frame) continue;
132
+ io.outbuf = reinterpret_cast<uint8_t*>(frame->rgb565.data());
133
+ if (jpeg_dec_process(decoder, &io) != JPEG_ERR_OK || io.out_size != outputBytes)
134
+ throw std::runtime_error("MJPEG JPEG decode failed");
135
+ frame->panelEndian = bool(GEA_EMBEDDED_PIXEL_PANEL_ENDIAN);
136
+ frame->timestampMs = packet->timestampMs;
137
+ }
138
+ if (!running) break;
139
+ media::publish_video_frame(track, std::move(frame));
140
+ ++decoded;
141
+ totalDecode += esp_timer_get_time() - started;
142
+ const auto now = esp_timer_get_time();
143
+ if (now - report >= 2000000) {
144
+ ESP_LOGI("gea_mjpeg", "decoded=%u received=%u replaced=%u decode_us=%lld raw=%u",
145
+ decoded, received.load(), replaced.load(), (long long)(totalDecode / decoded), raw);
146
+ report = now;
147
+ }
148
+ vTaskDelay(1); // Keep raster and CPU1 idle work progressing under sustained video.
149
+ }
150
+ }
151
+
152
+ template<bool Decode> static void worker(void* argument) {
153
+ auto* owner = static_cast<std::shared_ptr<State>*>(argument);
154
+ auto state = std::move(*owner);
155
+ delete owner;
156
+ try {
157
+ if constexpr (Decode) state->decode();
158
+ else state->receive();
159
+ } catch (const std::exception& error) {
160
+ if (state->running) ESP_LOGE("gea_mjpeg", "%s", error.what());
161
+ }
162
+ state->running = false;
163
+ xSemaphoreGive(state->wake);
164
+ state.reset();
165
+ vTaskDeleteWithCaps(nullptr);
166
+ }
167
+ #endif
168
+ };
169
+
170
+ MjpegStream::MjpegStream(const std::string& url) {
171
+ #ifdef GEA_HAS_MJPEG_STREAM
172
+ if (!url.starts_with("http://") && !url.starts_with("https://"))
173
+ throw std::invalid_argument("MJPEG requires an HTTP(S) URL");
174
+ state_ = std::make_shared<State>();
175
+ state_->url = url;
176
+ state_->wake = xSemaphoreCreateBinary();
177
+ if (!state_->wake) throw std::runtime_error("MJPEG wake allocation failed");
178
+ // Each task holds its own source lifetime. Stop is immediate on the UI;
179
+ // network timeouts bound cleanup without deleting a task inside HTTP/JPEG.
180
+ for (const bool decode : {false, true}) {
181
+ auto* owner = new std::shared_ptr<State>(state_);
182
+ const auto entry = decode ? State::worker<true> : State::worker<false>;
183
+ if (xTaskCreatePinnedToCoreWithCaps(entry, decode ? "gea_mjpeg_dec" : "gea_mjpeg_rx",
184
+ decode ? 64 * 1024 : 16 * 1024, owner, decode ? 4 : 7, nullptr, 1,
185
+ MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) != pdPASS) {
186
+ delete owner;
187
+ stop();
188
+ throw std::runtime_error("MJPEG task allocation failed");
189
+ }
190
+ }
191
+ #else
192
+ (void)url;
193
+ throw std::runtime_error("MJPEG native streaming requires an ESP JPEG decoder");
194
+ #endif
195
+ }
196
+ MjpegStream::~MjpegStream() { stop(); }
197
+ MediaStream MjpegStream::stream() const { return state_ ? state_->source : MediaStream{}; }
198
+ void MjpegStream::stop() {
199
+ if (!state_) return;
200
+ state_->running = false;
201
+ #ifdef GEA_HAS_MJPEG_STREAM
202
+ if (state_->wake) xSemaphoreGive(state_->wake);
203
+ #endif
204
+ }
205
+ } // namespace gea::host::video