TinyUVC 0.1.0
Header-only USB Video Class (UVC) device: turn an MCU into a USB webcam
Loading...
Searching...
No Matches
TinyGPU.h
Go to the documentation of this file.
1#pragma once
42#if defined(ARDUINO) && !defined(HOST)
43// TinyGPU's touch and display drivers use them: the Arduino build only
44// finds these libraries if they are included
45#include <SPI.h>
46#include <Wire.h>
47#endif
48#include <new>
49
50// angle brackets: "TinyGPU.h" would be this file
51#include <TinyGPU.h>
52
53#include "../TinyUVC.h"
54
55#if !defined(TINYUVC_NO_JPEG) && defined(ARDUINO_ARCH_ESP32) && \
56 __has_include("img_converters.h")
57#include "img_converters.h"
58#define TINYUVC_JPEG_ESP32 1
59#else
60#define TINYUVC_JPEG_ESP32 0
61#endif
62
63#if !defined(TINYUVC_NO_JPEG) && __has_include(<TinyJPEGEncoder.h>)
64#include <TinyJPEGEncoder.h>
65#define TINYUVC_JPEG_TINYJPEG 1
66#else
67#define TINYUVC_JPEG_TINYJPEG 0
68#endif
69
71#define TINYUVC_HAS_JPEG (TINYUVC_JPEG_ESP32 || TINYUVC_JPEG_TINYJPEG)
72
73namespace tinyuvc {
74
76template <typename RGB_T>
78
80template <>
81struct UVCTinyGPUPixel<tinygpu::RGB565> {
82 static constexpr PixelFormat format = PixelFormat::RGB565_BE;
83 static constexpr size_t bytes = 2;
84};
85
87template <>
88struct UVCTinyGPUPixel<tinygpu::RGB888> {
89 static constexpr PixelFormat format = PixelFormat::RGB888;
90 static constexpr size_t bytes = 3;
91};
92
109template <typename RGB_T = tinygpu::RGB565>
110class UVCDisplayDriver : public tinygpu::DisplayDriver<RGB_T> {
111 public:
112 explicit UVCDisplayDriver(UVCDevice &uvc) : uvc_(uvc) {}
113 ~UVCDisplayDriver() override {
114 // the device may still read a frame buffer
116#if TINYUVC_JPEG_TINYJPEG
117 if (encoder_ != nullptr) {
118 encoder_->~TinyJPEGEncoder();
119 UVCMemory::free(encoder_);
120 }
121#endif
122 }
123
127 bool addResolution(UVCFormat format, uint16_t width, uint16_t height,
128 std::initializer_list<uint8_t> fps,
129 uint32_t maxJpegSize = 0) {
130 if (format == UVCFormat::MJPEG) {
131#if TINYUVC_JPEG_TINYJPEG
132 if (!useEsp32Jpeg() && width > JE_MAX_WIDTH) {
133 TINYUVC_LOGE("MJPEG wider than JE_MAX_WIDTH (%d)", (int)JE_MAX_WIDTH);
134 return false;
135 }
136#endif
138 TINYUVC_LOGE("MJPEG needs a JPEG encoder: include TinyJPEGEncoder.h");
139 return false;
140 }
141 if (maxJpegSize == 0) maxJpegSize = (uint32_t)width * height;
142 }
143 return uvc_.addResolution(format, width, height, fps, maxJpegSize);
144 }
145 bool addResolution(UVCFormat format, uint16_t width, uint16_t height,
146 uint8_t fps, uint32_t maxJpegSize = 0) {
147 return addResolution(format, width, height, {fps}, maxJpegSize);
148 }
150 bool addResolution(uint16_t width, uint16_t height, uint8_t fps) {
151 return addResolution(UVCFormat::YUY2, width, height, {fps});
152 }
153 bool addResolution(uint16_t width, uint16_t height,
154 std::initializer_list<uint8_t> fps) {
156 }
157
159 bool begin() override { return uvc_.begin(); }
160
161 void end() override {
162 // the frame that is still being sent keeps its buffer
163 const bool idle = waitSent(1000);
165 if (idle) buffers_[1 - next_].release();
166 work_.release();
167 swap_.release();
168 workBytes_ = 0;
169 }
170
172 void setPacing(bool pacing) { pacing_ = pacing; }
173
175 void setTimeout(uint32_t ms) { timeoutMs_ = ms; }
176
178 void setJpegQuality(uint8_t quality) { quality_ = quality; }
179
182 end();
183 for (auto &b : buffers_) b.setMemoryType(type);
184 work_.setMemoryType(type);
185 swap_.setMemoryType(type);
186 }
187
191 bool writeData(tinygpu::ISurface<RGB_T> &surface) override {
192 if (!uvc_.isStreaming()) return false;
193 if (surface.width() != width() || surface.height() != height()) {
194 mismatched_++;
195 return false;
196 }
197 if (isJpeg()) return sendJpeg(surface.data());
199 if (buf == nullptr) return false;
200 memcpy(buf->data(), surface.data(), rawBytes());
202 }
203
207 bool writeData(tinygpu::ISurface<RGB_T> &surface, size_t x,
208 size_t y) override {
209 if (!uvc_.isStreaming() || x >= width() || y >= height()) return false;
210 if (workBytes_ != rawBytes()) {
211 // new resolution: the old content has a different layout
212 if (!work_.reserve(rawBytes())) return false;
213 memset(work_.data(), 0, rawBytes());
215 }
216 const size_t bpp = UVCTinyGPUPixel<RGB_T>::bytes;
217 const size_t w = std::min(surface.width(), width() - x);
218 const size_t h = std::min(surface.height(), height() - y);
219 const uint8_t *src = surface.data();
220 for (size_t row = 0; row < h; row++) {
221 memcpy(work_.data() + ((y + row) * width() + x) * bpp,
222 src + row * surface.width() * bpp, w * bpp);
223 }
224 dirty_ = true;
225 return true;
226 }
227
229 bool flush() {
230 if (!dirty_ || !uvc_.isStreaming() || workBytes_ != rawBytes())
231 return false;
232 dirty_ = false;
233 if (isJpeg()) return sendJpeg(work_.data());
235 if (buf == nullptr) return false;
236 memcpy(buf->data(), work_.data(), rawBytes());
238 }
239
242 size_t width() const override { return selected().width; }
243 size_t height() const override { return selected().height; }
244
246 bool sizeChanged(size_t width, size_t height) const {
247 return width != this->width() || height != this->height();
248 }
249
251 bool isJpeg() const {
253 }
254
256 bool waitSent(uint32_t timeoutMs) {
257 const uint32_t start = platform::millis();
258 while (uvc_.isSending()) {
259 if (platform::millis() - start >= timeoutMs) return false;
261 }
262 return true;
263 }
264
265 uint32_t frames() const { return frames_; }
266 uint32_t dropped() const { return dropped_; }
268 uint32_t mismatched() const { return mismatched_; }
270 size_t lastJpegSize() const { return lastJpegSize_; }
271
272 UVCDevice &device() { return uvc_; }
273
274 protected:
278 int next_ = 0;
282 size_t workBytes_ = 0;
285#if TINYUVC_JPEG_TINYJPEG
286 tinyjpeg::TinyJPEGEncoder *encoder_ = nullptr; // allocated when needed
287#endif
288
290 static constexpr bool useEsp32Jpeg() {
292 }
293
295 struct JpegSink {
296 uint8_t *data;
297 size_t capacity;
298 size_t len;
300 };
301
302 static size_t jpegSinkWrite(void *arg, size_t index, const void *data,
303 size_t len) {
304 JpegSink *sink = (JpegSink *)arg;
305 if (data == nullptr) return 0; // end of the image
306 if (index + len > sink->capacity) {
307 sink->overflow = true;
308 return 0; // stops the encoder
309 }
310 memcpy(sink->data + index, data, len);
311 if (index + len > sink->len) sink->len = index + len;
312 return len;
313 }
314 uint8_t quality_ = 80;
315 bool pacing_ = true;
316 bool dirty_ = false;
317 bool sent_ = false;
318 uint32_t timeoutMs_ = 1000;
319 uint32_t lastUs_ = 0;
320 uint32_t frames_ = 0;
321 uint32_t dropped_ = 0;
322 uint32_t mismatched_ = 0;
323 size_t lastJpegSize_ = 0;
324
326 struct Size {
327 size_t width = 0;
328 size_t height = 0;
329 uint32_t maxFrameSize = 0;
330 };
331
333 Size selected() const {
334 Size s;
335 const UVCFrameSpec *f = nullptr;
336 if (uvc_.isStreaming()) {
337 const UVCStreamSettings st = uvc_.settings();
338 if (st.formatIndex >= 1 && st.formatIndex <= uvc_.formatCount()) {
339 const UVCFormatSpec &fmt = uvc_.formats()[st.formatIndex - 1];
340 if (st.frameIndex >= 1 && st.frameIndex <= fmt.frameCount)
341 f = &fmt.frames[st.frameIndex - 1];
342 }
343 } else if (uvc_.formatCount() > 0 && uvc_.formats()[0].frameCount > 0) {
344 f = &uvc_.formats()[0].frames[0];
345 }
346 if (f != nullptr) {
347 s.width = f->width;
348 s.height = f->height;
350 }
351 return s;
352 }
353
354 size_t rawBytes() const {
356 }
357
360 UVCFrameBuffer *nextBuffer(size_t bytes) {
362 if (buf.capacity() >= bytes) return &buf;
363 buf.release(); // no copy of the old content needed
364 if (buf.reserve(bytes)) return &buf;
365 // no memory for a second frame: wait for the other buffer and reuse it
366 // (frames are then rendered and sent one after the other)
367 UVCFrameBuffer &other = buffers_[1 - next_];
368 if (waitSent(timeoutMs_)) {
369 if (other.capacity() < bytes) other.release();
370 if (other.reserve(bytes)) {
371 next_ = 1 - next_;
372 return &other;
373 }
374 }
375 TINYUVC_LOGE("UVCDisplayDriver: no memory for %u bytes", (unsigned)bytes);
376 dropped_++;
377 return nullptr;
378 }
379
380 bool sendJpeg(const uint8_t *pixels) {
381 const uint16_t w = (uint16_t)width(), h = (uint16_t)height();
382#if TINYUVC_JPEG_ESP32
383 if (useEsp32Jpeg()) {
384 const size_t maxJpeg = selected().maxFrameSize;
385 UVCFrameBuffer *buf = nextBuffer(maxJpeg);
386 if (buf == nullptr) return false;
387 JpegSink sink{buf->data(), maxJpeg, 0, false};
388 const bool ok = fmt2jpg_cb((uint8_t *)pixels, (size_t)w * h * 2, w, h,
389 PIXFORMAT_RGB565, quality_, jpegSinkWrite,
390 &sink);
391 if (!ok || sink.overflow) {
392 TINYUVC_LOGW("JPEG encoding failed%s",
393 sink.overflow ? ": increase maxJpegSize" : "");
394 dropped_++;
395 return false;
396 }
397 lastJpegSize_ = sink.len;
398 return send(*buf, sink.len, PixelFormat::MJPEG);
399 }
400#endif
401#if TINYUVC_JPEG_TINYJPEG
402 JEPixelFormat format = JE_FMT_RGB888;
404 // TinyGPU's RGB565 is byte-swapped, TinyJPEG reads native order
405 // (into swap_: work_ must keep the frame composed by partial writes)
406 const size_t bytes = (size_t)w * h * 2;
407 if (!swap_.reserve(bytes)) {
408 dropped_++;
409 return false;
410 }
411 uint8_t *dst = swap_.data();
412 for (size_t i = 0; i < bytes; i += 2) {
413 const uint8_t hi = pixels[i];
414 dst[i] = pixels[i + 1];
415 dst[i + 1] = hi;
416 }
417 pixels = dst;
418 format = JE_FMT_RGB565;
419 }
420 const size_t maxJpeg = selected().maxFrameSize;
421 UVCFrameBuffer *buf = nextBuffer(maxJpeg);
422 if (buf == nullptr) return false;
423 if (encoder_ == nullptr) {
424 // the encoder works on its workspace all the time: internal RAM is
425 // much faster than PSRAM (where new would put it on an ESP32)
426 void *mem = UVCMemory::alloc(sizeof(tinyjpeg::TinyJPEGEncoder),
428 if (mem == nullptr) {
429 dropped_++;
430 return false;
431 }
432 encoder_ = new (mem) tinyjpeg::TinyJPEGEncoder();
433 }
434 encoder_->setQuality(quality_);
435 size_t len = 0;
436 const JERESULT r =
437 encoder_->encodeJpg(pixels, w, h, format, buf->data(), maxJpeg, len);
438 if (r != JER_OK) {
439 TINYUVC_LOGW("JPEG encoding failed (%d): increase maxJpegSize?", (int)r);
440 dropped_++;
441 return false;
442 }
443 lastJpegSize_ = len;
444 return send(*buf, len, PixelFormat::MJPEG);
445#else
446 (void)pixels;
447 (void)w;
448 (void)h;
449 dropped_++;
450 return false;
451#endif
452 }
453
454 bool send(UVCFrameBuffer &buf, size_t len, PixelFormat format) {
455 if (pacing_ && sent_) {
456 const uint32_t intervalUs = uvc_.settings().interval / 10;
457 while (uvc_.isStreaming() && platform::micros() - lastUs_ < intervalUs)
459 }
460 if (!uvc_.isReady() && !uvc_.waitReady(timeoutMs_)) {
461 dropped_++;
462 return false;
463 }
464 if (!uvc_.writeFrame(buf.data(), len, format)) {
465 dropped_++;
466 return false;
467 }
468 next_ = 1 - next_; // keep this buffer until it is sent
470 sent_ = true;
471 frames_++;
472 return true;
473 }
474
475 bool setAddressWindow(size_t, size_t, size_t, size_t) override {
476 return true;
477 }
478};
479
480} // namespace tinyuvc
Integration with TinyGPU (https://github.com/pschatzmann/TinyGPU): UVCDisplayDriver is a TinyGPU Disp...
#define TINYUVC_JPEG_TINYJPEG
Definition TinyGPU.h:67
#define TINYUVC_JPEG_ESP32
Definition TinyGPU.h:60
#define TINYUVC_LOGE(...)
Definition UVCLogger.h:75
#define TINYUVC_LOGW(...)
Definition UVCLogger.h:77
USB Video Class (UVC 1.1) device - a USB webcam.
Definition UVCDevice.h:95
uint8_t formatCount() const
Definition UVCDevice.h:340
bool isStreaming() const
true while the host is streaming (between commit and stop)
Definition UVCDevice.h:261
const UVCFormatSpec * formats() const
Formats as defined with addResolution()
Definition UVCDevice.h:339
UVCStreamSettings settings() const
Format, resolution and frame rate the host selected.
Definition UVCDevice.h:272
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, uint8_t fps, uint32_t maxFrameSize=0)
Definition UVCDevice.h:107
bool writeFrame(const uint8_t *data, size_t len, PixelFormat fmt)
Sends a frame. Returns false (and the frame is not sent) if the device is not ready or the frame does...
Definition UVCDevice.h:287
bool waitReady(uint32_t timeoutMs)
Waits until isReady() (true) or the timeout or end of streaming (false)
Definition UVCDevice.h:323
bool isSending() const
Definition UVCDevice.h:269
bool begin()
Definition UVCDevice.h:198
bool isReady() const
Definition UVCDevice.h:265
TinyGPU DisplayDriver that sends the written surfaces as webcam frames to the USB host: uncompressed ...
Definition TinyGPU.h:110
bool setAddressWindow(size_t, size_t, size_t, size_t) override
Definition TinyGPU.h:475
uint32_t dropped_
Definition TinyGPU.h:321
void setMemoryType(UVCMemoryType type)
Where the frame buffers are allocated (default: PSRAM if available)
Definition TinyGPU.h:181
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, uint8_t fps, uint32_t maxJpegSize=0)
Definition TinyGPU.h:145
uint32_t mismatched_
Definition TinyGPU.h:322
bool flush()
Sends the frame composed with writeData(surface, x, y)
Definition TinyGPU.h:229
uint32_t frames() const
Definition TinyGPU.h:265
size_t workBytes_
size of the frame in work_ (0: none)
Definition TinyGPU.h:282
UVCFrameBuffer swap_
RGB565 in TinyJPEG's byte order.
Definition TinyGPU.h:284
bool sizeChanged(size_t width, size_t height) const
true when the host selected a different size than width x height
Definition TinyGPU.h:246
uint32_t dropped() const
Definition TinyGPU.h:266
void end() override
Definition TinyGPU.h:161
UVCDevice & device()
Definition TinyGPU.h:272
bool send(UVCFrameBuffer &buf, size_t len, PixelFormat format)
Definition TinyGPU.h:454
size_t lastJpegSize_
Definition TinyGPU.h:323
void setJpegQuality(uint8_t quality)
JPEG quality 1..100 (default 80)
Definition TinyGPU.h:178
void setPacing(bool pacing)
Wait for the frame interval the host selected (default true)
Definition TinyGPU.h:172
bool sent_
Definition TinyGPU.h:317
bool writeData(tinygpu::ISurface< RGB_T > &surface) override
Definition TinyGPU.h:191
bool writeData(tinygpu::ISurface< RGB_T > &surface, size_t x, size_t y) override
Definition TinyGPU.h:207
size_t lastJpegSize() const
Size of the last JPEG.
Definition TinyGPU.h:270
bool addResolution(uint16_t width, uint16_t height, std::initializer_list< uint8_t > fps)
Definition TinyGPU.h:153
uint32_t timeoutMs_
Definition TinyGPU.h:318
bool addResolution(uint16_t width, uint16_t height, uint8_t fps)
Uncompressed (YUY2) resolution.
Definition TinyGPU.h:150
bool sendJpeg(const uint8_t *pixels)
Definition TinyGPU.h:380
Size selected() const
The resolution the host selected, or the first one.
Definition TinyGPU.h:333
bool begin() override
Starts the UVC device (if it is not running yet)
Definition TinyGPU.h:159
bool waitSent(uint32_t timeoutMs)
Waits until the device finished reading the previous frame.
Definition TinyGPU.h:256
static size_t jpegSinkWrite(void *arg, size_t index, const void *data, size_t len)
Definition TinyGPU.h:302
size_t height() const override
Definition TinyGPU.h:243
int next_
Definition TinyGPU.h:278
static constexpr bool useEsp32Jpeg()
esp32-camera's encoder: RGB565 only (in TinyGPU's byte order)
Definition TinyGPU.h:290
UVCFrameBuffer work_
frames composed by partial writes
Definition TinyGPU.h:280
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, std::initializer_list< uint8_t > fps, uint32_t maxJpegSize=0)
Definition TinyGPU.h:127
uint8_t quality_
Definition TinyGPU.h:314
UVCDevice & uvc_
Definition TinyGPU.h:275
void setTimeout(uint32_t ms)
How long writeData() waits for the previous frame (default 1000 ms)
Definition TinyGPU.h:175
bool isJpeg() const
true if the host selected MJPEG
Definition TinyGPU.h:251
uint32_t frames_
Definition TinyGPU.h:320
size_t rawBytes() const
Definition TinyGPU.h:354
uint32_t lastUs_
Definition TinyGPU.h:319
UVCFrameBuffer * nextBuffer(size_t bytes)
Definition TinyGPU.h:360
UVCDisplayDriver(UVCDevice &uvc)
Definition TinyGPU.h:112
bool pacing_
Definition TinyGPU.h:315
uint32_t mismatched() const
Surfaces that were rejected because of their size.
Definition TinyGPU.h:268
size_t width() const override
Definition TinyGPU.h:242
bool dirty_
Definition TinyGPU.h:316
UVCFrameBuffer buffers_[2]
frames handed to the device: one is sent while the next is prepared
Definition TinyGPU.h:277
~UVCDisplayDriver() override
Definition TinyGPU.h:113
A growing byte buffer for one frame, allocated with UVCMemory (so in PSRAM where available)....
Definition UVCMemory.h:95
bool reserve(size_t size)
Makes sure that size bytes fit without a new allocation.
Definition UVCMemory.h:106
size_t capacity() const
Definition UVCMemory.h:145
void release()
Frees the memory.
Definition UVCMemory.h:136
void setMemoryType(UVCMemoryType type)
Definition UVCMemory.h:102
uint8_t * data()
Definition UVCMemory.h:142
static uint8_t * alloc(size_t size, UVCMemoryType type=UVCMemoryType::Auto)
Definition UVCMemory.h:51
static void free(void *p)
Definition UVCMemory.h:60
uint32_t millis()
Definition UVCPlatformDesktop.h:41
void idle()
Called while waiting: lets the USB stack make progress.
Definition UVCPlatformDesktop.h:33
uint32_t micros()
Definition UVCPlatformDesktop.h:47
TinyUVC: USB Video Class (UVC) device for Arduino and the desktop.
UVCMemoryType
Definition UVCMemory.h:29
@ RAMOnly
internal RAM only
UVCFormat
Video format offered to the USB host.
Definition UVCDefs.h:78
@ MJPEG
Motion JPEG: every frame is a complete JPEG image.
@ YUY2
Uncompressed YUV 4:2:2 (YUYV), 16 bits per pixel.
PixelFormat
Pixel format of the frame data handed to UVCDevice::writeFrame(). MJPEG (a JPEG image) is sent as is....
Definition UVCDefs.h:92
@ MJPEG
one complete JPEG image (for UVCFormat::MJPEG)
@ RGB888
24 bit, byte order R G B
@ RGB565_BE
16 bit RGB565, big endian (high byte first, esp32-camera)
Output of fmt2jpg_cb() into a frame buffer.
Definition TinyGPU.h:295
size_t len
Definition TinyGPU.h:298
bool overflow
Definition TinyGPU.h:299
size_t capacity
Definition TinyGPU.h:297
uint8_t * data
Definition TinyGPU.h:296
A resolution with the max frame size reported to the host.
Definition TinyGPU.h:326
uint32_t maxFrameSize
Definition TinyGPU.h:329
size_t width
Definition TinyGPU.h:327
size_t height
Definition TinyGPU.h:328
One video format (UVC format descriptor) with its resolutions.
Definition UVCDefs.h:194
uint8_t frameCount
Definition UVCDefs.h:196
UVCFrameSpec frames[6]
Definition UVCDefs.h:197
One resolution (UVC frame descriptor) with its supported frame rates.
Definition UVCDefs.h:148
uint16_t width
Definition UVCDefs.h:149
uint16_t height
Definition UVCDefs.h:150
uint32_t maxFrameSize
Max size of one frame in bytes, reported to the host for buffer sizing.
Definition UVCDefs.h:152
The format, resolution and frame rate the host selected.
Definition UVCDefs.h:201
uint8_t frameIndex
Definition UVCDefs.h:209
uint8_t formatIndex
1-based UVC indexes as used in the probe/commit control
Definition UVCDefs.h:208
UVCFormat format
Definition UVCDefs.h:202
uint32_t interval
Frame interval in 100ns units.
Definition UVCDefs.h:206
Maps a TinyGPU color type to the matching PixelFormat.
Definition TinyGPU.h:77