TinyUVC 0.1.0
Header-only USB Video Class (UVC) device: turn an MCU into a USB webcam
Loading...
Searching...
No Matches
UVCDevice.h
Go to the documentation of this file.
1#pragma once
9#include <atomic>
10#include <initializer_list>
11
12#include "UVCDescriptor.h"
13#include "UVCLogger.h"
14#include "UVCPayload.h"
15
16namespace tinyuvc {
17
18class UVCDevice;
19
21namespace platform {
23bool begin(UVCDevice &dev);
25void end(UVCDevice &dev);
27uint16_t maxPacketSize();
29void idle();
30uint32_t millis();
31uint32_t micros();
33uint8_t *allocBuffer(size_t size);
34void freeBuffer(uint8_t *buf);
38struct AppLock {
39 AppLock();
40 ~AppLock();
41 AppLock(const AppLock &) = delete;
42 AppLock &operator=(const AppLock &) = delete;
44 alignas(8) uint8_t state[24];
45};
46} // namespace platform
47
49struct UVCRequest {
50 uint8_t bmRequestType = 0;
51 uint8_t bRequest = 0;
52 uint16_t wValue = 0;
53 uint16_t wIndex = 0;
54 uint16_t wLength = 0;
55
56 enum Type : uint8_t { Standard = 0, Class = 1, Vendor = 2 };
57 enum Recipient : uint8_t { Device = 0, Interface = 1, Endpoint = 2 };
58 uint8_t type() const { return (bmRequestType >> 5) & 0x03; }
59 uint8_t recipient() const { return bmRequestType & 0x1F; }
60 bool isIn() const { return (bmRequestType & 0x80) != 0; }
61};
62
64enum class UVCControlResult : uint8_t {
65 Stall,
66 DataIn,
67 DataOut,
68 Status,
69 Handled,
70};
71
95class UVCDevice {
96 public:
97 UVCDevice() = default;
98 ~UVCDevice() { end(); }
99 UVCDevice(const UVCDevice &) = delete;
100 UVCDevice &operator=(const UVCDevice &) = delete;
101
102 // ------------------------------------------------------------ setup
103
107 bool addResolution(UVCFormat format, uint16_t width, uint16_t height,
108 uint8_t fps, uint32_t maxFrameSize = 0) {
109 return addResolution(format, width, height, {fps}, maxFrameSize);
110 }
111
113 bool addResolution(UVCFormat format, uint16_t width, uint16_t height,
114 std::initializer_list<uint8_t> fpsList,
115 uint32_t maxFrameSize = 0) {
116 return addResolution(format, width, height, fpsList.begin(),
117 fpsList.size(), maxFrameSize);
118 }
119
121 bool addResolution(UVCFormat format, uint16_t width, uint16_t height,
122 const uint8_t *fpsList, size_t fpsCount,
123 uint32_t maxFrameSize = 0) {
124 if (active_) {
125 TINYUVC_LOGE("addResolution() must be called before begin()");
126 return false;
127 }
128 bool anyFps = false;
129 for (size_t i = 0; i < fpsCount; i++) anyFps |= fpsList[i] != 0;
130 if (width == 0 || height == 0 || !anyFps) {
131 TINYUVC_LOGE("addResolution(): invalid size or no frame rate");
132 return false;
133 }
134 if (format == UVCFormat::YUY2 && (width & 1)) {
135 TINYUVC_LOGE("addResolution(): YUY2 needs an even width");
136 return false;
137 }
138 UVCFormatSpec *f = findFormat(format);
139 if (f == nullptr) {
141 TINYUVC_LOGE("too many formats (TINYUVC_MAX_FORMATS)");
142 return false;
143 }
144 f = &formats_[formatCount_++];
145 *f = UVCFormatSpec();
146 f->format = format;
147 }
148 if (f->frameCount >= TINYUVC_MAX_FRAMES) {
149 TINYUVC_LOGE("too many resolutions (TINYUVC_MAX_FRAMES)");
150 return false;
151 }
152 UVCFrameSpec &fr = f->frames[f->frameCount];
153 fr = UVCFrameSpec();
154 fr.width = width;
155 fr.height = height;
156 const uint32_t raw = (uint32_t)width * height * 2;
157 fr.maxFrameSize = format == UVCFormat::YUY2 ? raw
158 : maxFrameSize != 0 ? maxFrameSize
159 : raw;
160 for (size_t i = 0; i < fpsCount; i++) {
161 if (fpsList[i] == 0 || fr.intervalCount >= TINYUVC_MAX_INTERVALS) continue;
162 fr.intervals[fr.intervalCount++] = fpsToInterval(fpsList[i]);
163 }
164 f->frameCount++;
165 return true;
166 }
167
170 if (!active_) formatCount_ = 0;
171 }
172
175 void setName(const char *name) { name_ = name; }
176 const char *name() const { return name_; }
177
180 void setPayloadSize(uint32_t size) { payloadSizeCfg_ = size; }
181 uint32_t payloadSize() const { return payloadSize_; }
182
184 void setTimestamps(bool enabled) { withPts_ = enabled; }
185
188 void setStreamCallback(void (*cb)(bool streaming,
190 void *ref),
191 void *ref = nullptr) {
192 streamCb_ = cb;
193 streamCbRef_ = ref;
194 }
195
198 bool begin() {
199 if (active_) return true;
200 if (formatCount_ == 0) {
201 TINYUVC_LOGE("begin(): no resolution defined - call addResolution()");
202 return false;
203 }
204 UVCDevice *&inst = instance();
205 if (inst != nullptr && inst != this) {
206 TINYUVC_LOGE("begin(): only one UVCDevice can be active");
207 return false;
208 }
211 // end() keeps the buffer if a transfer was still in flight: reuse it
212 if (buffer_ == nullptr || bufferSize_ < payloadSize_) {
213 if (buffer_ != nullptr && !inFlight_.load()) platform::freeBuffer(buffer_);
215 bufferSize_ = buffer_ != nullptr ? payloadSize_ : 0;
216 }
217 if (buffer_ == nullptr) {
218 TINYUVC_LOGE("begin(): could not allocate %u bytes", (unsigned)payloadSize_);
219 return false;
220 }
222 commit_ = probe_;
223 inst = this;
224 active_ = true;
225 if (!platform::begin(*this)) {
226 TINYUVC_LOGE("begin(): USB registration failed");
227 active_ = false;
228 inst = nullptr;
230 buffer_ = nullptr;
231 bufferSize_ = 0;
232 return false;
233 }
234 TINYUVC_LOGI("UVC device started: %d format(s), payload %u, packet %u",
235 formatCount_, (unsigned)payloadSize_, (unsigned)maxPacketSize_);
236 return true;
237 }
238
240 void end() {
241 if (!active_) return;
242 stopStream();
243 platform::end(*this);
244 active_ = false;
245 if (instance() == this) instance() = nullptr;
246 // a transfer in flight still reads the buffer: then it is kept and
247 // reused by the next begin()
248 if (!inFlight_.load()) {
250 buffer_ = nullptr;
251 bufferSize_ = 0;
252 }
253 }
254
255 // ------------------------------------------------------------ streaming
256
258 bool isActive() const { return active_; }
259
261 bool isStreaming() const { return streaming_.load(); }
262
265 bool isReady() const { return streaming_.load() && !framePending_.load(); }
266
269 bool isSending() const { return framePending_.load(); }
270
273
275 uint32_t streamGeneration() const { return generation_.load(); }
276
287 bool writeFrame(const uint8_t *data, size_t len, PixelFormat fmt) {
288 if (!isReady()) return false;
289 if (data == nullptr || len == 0) return false;
291 if (s.format == UVCFormat::MJPEG) {
292 if (fmt != PixelFormat::MJPEG) {
293 TINYUVC_LOGW("writeFrame(): host expects MJPEG, got %s", toString(fmt));
294 dropped_++;
295 return false;
296 }
297 if (len > maxFrameSize_) {
298 TINYUVC_LOGW("writeFrame(): JPEG of %u bytes exceeds max frame size %u",
299 (unsigned)len, (unsigned)maxFrameSize_);
300 dropped_++;
301 return false;
302 }
303 } else {
304 const size_t expected = (size_t)s.width * s.height * bytesPerPixel(fmt);
305 if (fmt == PixelFormat::MJPEG || len != expected) {
306 TINYUVC_LOGW("writeFrame(): host expects %ux%u YUY2: got %u bytes %s",
307 s.width, s.height, (unsigned)len, toString(fmt));
308 dropped_++;
309 return false;
310 }
311 }
312 frameData_ = data;
313 frameLen_ = len;
314 frameFmt_ = fmt;
316 framePending_.store(true);
318 kick();
319 return true;
320 }
321
323 bool waitReady(uint32_t timeoutMs) {
324 uint32_t start = platform::millis();
325 while (!isReady()) {
326 if (!isStreaming()) return false;
327 if (platform::millis() - start >= timeoutMs) return false;
329 }
330 return true;
331 }
332
334 uint32_t framesSent() const { return sent_; }
336 uint32_t framesDropped() const { return dropped_; }
337
339 const UVCFormatSpec *formats() const { return formats_; }
340 uint8_t formatCount() const { return formatCount_; }
341
342 // ------------------------------------------------- USB glue interface
343 // Called by UVCTinyUSB.h and the platform layers - not by sketches.
344
346 static UVCDevice *&instance() {
347 static UVCDevice *dev = nullptr;
348 return dev;
349 }
350
352 uint16_t descriptorLength() const {
354 p.formats = formats_;
357 }
358
361 uint16_t buildDescriptor(uint8_t *buf, uint16_t bufLen, uint8_t controlItf,
362 uint8_t endpointIn, uint16_t maxPacketSize,
363 uint8_t stringIndex) {
364 controlItf_ = controlItf;
365 endpoint_ = (uint8_t)(endpointIn | 0x80);
367 p.controlInterface = controlItf;
369 p.maxPacketSize = maxPacketSize;
370 p.stringIndex = stringIndex;
371 p.formats = formats_;
373 return UVCDescriptorBuilder::build(p, buf, bufLen);
374 }
375
376 uint8_t controlInterface() const { return controlItf_; }
377 uint8_t streamingInterface() const { return (uint8_t)(controlItf_ + 1); }
378 uint8_t endpoint() const { return endpoint_; }
379
381 using XferFn = bool (*)(uint8_t ep, uint8_t *buf, uint16_t len);
382
384 void usbOpened(XferFn xfer, uint16_t maxPacketSize) {
385 xfer_ = xfer;
386 if (maxPacketSize != 0 && maxPacketSize != maxPacketSize_) {
387 // e.g. a high speed device that enumerated at full speed
388 maxPacketSize_ = maxPacketSize;
389 }
390 TINYUVC_LOGI("USB configured (interfaces %d/%d, endpoint 0x%02x)",
392 }
393
395 void usbReset() {
396 stopStream();
397 inFlight_.store(false);
398 framePending_.store(false);
399 zlpPending_ = false;
400 encoder_.abort();
401 }
402
405 uint16_t &len) {
406 data = ctrlBuf_;
407 len = 0;
408 if (r.type() == UVCRequest::Standard) return handleStandard(r, data, len);
411
412 const uint8_t itf = (uint8_t)(r.wIndex & 0xFF);
413 const uint8_t entity = (uint8_t)(r.wIndex >> 8);
414 const uint8_t selector = (uint8_t)(r.wValue >> 8);
415
416 if (itf == controlInterface()) {
417 if (entity == 0 && selector == uvc_spec::VC_REQUEST_ERROR_CODE_CONTROL) {
418 if (r.bRequest == uvc_spec::GET_CUR) return reply(&errorCode_, 1, r, data, len);
419 if (r.bRequest == uvc_spec::GET_INFO) {
420 static const uint8_t info = 0x01; // GET supported
421 return reply(&info, 1, r, data, len);
422 }
423 }
424 // the camera and output terminal have no controls
425 return stall(entity == 0 ? uvc_spec::ERR_INVALID_CONTROL
429 }
430
431 if (itf == streamingInterface() && entity == 0 &&
432 (selector == uvc_spec::VS_PROBE_CONTROL || selector == uvc_spec::VS_COMMIT_CONTROL)) {
433 const bool probe = selector == uvc_spec::VS_PROBE_CONTROL;
434 switch (r.bRequest) {
436 if (r.wLength == 0) return stall(uvc_spec::ERR_INVALID_REQUEST);
437 len = r.wLength < sizeof(ctrlBuf_) ? r.wLength : sizeof(ctrlBuf_);
441 return replyProbe(probe ? probe_ : commit_, r, data, len);
443 return replyProbe(negotiate(UVCProbeCommit()), r, data, len);
445 return replyProbe(limit(false), r, data, len);
447 return replyProbe(limit(true), r, data, len);
448 case uvc_spec::GET_RES: {
449 UVCProbeCommit res; // all zero: no resolution steps
450 return replyProbe(res, r, data, len);
451 }
452 case uvc_spec::GET_LEN: {
453 uint8_t l[2];
455 return reply(l, 2, r, data, len);
456 }
457 case uvc_spec::GET_INFO: {
458 const uint8_t info = 0x03; // GET and SET supported
459 return reply(&info, 1, r, data, len);
460 }
461 default:
463 }
464 }
467 }
468
471 bool handleControlData(const UVCRequest &r, uint16_t len) {
472 if (r.type() != UVCRequest::Class || r.bRequest != uvc_spec::SET_CUR) return true;
473 const uint8_t itf = (uint8_t)(r.wIndex & 0xFF);
474 const uint8_t selector = (uint8_t)(r.wValue >> 8);
475 if (itf != streamingInterface()) return false;
477 memcpy(in.raw, ctrlBuf_,
479 if (selector == uvc_spec::VS_PROBE_CONTROL) {
480 probe_ = negotiate(in);
481 TINYUVC_LOGD("probe: format %d frame %d interval %u", probe_.formatIndex(),
482 probe_.frameIndex(), (unsigned)probe_.frameInterval());
483 return true;
484 }
485 if (selector == uvc_spec::VS_COMMIT_CONTROL) {
486 commit_ = negotiate(in);
488 return true;
489 }
490 return false;
491 }
492
494 void usbTransferComplete(bool ok) {
495 if (!ok) {
496 // the frame in progress is incomplete
497 if (encoder_.active()) {
498 encoder_.abort();
499 finishFrame(false);
500 }
501 zlpPending_ = false;
502 }
503 if (!startTransfer()) {
504 inFlight_.store(false);
505 kick();
506 }
507 }
508
509 protected:
511 uint8_t formatCount_ = 0;
514 uint32_t payloadSize_ = 0;
515 uint16_t maxPacketSize_ = 64;
516 bool withPts_ = false;
517 bool active_ = false;
518 uint8_t *buffer_ = nullptr;
519 uint32_t bufferSize_ = 0;
520 XferFn xfer_ = nullptr;
521
522 uint8_t controlItf_ = 0;
523 uint8_t endpoint_ = 0x81;
525 uint8_t ctrlBuf_[48] = {};
529 uint32_t maxFrameSize_ = 0;
530
531 void (*streamCb_)(bool, const UVCStreamSettings &, void *) = nullptr;
532 void *streamCbRef_ = nullptr;
533
534 // shared between app context and USB context
535 std::atomic<bool> streaming_{false};
536 std::atomic<bool> framePending_{false};
537 std::atomic<bool> inFlight_{false};
538 std::atomic<uint32_t> generation_{0};
539 const uint8_t *volatile frameData_ = nullptr;
540 volatile size_t frameLen_ = 0;
542 volatile uint32_t framePts_ = 0;
543 volatile uint32_t sent_ = 0;
544 volatile uint32_t dropped_ = 0;
545
546 // owned by whoever holds inFlight_
548 uint32_t encoderGeneration_ = 0;
549 bool fid_ = false;
550 bool zlpPending_ = false;
551
558 static uint32_t effectivePayloadSize(uint32_t requested, uint16_t mps) {
559 uint32_t size = requested;
560 if (size > 32u * mps) size = 32u * mps;
561 if (size < 2u * mps) size = 2u * mps;
562 return size - size % mps;
563 }
564
566 for (int i = 0; i < formatCount_; i++)
567 if (formats_[i].format == format) return &formats_[i];
568 return nullptr;
569 }
570
571 UVCControlResult stall(uint8_t error) {
572 errorCode_ = error;
574 }
575
576 UVCControlResult reply(const void *src, uint16_t n, const UVCRequest &r,
577 uint8_t *&data, uint16_t &len) {
578 if (n > sizeof(ctrlBuf_)) n = sizeof(ctrlBuf_);
579 memcpy(ctrlBuf_, src, n);
580 data = ctrlBuf_;
581 len = n < r.wLength ? n : r.wLength;
584 }
585
587 uint8_t *&data, uint16_t &len) {
588 return reply(pc.raw, uvc_spec::PROBE_COMMIT_SIZE, r, data, len);
589 }
590
592 uint16_t &len) {
593 constexpr uint8_t GET_INTERFACE = 0x0A, SET_INTERFACE = 0x0B;
594 if (r.recipient() == UVCRequest::Endpoint) {
595 // CLEAR_FEATURE(ENDPOINT_HALT): how hosts stop a bulk stream
596 constexpr uint8_t CLEAR_FEATURE = 0x01;
597 if (r.bRequest == CLEAR_FEATURE && (r.wIndex & 0xFF) == endpoint_) {
598 TINYUVC_LOGI("host stopped the stream (clear halt)");
599 stopStream();
600 }
602 }
603 if (r.recipient() == UVCRequest::Interface) {
604 if (r.bRequest == SET_INTERFACE) {
605 if (r.wValue != 0) return stall(uvc_spec::ERR_INVALID_REQUEST);
606 if ((r.wIndex & 0xFF) == streamingInterface() && isStreaming()) {
607 TINYUVC_LOGI("host stopped the stream (set interface)");
608 stopStream();
609 }
611 }
612 if (r.bRequest == GET_INTERFACE) {
613 const uint8_t alt = 0;
614 return reply(&alt, 1, r, data, len);
615 }
616 }
618 }
619
622 UVCProbeCommit out;
623 uint8_t fi = in.formatIndex();
624 if (fi < 1 || fi > formatCount_) fi = 1;
625 const UVCFormatSpec &fmt = formats_[fi - 1];
626 uint8_t fr = in.frameIndex();
627 if (fr < 1 || fr > fmt.frameCount) fr = 1;
628 const UVCFrameSpec &frame = fmt.frames[fr - 1];
629 uint32_t interval = in.frameInterval() == 0
630 ? frame.intervals[0]
631 : frame.closestInterval(in.frameInterval());
632 out.setHint(in.bmHint());
633 out.setFormatIndex(fi);
634 out.setFrameIndex(fr);
635 out.setFrameInterval(interval);
639 out.setFramingInfo(0x03); // FID required, EOF may be present
640 out.setVersions(1, 1, 1);
641 return out;
642 }
643
645 UVCProbeCommit limit(bool max) const {
647 const uint8_t fi = max ? formatCount_ : 1;
648 const UVCFormatSpec &fmt = formats_[fi - 1];
649 const uint8_t fr = max ? fmt.frameCount : 1;
650 in.setFormatIndex(fi);
651 in.setFrameIndex(fr);
652 const UVCFrameSpec &frame = fmt.frames[fr - 1];
653 in.setFrameInterval(max ? frame.maxInterval() : frame.minInterval());
654 return negotiate(in);
655 }
656
657 void startStream(const UVCProbeCommit &pc) {
658 const UVCFormatSpec &fmt = formats_[pc.formatIndex() - 1];
659 const UVCFrameSpec &fr = fmt.frames[pc.frameIndex() - 1];
661 s.format = fmt.format;
662 s.width = fr.width;
663 s.height = fr.height;
664 s.interval = pc.frameInterval();
665 s.formatIndex = pc.formatIndex();
666 s.frameIndex = pc.frameIndex();
667 settings_ = s;
669 generation_.fetch_add(1);
670 streaming_.store(true);
671 TINYUVC_LOGI("host started %s %ux%u @ %u fps", toString(s.format), s.width,
672 s.height, (unsigned)s.fps());
673 if (streamCb_) streamCb_(true, s, streamCbRef_);
674 kick();
675 }
676
677 void stopStream() {
678 if (!streaming_.load()) return;
679 streaming_.store(false);
680 generation_.fetch_add(1);
682 kick(); // releases a pending frame if no transfer is in flight
683 }
684
685 void finishFrame(bool complete) {
686 framePending_.store(false);
687 if (complete)
688 sent_ = sent_ + 1;
689 else
690 dropped_ = dropped_ + 1;
691 }
692
696 const uint32_t gen = generation_.load();
697 if (encoder_.active() && encoderGeneration_ != gen) {
698 // the host restarted or stopped the stream in the middle of a frame
699 encoder_.abort();
700 zlpPending_ = false;
701 finishFrame(false);
702 }
703 if (!streaming_.load()) {
704 zlpPending_ = false;
705 if (framePending_.load() && !encoder_.active()) finishFrame(false);
706 return false;
707 }
708 if (xfer_ == nullptr || buffer_ == nullptr) return false;
709 if (zlpPending_) {
710 zlpPending_ = false;
711 return xfer_(endpoint_, buffer_, 0);
712 }
713 if (!encoder_.active()) {
714 if (!framePending_.load()) return false;
715 fid_ = !fid_;
717 encoderGeneration_ = gen;
718 }
719 size_t len = encoder_.fill(buffer_, payloadSize_);
720 if (!encoder_.active()) {
721 // last payload: the frame data is no longer needed
722 finishFrame(true);
723 // a transfer that ends on a packet boundary needs a zero length packet,
724 // or the host keeps waiting for the rest of the payload
725 zlpPending_ = len < payloadSize_ && (len % maxPacketSize_) == 0;
726 }
727 if (xfer_(endpoint_, buffer_, (uint16_t)len)) return true;
728 TINYUVC_LOGW("transfer failed");
729 zlpPending_ = false;
730 if (encoder_.active()) {
731 encoder_.abort();
732 finishFrame(false);
733 }
734 return false;
735 }
736
738 void kick() {
739 for (int i = 0; i < 3; i++) {
740 bool expected = false;
741 if (!inFlight_.compare_exchange_strong(expected, true)) return;
742 if (startTransfer()) return;
743 inFlight_.store(false);
744 // something might have arrived while we owned inFlight_
745 if (!(framePending_.load() && streaming_.load())) return;
746 }
747 }
748};
749
750} // namespace tinyuvc
#define TINYUVC_MAX_FRAMES
Max number of resolutions (frame descriptors) per format.
Definition UVCConfig.h:16
#define TINYUVC_MAX_FORMATS
Max number of video formats (e.g. MJPEG + YUY2) a UVCDevice offers.
Definition UVCConfig.h:11
#define TINYUVC_MAX_INTERVALS
Max number of frame rates per resolution.
Definition UVCConfig.h:21
#define TINYUVC_DEFAULT_NAME
Definition UVCConfig.h:44
#define TINYUVC_PAYLOAD_SIZE
Definition UVCConfig.h:32
Builds the USB descriptors of a UVC 1.1 camera function: an Interface Association,...
Minimal printf-style logger. On Arduino it writes to a Print (default: Serial), on the desktop to std...
#define TINYUVC_LOGI(...)
Definition UVCLogger.h:79
#define TINYUVC_LOGE(...)
Definition UVCLogger.h:75
#define TINYUVC_LOGD(...)
Definition UVCLogger.h:81
#define TINYUVC_LOGW(...)
Definition UVCLogger.h:77
Splits one video frame into UVC payloads (payload header + data).
static uint16_t length(const UVCDescriptorParams &p)
Length in bytes of the descriptors for the given parameters.
Definition UVCDescriptor.h:39
static uint16_t build(const UVCDescriptorParams &p, uint8_t *buf, uint16_t bufLen)
Definition UVCDescriptor.h:45
static constexpr uint32_t kClockFrequency
dwClockFrequency reported in the headers: 1 MHz (PTS in microseconds)
Definition UVCDescriptor.h:138
USB Video Class (UVC 1.1) device - a USB webcam.
Definition UVCDevice.h:95
uint32_t bufferSize_
Definition UVCDevice.h:519
uint8_t formatCount() const
Definition UVCDevice.h:340
bool handleControlData(const UVCRequest &r, uint16_t len)
Definition UVCDevice.h:471
uint32_t payloadSizeCfg_
Definition UVCDevice.h:513
bool isStreaming() const
true while the host is streaming (between commit and stop)
Definition UVCDevice.h:261
void finishFrame(bool complete)
Definition UVCDevice.h:685
const UVCFormatSpec * formats() const
Formats as defined with addResolution()
Definition UVCDevice.h:339
UVCPayloadEncoder encoder_
Definition UVCDevice.h:547
static UVCDevice *& instance()
The active device.
Definition UVCDevice.h:346
uint32_t payloadSize_
Definition UVCDevice.h:514
void setPayloadSize(uint32_t size)
Definition UVCDevice.h:180
bool fid_
Definition UVCDevice.h:549
void usbOpened(XferFn xfer, uint16_t maxPacketSize)
The host configured the device: the bulk endpoint is open.
Definition UVCDevice.h:384
void usbTransferComplete(bool ok)
A transfer on our endpoint completed.
Definition UVCDevice.h:494
void * streamCbRef_
Definition UVCDevice.h:532
uint8_t controlItf_
Definition UVCDevice.h:522
UVCFormatSpec formats_[2]
Definition UVCDevice.h:510
uint8_t controlInterface() const
Definition UVCDevice.h:376
uint32_t encoderGeneration_
Definition UVCDevice.h:548
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, const uint8_t *fpsList, size_t fpsCount, uint32_t maxFrameSize=0)
Adds a resolution with fpsCount frame rates; the first is the default.
Definition UVCDevice.h:121
std::atomic< bool > streaming_
Definition UVCDevice.h:535
uint8_t formatCount_
Definition UVCDevice.h:511
UVCFormatSpec * findFormat(UVCFormat format)
Definition UVCDevice.h:565
volatile uint32_t dropped_
Definition UVCDevice.h:544
std::atomic< bool > inFlight_
Definition UVCDevice.h:537
const char * name() const
Definition UVCDevice.h:176
UVCDevice & operator=(const UVCDevice &)=delete
uint32_t framesDropped() const
Number of frames that were rejected or aborted.
Definition UVCDevice.h:336
void clearResolutions()
Removes all formats/resolutions (before begin())
Definition UVCDevice.h:169
bool active_
Definition UVCDevice.h:517
uint32_t framesSent() const
Number of frames that were completely sent.
Definition UVCDevice.h:334
bool isActive() const
true if begin() succeeded
Definition UVCDevice.h:258
uint8_t endpoint_
Definition UVCDevice.h:523
static uint32_t effectivePayloadSize(uint32_t requested, uint16_t mps)
Definition UVCDevice.h:558
UVCStreamSettings settings() const
Format, resolution and frame rate the host selected.
Definition UVCDevice.h:272
uint8_t endpoint() const
Definition UVCDevice.h:378
void startStream(const UVCProbeCommit &pc)
Definition UVCDevice.h:657
uint16_t maxPacketSize_
Definition UVCDevice.h:515
uint32_t payloadSize() const
Definition UVCDevice.h:181
UVCDevice(const UVCDevice &)=delete
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, uint8_t fps, uint32_t maxFrameSize=0)
Definition UVCDevice.h:107
volatile uint32_t framePts_
Definition UVCDevice.h:542
UVCControlResult handleControlSetup(const UVCRequest &r, uint8_t *&data, uint16_t &len)
Handles the setup stage of a request to our interfaces/endpoint.
Definition UVCDevice.h:404
void(* streamCb_)(bool, const UVCStreamSettings &, void *)
Definition UVCDevice.h:531
UVCProbeCommit probe_
Definition UVCDevice.h:526
volatile uint32_t sent_
Definition UVCDevice.h:543
XferFn xfer_
Definition UVCDevice.h:520
~UVCDevice()
Definition UVCDevice.h:98
uint16_t descriptorLength() const
Length of the function descriptors.
Definition UVCDevice.h:352
bool startTransfer()
Definition UVCDevice.h:695
UVCProbeCommit limit(bool max) const
GET_MIN / GET_MAX values.
Definition UVCDevice.h:645
uint8_t * buffer_
Definition UVCDevice.h:518
UVCControlResult stall(uint8_t error)
Definition UVCDevice.h:571
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
const char * name_
Definition UVCDevice.h:512
volatile size_t frameLen_
Definition UVCDevice.h:540
void usbReset()
Bus reset / unconfigured.
Definition UVCDevice.h:395
uint8_t errorCode_
Definition UVCDevice.h:524
void stopStream()
Definition UVCDevice.h:677
UVCControlResult replyProbe(const UVCProbeCommit &pc, const UVCRequest &r, uint8_t *&data, uint16_t &len)
Definition UVCDevice.h:586
bool waitReady(uint32_t timeoutMs)
Waits until isReady() (true) or the timeout or end of streaming (false)
Definition UVCDevice.h:323
bool withPts_
Definition UVCDevice.h:516
UVCProbeCommit negotiate(const UVCProbeCommit &in) const
Validates/completes a probe or commit structure from the host.
Definition UVCDevice.h:621
uint16_t buildDescriptor(uint8_t *buf, uint16_t bufLen, uint8_t controlItf, uint8_t endpointIn, uint16_t maxPacketSize, uint8_t stringIndex)
Definition UVCDevice.h:361
void setTimestamps(bool enabled)
Adds a presentation time stamp (PTS, microseconds) to every payload.
Definition UVCDevice.h:184
std::atomic< bool > framePending_
Definition UVCDevice.h:536
bool zlpPending_
Definition UVCDevice.h:550
UVCStreamSettings settings_
Definition UVCDevice.h:528
void kick()
Starts a transfer if none is in flight (callable from any context)
Definition UVCDevice.h:738
bool isSending() const
Definition UVCDevice.h:269
bool begin()
Definition UVCDevice.h:198
uint8_t streamingInterface() const
Definition UVCDevice.h:377
uint8_t ctrlBuf_[48]
Definition UVCDevice.h:525
bool addResolution(UVCFormat format, uint16_t width, uint16_t height, std::initializer_list< uint8_t > fpsList, uint32_t maxFrameSize=0)
Adds a resolution with several frame rates; the first is the default.
Definition UVCDevice.h:113
void setStreamCallback(void(*cb)(bool streaming, const UVCStreamSettings &settings, void *ref), void *ref=nullptr)
Definition UVCDevice.h:188
bool(*)(uint8_t ep, uint8_t *buf, uint16_t len) XferFn
Transfer function: starts an IN transfer, returns false on error.
Definition UVCDevice.h:381
const uint8_t *volatile frameData_
Definition UVCDevice.h:539
UVCControlResult handleStandard(const UVCRequest &r, uint8_t *&data, uint16_t &len)
Definition UVCDevice.h:591
void setName(const char *name)
Definition UVCDevice.h:175
void end()
Stops the camera function.
Definition UVCDevice.h:240
std::atomic< uint32_t > generation_
Definition UVCDevice.h:538
bool isReady() const
Definition UVCDevice.h:265
volatile PixelFormat frameFmt_
Definition UVCDevice.h:541
UVCControlResult reply(const void *src, uint16_t n, const UVCRequest &r, uint8_t *&data, uint16_t &len)
Definition UVCDevice.h:576
uint32_t streamGeneration() const
Incremented whenever the host starts or stops a stream.
Definition UVCDevice.h:275
uint32_t maxFrameSize_
Definition UVCDevice.h:529
UVCProbeCommit commit_
Definition UVCDevice.h:527
Produces the UVC payloads of one frame. Each payload starts with a 2 byte header (6 bytes with a pres...
Definition UVCPayload.h:21
bool active() const
true while the frame still has data to send
Definition UVCPayload.h:76
void abort()
Aborts the current frame.
Definition UVCPayload.h:78
size_t fill(uint8_t *buf, size_t maxLen)
Definition UVCPayload.h:49
void begin(const uint8_t *data, size_t len, PixelFormat fmt, bool fid, bool withPts=false, uint32_t pts=0)
Definition UVCPayload.h:26
void put16(uint8_t *p, uint16_t v)
Definition UVCDefs.h:225
void freeBuffer(uint8_t *buf)
Definition UVCPlatformDesktop.h:56
bool begin(UVCDevice &)
Registers the UVC function with the USB stack (and starts it if needed)
Definition UVCPlatformDesktop.h:29
uint8_t * allocBuffer(size_t size)
Allocates the transfer buffer (DMA capable, aligned)
Definition UVCPlatformDesktop.h:53
void end(UVCDevice &)
Unregisters the UVC function, where the USB stack supports that.
Definition UVCPlatformDesktop.h:30
uint16_t maxPacketSize()
Max packet size of the bulk endpoint (64 full speed, 512 high speed)
Definition UVCPlatformDesktop.h:31
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
constexpr uint8_t GET_CUR
Definition UVCDefs.h:43
constexpr uint8_t GET_DEF
Definition UVCDefs.h:49
constexpr uint8_t VC_REQUEST_ERROR_CODE_CONTROL
Definition UVCDefs.h:51
constexpr uint8_t VS_COMMIT_CONTROL
Definition UVCDefs.h:53
constexpr uint8_t GET_MIN
Definition UVCDefs.h:44
constexpr uint8_t ERR_INVALID_REQUEST
Definition UVCDefs.h:59
constexpr uint8_t ERR_NONE
Definition UVCDefs.h:55
constexpr uint8_t GET_LEN
Definition UVCDefs.h:47
constexpr uint8_t GET_MAX
Definition UVCDefs.h:45
constexpr uint16_t PROBE_COMMIT_SIZE
Size of the probe/commit control structure for UVC 1.1.
Definition UVCDefs.h:72
constexpr uint8_t ERR_INVALID_UNIT
Definition UVCDefs.h:57
constexpr uint8_t ERR_INVALID_CONTROL
Definition UVCDefs.h:58
constexpr uint8_t VS_PROBE_CONTROL
Definition UVCDefs.h:52
constexpr uint8_t GET_RES
Definition UVCDefs.h:46
constexpr uint8_t ID_OUTPUT_TERMINAL
Definition UVCDefs.h:70
constexpr uint8_t SET_CUR
Definition UVCDefs.h:42
constexpr uint8_t GET_INFO
Definition UVCDefs.h:48
TinyUVC: USB Video Class (UVC) device for Arduino and the desktop.
const char * toString(PixelFormat fmt)
Name of a pixel format, for logging.
Definition UVCDefs.h:112
constexpr uint8_t bytesPerPixel(PixelFormat fmt)
Bytes per pixel of a raw pixel format (0 for JPEG)
Definition UVCDefs.h:103
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)
constexpr uint32_t fpsToInterval(uint32_t fps)
Frame interval in 100ns units for a frame rate.
Definition UVCDefs.h:138
UVCControlResult
What the USB glue has to do with a setup request.
Definition UVCDevice.h:64
@ DataIn
send data/len to the host
@ DataOut
receive wLength bytes into data, then call handleControlData()
@ Handled
nothing to do (the USB stack acknowledges itself)
@ Status
no data stage: just acknowledge
Input of UVCDescriptorBuilder::build()
Definition UVCDescriptor.h:14
uint8_t formatCount
Definition UVCDescriptor.h:26
uint8_t stringIndex
String index for the function and interface names (0 = none)
Definition UVCDescriptor.h:23
uint8_t controlInterface
Definition UVCDescriptor.h:17
const UVCFormatSpec * formats
The formats to offer.
Definition UVCDescriptor.h:25
uint16_t maxPacketSize
Max packet size of the bulk endpoint (64 full speed, 512 high speed)
Definition UVCDescriptor.h:21
uint8_t endpointIn
Address of the bulk IN endpoint (with bit 7 set)
Definition UVCDescriptor.h:19
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
UVCFormat format
Definition UVCDefs.h:195
One resolution (UVC frame descriptor) with its supported frame rates.
Definition UVCDefs.h:148
uint32_t closestInterval(uint32_t interval) const
Supported interval that is closest to the requested one.
Definition UVCDefs.h:165
uint32_t intervals[4]
Supported frame intervals in 100ns units; intervals[0] is the default.
Definition UVCDefs.h:156
uint16_t width
Definition UVCDefs.h:149
uint32_t minInterval() const
Definition UVCDefs.h:179
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
uint32_t maxInterval() const
Definition UVCDefs.h:185
uint8_t intervalCount
Number of valid entries in intervals[].
Definition UVCDefs.h:154
Video probe and commit control (UVC 1.1, 34 bytes). Kept as a byte array in USB (little endian) layou...
Definition UVCDefs.h:247
uint32_t frameInterval() const
Definition UVCDefs.h:253
void setVersions(uint8_t preferred, uint8_t min, uint8_t max)
Definition UVCDefs.h:272
void setFramingInfo(uint8_t v)
Definition UVCDefs.h:271
void setFrameInterval(uint32_t v)
Definition UVCDefs.h:262
uint8_t raw[uvc_spec::PROBE_COMMIT_SIZE]
Definition UVCDefs.h:248
void setFormatIndex(uint8_t v)
Definition UVCDefs.h:260
void setFrameIndex(uint8_t v)
Definition UVCDefs.h:261
uint8_t frameIndex() const
Definition UVCDefs.h:252
void setMaxPayloadTransferSize(uint32_t v)
Definition UVCDefs.h:269
void setMaxVideoFrameSize(uint32_t v)
Definition UVCDefs.h:268
void setHint(uint16_t v)
Definition UVCDefs.h:259
uint16_t bmHint() const
Definition UVCDefs.h:250
void setClockFrequency(uint32_t v)
Definition UVCDefs.h:270
uint8_t formatIndex() const
Definition UVCDefs.h:251
Setup request as seen by UVCDevice (independent of the USB stack)
Definition UVCDevice.h:49
uint8_t bRequest
Definition UVCDevice.h:51
bool isIn() const
Definition UVCDevice.h:60
Recipient
Definition UVCDevice.h:57
@ Endpoint
Definition UVCDevice.h:57
@ Interface
Definition UVCDevice.h:57
@ Device
Definition UVCDevice.h:57
Type
Definition UVCDevice.h:56
@ Standard
Definition UVCDevice.h:56
@ Class
Definition UVCDevice.h:56
@ Vendor
Definition UVCDevice.h:56
uint16_t wLength
Definition UVCDevice.h:54
uint16_t wValue
Definition UVCDevice.h:52
uint16_t wIndex
Definition UVCDevice.h:53
uint8_t type() const
Definition UVCDevice.h:58
uint8_t bmRequestType
Definition UVCDevice.h:50
uint8_t recipient() const
Definition UVCDevice.h:59
The format, resolution and frame rate the host selected.
Definition UVCDefs.h:201
uint8_t frameIndex
Definition UVCDefs.h:209
uint16_t width
Definition UVCDefs.h:203
uint8_t formatIndex
1-based UVC indexes as used in the probe/commit control
Definition UVCDefs.h:208
uint32_t fps() const
Frame rate (frames per second, rounded)
Definition UVCDefs.h:211
uint16_t height
Definition UVCDefs.h:204
UVCFormat format
Definition UVCDefs.h:202
uint32_t interval
Frame interval in 100ns units.
Definition UVCDefs.h:206
Serializes app context calls into the USB stack against the USB task, for USB stacks that need that (...
Definition UVCDevice.h:38
AppLock(const AppLock &)=delete
~AppLock()
Definition UVCPlatformDesktop.h:59
AppLock()
Definition UVCPlatformDesktop.h:58
AppLock & operator=(const AppLock &)=delete
uint8_t state[24]
storage for the platform's lock object
Definition UVCDevice.h:44