Ocean
Loading...
Searching...
No Matches
VideoDevice.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#ifndef META_OCEAN_SYSTEM_USB_VIDEO_VIDEO_DEVICE_H
9#define META_OCEAN_SYSTEM_USB_VIDEO_VIDEO_DEVICE_H
10
14
16
17#include "ocean/base/Memory.h"
18
19namespace Ocean
20{
21
22namespace System
23{
24
25namespace USB
26{
27
28namespace Video
29{
30
31// Forward declaration.
32class VideoDevice;
33
34/**
35 * Definition of a shared pointer holding a VideoDevice.
36 * @see VideoDevice
37 * @ingroup systemusbvideo
38 */
39using SharedVideoDevice = std::shared_ptr<VideoDevice>;
40
41/**
42 * This class implements a USB video device.
43 * The device allows to select individual stream configurations, to start a stream, and to receive samples from the stream.
44 * @ingroup systemusbvideo
45 */
46class OCEAN_SYSTEM_USB_VIDEO_EXPORT VideoDevice : public Device
47{
48 protected:
49
50 // Forward declaration.
51 class PayloadHeader;
52
53 public:
54
55 /**
56 * Definition of individual USB UVC device stream types.
57 */
58 enum DeviceStreamType : uint32_t
59 {
60 /// An invalid stream type.
61 DST_INVALID = 0u,
62 /// A stream composed of uncompressed video frames.
64 /// A stream based on MJpeg.
66 /// A stream based on advanced compression like H.264 or H.265
67 DST_FRAME_BASED
68 };
69
70 /**
71 * This class holds the data of a media sample.
72 */
73 class OCEAN_SYSTEM_USB_VIDEO_EXPORT Sample
74 {
75 friend class VideoDevice;
76
77 public:
78
79 /**
80 * Default constructor creating an invalid sample object.
81 */
82 Sample() = default;
83
84 /**
85 * Creates a new sample associated with a specific stream configuration.
86 * @param capacity The maximal capacity of the sample, in bytes, with range [0, infinity)
87 * @param descriptorFormatIndex The video format index specifying the format descriptor of the stream delivering this sample, must be valid
88 * @param descriptorFrameIndex The video frame index specifying the frame descriptor of the stream delivering this sample, must be valid
89 * @param dwClockFrequency The clock frequency of the stream, in Hz, with range [1, infinity)
90 */
91 explicit Sample(const size_t capacity, const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, const uint32_t dwClockFrequency);
92
93 /**
94 * Returns the video format index specifying the format descriptor of the stream delivering this sample.
95 * @return The sample's format index
96 */
97 inline uint8_t descriptorFormatIndex() const;
98
99 /**
100 * Returns the video frame index specifying the frame descriptor of the stream delivering this sample, must be valid.
101 * @return The sample's frame index
102 */
103 inline uint8_t descriptorFrameIndex() const;
104
105 /**
106 * Determines the timestamp the sample was captured.
107 * @return The sample's capture timestamp
108 */
110
111 /**
112 * Returns whether a payload delay is plausible.
113 * The delay corrects the host timestamp, an implausible delay would move the timestamp further than the correction is worth.
114 * @param sPayloadDelay The delay to check, in seconds
115 * @return True, if so
116 */
117 static bool isPlausiblePayloadDelay(const double sPayloadDelay);
118
119 /**
120 * Returns the buffer of this sample.
121 * @return The sample's buffer
122 */
123 inline const void* data() const;
124
125 /**
126 * Returns the size of the sample.
127 * @return The sample's size, in bytes
128 */
129 inline size_t size() const;
130
131 /**
132 * Returns whether this sample may contain errors (e.g., because there was a transmission error).
133 * @return True, if so
134 */
135 inline bool mayContainError() const;
136
137 /**
138 * Returns a string with the relevant information of this sample.
139 * @return The string with the relevant information
140 */
141 std::string toString() const;
142
143 protected:
144
145 /**
146 * Appends a payload packet to the sample.
147 * @param payloadHeader The payload header of the packet
148 * @param data The actual payload data to append, must be valid
149 * @param size The size of the payload data to append, in bytes, with range [1, infinity)
150 * @return True, if succeeded
151 */
152 bool append(const PayloadHeader& payloadHeader, const void* data, const size_t size);
153
154 /**
155 * Resets the sample so that it can be reused.
156 */
157 void reset();
158
159 /**
160 * Adopts the stream a pooled sample is reused for.
161 * A sample outlives the stream it was created for, and its clock scales the timestamps while its descriptor indices select the decoder, so both have to follow the stream it is handed to.
162 * @param descriptorFormatIndex The video format index of the stream now delivering this sample, must be valid
163 * @param descriptorFrameIndex The video frame index of the stream now delivering this sample, must be valid
164 * @param dwClockFrequency The clock frequency of the stream now delivering this sample, in Hz, with range [1, infinity)
165 * @param capacity The maximal capacity the stream needs, in bytes, with range [0, infinity)
166 */
167 void adoptStream(const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, const uint32_t dwClockFrequency, const size_t capacity);
168
169 protected:
170
171 /**
172 * Unwraps two timestamps while both are wrapped around 2^32.
173 * @param timestampA The first timestamp, with input range [0, 2^32-1] and output range [0, 2^33-1]
174 * @param timestampB The second timestamp, with input range [0, 2^32-1] and output range [0, 2^33-1]
175 * @return Which timestamp was unwrapped, 0 for timestampA, 1 for timestampB and -1 if no timestamp needed to be unwrapped
176 */
177 static int unwrapTimestamps(uint64_t& timestampA, uint64_t& timestampB);
178
179 /**
180 * Returns the earlier timestamp of the two given timestamps while both timestamps are wrapped around 2^32.
181 * @param timestampA The first timestamp, with range [0, 2^31-1]
182 * @param timestampB The second timestamp, with range [0, 2^31-1]
183 * @return The earlier of both timestamps
184 */
185 static uint64_t earlierTimestamp(const uint64_t timestampA, const uint64_t timestampB);
186
187 public:
188
189 /// The payload buffer which can be appended with payload packets.
190 std::vector<uint8_t> buffer_;
191
192 /// The current position inside the payload buffer, with range [0, data_.size() - 1].
193 size_t position_ = 0;
194
195 /// True, if the sample may contain any error.
196 bool mayContainError_ = false;
197
198 /// The device's timestamp when capturing began (taken from dwPresentationTime).
199 uint64_t captureDeviceTime_ = uint64_t(-1);
200
201 /// Up to two device timestamps when the first and last payload packets were delivered/received (taken from scrSourceClock).
202 uint64_t payloadDeviceTimes_[2] = {uint64_t(-1), uint64_t(-1)};
203
204 /// Up to two host/local unix timestamps when the first and last payload packets were received.
205 Timestamp payloadHostTimestamps_[2] = {Timestamp(false), Timestamp(false)};
206
207 //// The index of the next device timestamps, with range [0, 1]
208 size_t nextDeviceTimeIndex_ = 0;
209
210 /// True, to allow the buffer to be resized if incoming data does not fit into the buffer.
211 bool allowToResize_ = false;
212
213 /// The video format index specifying the format descriptor of the stream delivering this sample.
214 uint8_t descriptorFormatIndex_ = 0u;
215
216 /// The video frame index specifying the frame descriptor of the stream delivering this sample.
217 uint8_t descriptorFrameIndex_ = 0u;
218
219 /// The dwClockFrequency field of the VideoProbe Control response in Hz (the frequency of captureDeviceTime_ and payloadDeviceTimes_), with range [1, infinity)
220 uint32_t dwClockFrequency_ = 0u;
221 };
222
223 /**
224 * Definition of a shared pointer holding a Sample.
225 */
226 using SharedSample = std::shared_ptr<Sample>;
227
228 /**
229 * Definition of a vector holding samples.
230 */
231 using Samples = std::vector<SharedSample>;
232
233 /**
234 * Definition of a queue holding samples.
235 */
236 using SampleQueue = std::queue<SharedSample>;
237
238 /// The maximal size of the sample queue before queued samples will be dropped.
239 static constexpr size_t maximalSampleQueueSize_ = 10;
240
241 /**
242 * This class combines the video control interface functionality.
243 */
244 class OCEAN_SYSTEM_USB_VIDEO_EXPORT VideoControlInterface
245 {
246 friend class VideoDevice;
247
248 public:
249
250 /**
251 * Returns whether this interface object is valid
252 * @return True, if so
253 */
254 inline bool isValid() const;
255
256 protected:
257
258 /**
259 * Default constructor creating an invalid interface.
260 */
262
263 /**
264 * Creates a new video control interface based on a given interface descriptor.
265 * @param interfaceDescriptor The descriptor of the interface based on which this object will be created
266 * @param usbDeviceHandle The handle to the USB device associated with given interface descriptor
267 */
268 VideoControlInterface(const libusb_interface_descriptor& interfaceDescriptor, libusb_device_handle* usbDeviceHandle);
269
270 protected:
271
272 /// The descriptor of the header interface.
274
275 /// The input terminal descriptors.
276 std::vector<VCInputTerminalDescriptor> vcInputTerminalDescriptors_;
277
278 /// The selector unit descriptors.
279 std::vector<VCSelectorUnitDescriptor> vcSelectorUnitDescriptors_;
280
281 /// The processing unit descriptors.
282 std::vector<VCProcessingUnitDescriptor> vcProcessingUnitDescriptors_;
283
284 /// The extension unit descriptors.
285 std::vector<VCExtensionUnitDescriptor> vcExtensionUnitDescriptors_;
286
287 /// The index of the control interface.
288 uint8_t bInterfaceIndex_ = 0u;
289
290 /// The endpoint of the control interface.
291 uint8_t bEndpointAddress_ = 0u;
292
293 /// True, if this control interface object is valid.
294 bool isValid_ = false;
295 };
296
297 /**
298 * This class combines the video streaming interface functionality.
299 */
300 class OCEAN_SYSTEM_USB_VIDEO_EXPORT VideoStreamingInterface
301 {
302 friend class VideoDevice;
303
304 public:
305
306 /**
307 * Definition of a priority triple combining format index, frame index, and frame interval of a stream.
308 */
310
311 /**
312 * Definition of an ordered map mapping priorities to triples combining formats, frames, and intervals.
313 */
314 using PriorityMap = std::map<float, PriorityTriple>;
315
316 public:
317
318 /**
319 * This class implements the base class for all video streams.
320 */
322 {
323 public:
324
325 /// The color matching descriptor of the stream.
327 };
328
329 /**
330 * This class implements an uncompressed video stream.
331 */
333 {
334 public:
335
336 /// The format descriptor of the uncompressed stream.
338
339 /// The frame descriptors of the uncompressed stream.
340 std::vector<VSUncompressedVideoFrameDescriptor> vsUncompressedVideoFrameDescriptors_;
341 };
342
343 /**
344 * This class implements a frame-based video stream.
345 */
347 {
348 public:
349
350 /// The format descriptor of the frame-based stream.
352
353 /// The frame descriptors of the frame-based stream.
354 std::vector<VSFrameBasedFrameDescriptor> vsFrameBasedFrameDescriptors_;
355 };
356
357 /**
358 * This class implements a Mjpeg video stream.
359 */
361 {
362 public:
363
364 /// The format descriptor of the Mjpeg stream.
366
367 /// The frame descriptors of the Mjpeg stream.
368 std::vector<VSMJPEGVideoFrameDescriptor> vsMJPEGVideoFrameDescriptors_;
369 };
370
371 /**
372 * Definition of a vector holding UncompressedVideoStream objects.
373 */
374 using UncompressedVideoStreams = std::vector<UncompressedVideoStream>;
375
376 /**
377 * Definition of a vector holding FrameBasedVideoStream objects.
378 */
379 using FrameBasedVideoStreams = std::vector<FrameBasedVideoStream>;
380
381 /**
382 * Definition of a vector holding MJPEGVideoStream objects.
383 */
384 using MJPEGVideoStreams = std::vector<MJPEGVideoStream>;
385
386 public:
387
388 /**
389 * Returns the available uncompressed video streams.
390 * @return The interface's uncompressed video streams
391 */
392 inline const UncompressedVideoStreams& uncompressedVideoStreams() const;
393
394 /**
395 * Returns the available frame-based video streams.
396 * @return The interface's frame-based video streams
397 */
398 inline const FrameBasedVideoStreams& frameBasedVideoStreams() const;
399
400 /**
401 * Returns the available Mjpeg video streams.
402 * @return The interface's Mjpeg video streams
403 */
404 inline const MJPEGVideoStreams& mjpegVideoStreams() const;
405
406 /**
407 * Returns a priority map with best matching stream configurations.
408 * @param preferredWidth The preferred width, in pixel, 0 to use a default width, with range [0, infinity)
409 * @param preferredHeight The preferred height, in pixel, 0 to use a default height, with range [0, infinity)
410 * @param preferredFrameRate The preferred frame rate, in Hz, 0 to use a default frame rate, with range [0, infinity)
411 * @param deviceStreamType The stream type to be used, ST_INVALID to allow any stream type
412 * @param pixelFormat The pixel format which needs to be used in case of an uncompressed stream, FORMAT_UNDEFINED to use any pixel format
413 * @param encodingFormat The encoding format which needs to be used in case of an frame-based stream, EF_INVALID to allow any encoding format
414 * @return The map with best matching stream configurations, the higher the key the better the match
415 */
416 PriorityMap findBestMatchingStream(const unsigned int preferredWidth, const unsigned int preferredHeight, const double preferredFrameRate, const DeviceStreamType deviceStreamType = DST_INVALID, const FrameType::PixelFormat pixelFormat = FrameType::FORMAT_UNDEFINED, VSFrameBasedVideoFormatDescriptor::EncodingFormat encodingFormat = VSFrameBasedVideoFormatDescriptor::EF_INVALID);
417
418 /**
419 * Returns whether this interface object is valid.
420 * @return True, if so
421 */
422 inline bool isValid() const;
423
424 protected:
425
426 /**
427 * Creates an invalid interface object.
428 */
430
431 /**
432 * Parses an additional interface and adds it to this streaming interface object.
433 * @param interfaceDescriptor The descriptor of the interface to be added
434 * @param usbDeviceHandle The handle to the USB device associated with given interface descriptor
435 */
436 bool parseAdditionalInterface(const libusb_interface_descriptor& interfaceDescriptor, libusb_device_handle* usbDeviceHandle);
437
438 /**
439 * Returns a factor describing how well the resolution of a descriptor matches a preferred image resolution.
440 * @param frameDescriptor The frame descriptor for which the factor will be determined
441 * @param preferredWidth The preferred width, in pixel, with range [0, infinity)
442 * @param preferredHeight The preferred height, in pixel, with range [0, infinity)
443 * @param defaultPixels The default number of pixels which is used as a reference resolution in case preferred width and height are zero, with range [1, infinity)
444 * @return The matching factor, the higher the better the match, with range [0, 1]
445 * @tparam T The data type of the descriptor
446 */
447 template <typename T>
448 static float determineResolutionFactor(const T& frameDescriptor, const unsigned int preferredWidth, const unsigned int preferredHeight, const unsigned int defaultPixels = 1280u * 720u);
449
450 /**
451 * Returns a factor describing how well one of the frame rates of a descriptor matches a preferred frame rate.
452 * @param frameDescriptor The frame descriptor for which the factor will be determined
453 * @param preferredFrameRate The preferred frame rate, in Hz, with range [0, infinity)
454 * @param frameInterval The resulting best matching frame interval, in 100ns
455 * @param defaultFrameRate The default frame rate which is used as a reference frame rate in case the preferred frame rate is zero, with range (0, infinity)
456 * @return The matching factor, the higher the better the match, with range [0, 1]
457 * @tparam T The data type of the descriptor
458 */
459 template <typename T>
460 static float determineFrameRateFactor(const T& frameDescriptor, const double preferredFrameRate, uint32_t& frameInterval, const double defaultFrameRate);
461
462 protected:
463
464 /// The descriptor of the input header interface.
466
467 /// The uncompressed video streams.
469
470 /// The frame-based video streams.
472
473 /// The Mjpeg-based video streams.
475
476 /// The index of the control interface.
477 uint8_t bInterfaceIndex_ = 0u;
478
479 /// The endpoint of the control interface.
480 uint8_t bEndpointAddress_ = 0u;
481 };
482
483 protected:
484
485 /// The maximal size the memory of a sample can have, in bytes.
486 static constexpr size_t sampleMaxPayloadSize_ = 1024 * 1024 * 10;
487
488 /**
489 * Definition of USB UVC Video Interface Subclass Codes.
490 */
492 {
493 /// Undefined
494 SC_UNDEFINED = 0x00u,
495 /// This code is used for interfaces that manage control operations for video streaming devices.
496 SC_VIDEOCONTROL = 0x01u,
497 /// This code is used for interfaces that handle video streaming data.
498 SC_VIDEOSTREAMING = 0x02u,
499 /// This code is used for a collection of video interfaces that are grouped together to form a single functional entity.
500 SC_VIDEO_INTERFACE_COLLECTION = 0x03u
501 };
502
503 enum ControlSelectors : uint8_t
504 {
505 VS_CONTROL_UNDEFINED = 0x00u,
506 /// Video Probe control.
507 VS_PROBE_CONTROL = 0x01u,
508 /// Video commit control.
509 VS_COMMIT_CONTROL = 0x02u,
510 VS_STILL_PROBE_CONTROL = 0x03u,
511 VS_STILL_COMMIT_CONTROL = 0x04u,
512 VS_STILL_IMAGE_TRIGGER_CONTROL = 0x05u,
513 VS_STREAM_ERROR_CODE_CONTROL = 0x06u,
514 VS_GENERATE_KEY_FRAME_CONTROL = 0x07u,
515 VS_UPDATE_FRAME_SEGMENT_CONTROL = 0x08u,
516 VS_SYNCH_DELAY_CONTROL = 0x09u
517 };
518
519#pragma pack(push)
520#pragma pack(1)
521
522 class OCEAN_SYSTEM_USB_VIDEO_EXPORT Control
523 {
524 public:
525
526 /**
527 * Definition of the individual Video Class-Specific Request Codes.
528 */
529 enum RequestCode : uint8_t
530 {
531 /// Undefined request code.
532 RC_UNDEFINED = 0u,
533 /// Set current.
534 RC_SET_CUR = 0x01u,
535 /// Get current.
536 RC_GET_CUR = 0x81u,
537 /// Get minimum.
538 RC_GET_MIN = 0x82u,
539 /// Get maximum.
540 RC_GET_MAX = 0x83u,
541 /// Get resolution.
542 RC_GET_RES = 0x84u,
543 /// Get length.
544 RC_GET_LEN = 0x85u,
545 /// Get information.
546 RC_GET_INFO = 0x86u,
547 /// Get default.
548 RC_GET_DEF = 0x87u
549 };
550
551 public:
552
553 /**
554 * Executes a control commit or probe request.
555 * @param usbDeviceHandle The hand of the USB device to which the request will be set
556 * @param bmRequestType The request type parameter
557 * @param bRequest The request parameter
558 * @param wValue The value parameter
559 * @param wIndex The index parameter
560 * @param buffer The control buffer, must be valid
561 * @param size The size of the control buffer, in bytes, with range [1, infinity)
562 * @param timeout The time the device is given to answer, in milliseconds, with range [1, infinity)
563 * @return True, if succeeded
564 *
565 * A timeout of zero would mean 'wait forever' in libusb, which is why the default is a real value.
566 * The default matches the five seconds USB 2.0 allows a device for a request with a data stage, cameras take that long for controls which reconfigure the sensor.
567 */
568 static bool executeControl(libusb_device_handle* usbDeviceHandle, const uint8_t bmRequestType, const uint8_t bRequest, const uint16_t wValue, const uint16_t wIndex, void* buffer, const size_t size, const unsigned int timeout = 5000u);
569 };
570
571 /**
572 * Video Probe and Commit Controls.
573 *
574 * The streaming parameters selection process is based on a shared negotiation model between the host and the video streaming interface, taking into account the following features:
575 * - shared nature of the USB
576 * - interdependency of streaming parameters
577 * - payload independence
578 * - modification of streaming parameters during streaming
579 * This negotiation model is supported by the Video Probe and Commit controls.
580 * The Probe control allows retrieval and negotiation of streaming parameters.
581 * When an acceptable combination of streaming parameters has been obtained, the Commit control is used to configure the hardware with the negotiated parameters from the Probe control
582 *
583 * @see http://www.cajunbot.com/wiki/images/8/85/USB_Video_Class_1.1.pdf
584 */
585 class OCEAN_SYSTEM_USB_VIDEO_EXPORT VideoControl : public Control
586 {
587 public:
588
589 /// The time a device is given to answer a single negotiation request, in milliseconds.
590 /// Shorter than the default of executeControl(), the negotiation is retried and start() has to stay inside the five second waits around it.
591 static constexpr unsigned int negotiationTimeout_ = 1000u;
592
593 /**
594 * Returns a string with the content of this object.
595 * @return The string holding the content of this object
596 */
597 std::string toString() const;
598
599 /**
600 * Executes a video commit control request.
601 * @param usbDeviceHandle The hand of the USB device to which the request will be set
602 * @param interfaceIndex The index of the interface to which the control request will be sent
603 * @param videoControl The control to be sent, must be valid
604 * @param videoControlSize The size of the control to be sent, in bytes, either 26 or 34
605 * @param bRequest The request parameter
606 * @return True, if succeeded
607 */
608 static bool executeVideoControlCommit(libusb_device_handle* usbDeviceHandle, const uint8_t interfaceIndex, const VideoControl& videoControl, const size_t videoControlSize, const uint8_t bRequest = RC_SET_CUR);
609
610 /**
611 * Executes a video probe control request.
612 * @param usbDeviceHandle The hand of the USB device to which the request will be set
613 * @param interfaceIndex The index of the interface to which the control request will be sent
614 * @param videoControl The resulting control
615 * @param videoControlSize The size of the control to be sent, in bytes, either 26 or 34
616 * @param bRequest The request parameter
617 * @return True, if succeeded
618 */
619 static bool executeVideoControlProbe(libusb_device_handle* usbDeviceHandle, const uint8_t interfaceIndex, VideoControl& videoControl, const size_t videoControlSize, const uint8_t bRequest = RC_GET_CUR);
620
621 /**
622 * Proposes a video control to the device, the first step of the UVC stream negotiation.
623 * The device answers with executeVideoControlProbe(), which reports the parameters it is willing to use.
624 * @param usbDeviceHandle The handle of the USB device to which the request will be sent
625 * @param interfaceIndex The index of the interface to which the control request will be sent
626 * @param videoControl The control to be proposed, must be valid
627 * @param videoControlSize The size of the control to be sent, in bytes, either 26 or 34
628 * @return True, if succeeded
629 */
630 static bool proposeVideoControlProbe(libusb_device_handle* usbDeviceHandle, const uint8_t interfaceIndex, const VideoControl& videoControl, const size_t videoControlSize);
631
632 public:
633
634 /**
635 * Bitfield control indicating to the function what fields shall be kept fixed (indicative only):
636 * D0: dwFrameInterval
637 * D1: wKeyFrameRate
638 * D2: wPFrameRate
639 * D3: wCompQuality
640 * D4: wCompWindowSize
641 * D15..5: Reserved (0)
642 *
643 * The hint bitmap indicates to the video streaming interface which fields shall be kept constant during stream parameter negotiation.
644 * For example, if the selection wants to favor frame rate over quality, the dwFrameInterval bit will be set (1).
645 *
646 * This field is set by the host, and is read-only for the video streaming interface.
647 */
648 uint16_t bmHint_ = 0u;
649
650 /**
651 * Video format index from a format descriptor.
652 *
653 * Select a specific video stream format by setting this field to the one-based index of the associated format descriptor.
654 * To select the first format defined by a device, a value one (1) is written to this field. This field must be supported even if only one video format is supported by the device.
655 *
656 * This field is set by the host.
657 */
658 uint8_t bFormatIndex_ = 0u;
659
660 /**
661 * Video frame index from a frame descriptor.
662 *
663 * This field selects the video frame resolution from the array of resolutions supported by the selected stream.
664 * The index value ranges from 1 to the number of Frame descriptors following a particular Format descriptor.
665 * This field must be supported even if only one video frame index is supported by the device.
666 *
667 * For video payloads with no defined frame descriptor, this field shall be set to zero (0).
668 *
669 * This field is set by the host.
670 */
671 uint8_t bFrameIndex_ = 0u;
672
673 /**
674 * Frame interval in 100 ns units.
675 *
676 * This field sets the desired video frame interval for the selected video stream and frame index.
677 * The frame interval value is specified in 100 ns units.
678 * The device shall support the setting of all frame intervals reported in the Frame Descriptor corresponding to the selected Video Frame Index.
679 * This field must be implemented even if only one video frame interval is supported by the device.
680 *
681 * When used in conjunction with an IN endpoint, the host shall indicate its preference during the Probe phase.
682 * The value must be from the range of values supported by the device.
683 *
684 * When used in conjunction with an OUT endpoint, the host shall accept the value indicated by the device.
685 */
686 uint32_t dwFrameInterval_ = 0u;
687
688 /**
689 * Key frame rate in key-frame per videoframe units.
690 *
691 * This field is only applicable to sources (and formats) capable of streaming video with adjustable compression parameters.
692 * Use of this control is at the discretion of the device, and is indicated in the VS Input or Output Header descriptor.
693 *
694 * The Key Frame Rate field is used to specify the compressor’s key frame rate.
695 * For example, if one of every ten encoded frames in a video stream sequence is a key frame, this control would report a value of 10.
696 * A value of 0 indicates that only the first frame is a key frame.
697 *
698 * When used in conjunction with an IN endpoint, the host shall indicate its preference during the Probe phase.
699 * The value must be from the range of values supported by the device.
700 *
701 * When used in conjunction with an OUT endpoint, the host shall accept the value indicated by the device.
702 */
703 uint16_t wKeyFrameRate_ = 0u;
704
705 /**
706 * PFrame rate in PFrame/key frame units.
707 *
708 * This field is only applicable to sources (and formats) capable of streaming video with adjustable compression parameters.
709 * Use of this control is at the discretion of the device, and is indicated in the VS Input or Output Header descriptor.
710 *
711 * The P Frame Rate Control is used to specify the number of P frames per key frame.
712 * As an example of the relationship between the types of encoded frames, suppose a key frame occurs once in every 10 frames, and there are 3 P frames per key frame.
713 * The P frames will be spaced evenly between the key frames.
714 * The other 6 frames, which occur between the key frames and the P frames, will be bi-directional (B) frames.
715 *
716 * When used in conjunction with an IN endpoint, the host shall indicate its preference during the Probe phase.
717 * The value must be from the range of values supported by the device.
718 *
719 * When used in conjunction with an OUT endpoint, the host shall accept the value indicated by the device.
720 */
721 uint16_t wPFrameRate_ = 0u;
722
723 /**
724 * Compression quality control in abstract units 0 (lowest) to 10000 (highest).
725 *
726 * This field is only applicable to sources (and formats) capable of streaming video with adjustable compression parameters.
727 * Use of this field is at the discretion of the device, and is indicated in the VS Input or Output Header descriptor.
728 *
729 * This field is used to specify the quality of the video compression.
730 * Values for this property range from 0 to 10000 (0 indicates the lowest quality, 10000 the highest).
731 * The resolution reported by this control will determine the number of discrete quality settings that it can support.
732 *
733 * When used in conjunction with an IN endpoint, the host shall indicate its preference during the Probe phase.
734 * The value must be from the range of values supported by the device.
735 *
736 * When used in conjunction with an OUT endpoint, the host shall accept the value indicated by the device.
737 */
738 uint16_t wCompQuality_ = 0u;
739
740 /**
741 * Window size for average bit rate control.
742 *
743 * This field is only applicable to sources (and formats) capable of streaming video with adjustable compression parameters.
744 * Use of this control is at the discretion of the device, and is indicated in the VS Input or Output Header descriptor.
745 *
746 * The Compression Window Size Control is used to specify the number of encoded video frames over which the average size cannot exceed the specified data rate.
747 * For a window of size n, the average frame size of any consecutive n frames will not exceed the stream's specified data rate.
748 * Individual frames can be larger or smaller.
749 *
750 * For example, if the data rate has been set to 100 kilobytes per second (KBps) on a 10 frames per second (fps) movie with a compression window size of 10,
751 * the individual frames can be any size, as long as the average size of a frame in any 10-frame sequence is less than or equal to 10 kilobytes.
752 *
753 * When used in conjunction with an IN endpoint, the host shall indicate its preference during the Probe phase.
754 * The value must be from the range of values supported by the device.
755 *
756 * When used in conjunction with an OUT endpoint, the host shall accept the value indicated by the device.
757 */
758 uint16_t wCompWindowSize_ = 0u;
759
760 /**
761 * Internal video streaming interface latency in ms from video data capture to presentation on the USB.
762 *
763 * When used in conjunction with an IN endpoint, this field is set by the device and read only from the host.
764 *
765 * When used in conjunction with an OUT endpoint, this field is set by the host and read only from the device.
766 */
767 uint16_t wDelay_ = 0u;
768
769 /**
770 * Maximum video frame or codec-specific segment size in bytes.
771 *
772 * For frame-based formats, this field indicates the maximum size of a single video frame.
773 *
774 * For stream-based formats, and when this behavior is enabled via the bmFramingInfo field (below), this field indicates the maximum size of a single codec-specific segment.
775 * The sender is required to indicate a segment boundary via the FID bit in the payload header.
776 * This field is ignored (for stream-based formats) if the bmFramingInfo bits are not enabled.
777 *
778 * When used in conjunction with an IN endpoint, this field is set by the device and read only from the host.
779 *
780 * When used in conjunction with an OUT endpoint, this field is set by the host and read only from the device.
781 */
782 uint32_t dwMaxVideoFrameSize_ = 0u;
783
784 /**
785 * Specifies the maximum number of bytes that the device can transmit or receive in a single payload transfer.
786 *
787 * This field is set by the device and read only from the host.
788 * Some host implementations restrict the maximum value permitted for this field.
789 */
790 uint32_t dwMaxPayloadTransferSize_ = 0u;
791
792 /**
793 * The device clock frequency in Hz for the specified format.
794 * This will specify the units used for the time information fields in the Video Payload Headers in the data stream.
795 *
796 * This parameter is set by the device and read only from the host.
797 */
798 uint32_t dwClockFrequency_ = 0u;
799
800 /**
801 * Bitfield control supporting the following values:
802 * D0:
803 * If set to 1, the Frame ID (FID) field is required in the Payload Header (see description of D0 in section 2.4.3.3, “Video and Still Image Payload Headers”).
804 * The sender is required to toggle the Frame ID at least every 'dwMaxVideoFrameSize' bytes (see above).
805 *
806 * D1:
807 * If set to 1, indicates that the End of Frame (EOF) field may be present in the Payload Header (see description of D1 in section 2.4.3.3, “Video and Still Image Payload Headers”).
808 * It is an error to specify this bit without also specifying D0.
809 *
810 * D7..2: Reserved (0)
811 *
812 * This control indicates to the function whether payload transfers will contain out-of-band framing information in the Video Payload Header (see section 2.4.3.3, “Video and Still Image Payload Headers”).
813 * For known frame-based formats (e.g., MJPEG, Uncompressed, DV), this control is ignored.
814 * For known stream-based formats, this control allows the sender to indicate that it will identify segment boundaries in the stream, enabling low-latency buffer handling by the receiver without the overhead of parsing the stream itself.
815 * When used in conjunction with an IN endpoint, this control is set by the device, and is read-only from the host.
816 * When used in conjunction with an OUT endpoint, this parameter is set by the host, and is read-only from the device.
817 */
818 uint8_t bmFramingInfo_ = 0u;
819
820 /**
821 * The preferred payload format version supported by the host or device for the specified bFormatIndex value.
822 *
823 * This parameter allows the host and device to negotiate a mutually agreed version of the payload format associated with the bFormatIndex field.
824 * The host initializes this and the following bMinVersion and bMaxVersion fields to zero on the first Probe Set.
825 * Upon Probe Get, the device shall return its preferred version, plus the minimum and maximum versions supported by the device (see bMinVersion and bMaxVersion below).
826 * The host may issue a subsequent Probe Set/Get sequence to specify its preferred version (within the ranges returned in bMinVersion and bMaxVersion from the initial Probe Set/Get sequence).
827 *
828 * The host is not permitted to alter the bMinVersion and bMaxVersion values.
829 *
830 * This field will support up to 256 (0-255) versions of a single payload format.
831 * The version number is drawn from the minor version of the Payload Format specification. For example, version 1.2 of a Payload Format specification would result in a value of 2 for this parameter.
832 */
833 uint8_t bPreferedVersion_ = 0u;
834
835 /**
836 * The minimum payload format version supported by the device for the specified bFormatIndex value.
837 *
838 * This value is initialized to zero by the host and reset to a value in the range of 0 to 255 by the device.
839 * The host is not permitted to modify this value (other than to restart the negotiation by setting bPreferredVersion, bMinVersion and bMaxVersion to zero).
840 */
841 uint8_t bMinVersion_ = 0u;
842
843 /**
844 * The maximum payload format version supported by the device for the specified bFormatIndex value.
845 *
846 * This value is initialized to zero by the host and reset to a value in the range of 0 to 255 by the device.
847 * The host is not permitted to modify this value (other than to restart the negotiation by setting bPreferredVersion, bMinVersion and bMaxVersion to zero).
848 */
849 uint8_t bMaxVersion_ = 0u;
850 };
851
852 /**
853 * This class implements functions for a Camera Control terminal
854 */
855 class OCEAN_SYSTEM_USB_VIDEO_EXPORT CameraTerminalControl : public Control
856 {
857 public:
858
859 /**
860 * Executes a probe request for an auto focus interface.
861 * @param usbDeviceHandle The handle of the USB device, must be valid
862 * @param terminalId The id of the terminal to be used, must be valid
863 * @param interfaceIndex The index of the interface to be used, must be valid
864 * @param requestCode The request code to be used
865 * @param value The resulting value
866 * @return True, if succeeded
867 */
868 static bool getFocusAuto(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, bool& value);
869
870 /**
871 * Executes a commit request for an auto focus interface.
872 * @param usbDeviceHandle The handle of the USB device, must be valid
873 * @param terminalId The id of the terminal to be used, must be valid
874 * @param interfaceIndex The index of the interface to be used, must be valid
875 * @param value The value to set
876 * @return True, if succeeded
877 */
878 static bool setFocusAuto(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const bool value);
879
880 /**
881 * Executes a probe request for an absolute focus interface.
882 * @param usbDeviceHandle The handle of the USB device, must be valid
883 * @param terminalId The id of the terminal to be used, must be valid
884 * @param interfaceIndex The index of the interface to be used, must be valid
885 * @param requestCode The request code to be used
886 * @param value The resulting value
887 * @return True, if succeeded
888 */
889 static bool getFocusAbsolute(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint16_t& value);
890
891 /**
892 * Executes a commit request for an auto focus interface.
893 * @param usbDeviceHandle The handle of the USB device, must be valid
894 * @param terminalId The id of the terminal to be used, must be valid
895 * @param interfaceIndex The index of the interface to be used, must be valid
896 * @param value The value to set
897 * @return True, if succeeded
898 */
899 static bool setFocusAbsolute(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint16_t value);
900
901 /**
902 * Executes a probe request for an auto exposure interface.
903 * <pre>
904 * The setting for the attribute of the addressed Auto-Exposure Mode Control:
905 * D0: Manual Mode – manual Exposure Time, manual Iris
906 * D1: Auto Mode – auto Exposure Time, auto Iris
907 * D2: Shutter Priority Mode – manual Exposure Time, auto Iris
908 * D3: Aperture Priority Mode – auto Exposure Time, manual Iris
909 * D4..D7: Reserved, set to zero.
910 * </pre>
911 * @param usbDeviceHandle The handle of the USB device, must be valid
912 * @param terminalId The id of the terminal to be used, must be valid
913 * @param interfaceIndex The index of the interface to be used, must be valid
914 * @param requestCode The request code to be used
915 * @param value The resulting value
916 * @return True, if succeeded
917 */
918 static bool getAutoExposureMode(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint8_t& value);
919
920 /**
921 * Executes a commit request for an auto exposure interface.
922 * <pre>
923 * The setting for the attribute of the addressed Auto-Exposure Mode Control:
924 * D0: Manual Mode – manual Exposure Time, manual Iris
925 * D1: Auto Mode – auto Exposure Time, auto Iris
926 * D2: Shutter Priority Mode – manual Exposure Time, auto Iris
927 * D3: Aperture Priority Mode – auto Exposure Time, manual Iris
928 * D4..D7: Reserved, set to zero.
929 * </pre>
930 * @param usbDeviceHandle The handle of the USB device, must be valid
931 * @param terminalId The id of the terminal to be used, must be valid
932 * @param interfaceIndex The index of the interface to be used, must be valid
933 * @param value The value to set
934 * @return True, if succeeded
935 */
936 static bool setAutoExposureMode(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint8_t value);
937
938 /**
939 * Executes a probe request for an absolute exposure interface.
940 * @param usbDeviceHandle The handle of the USB device, must be valid
941 * @param terminalId The id of the terminal to be used, must be valid
942 * @param interfaceIndex The index of the interface to be used, must be valid
943 * @param requestCode The request code to be used
944 * @param value The resulting value
945 * @return True, if succeeded
946 */
947 static bool getExposureAbsolute(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint32_t& value);
948
949 /**
950 * Executes a commit request for an absolute exposure interface.
951 * @param usbDeviceHandle The handle of the USB device, must be valid
952 * @param terminalId The id of the terminal to be used, must be valid
953 * @param interfaceIndex The index of the interface to be used, must be valid
954 * @param value The value to set
955 * @return True, if succeeded
956 */
957 static bool setExposureAbsolute(libusb_device_handle* usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint32_t value);
958 };
959
960#pragma pack(pop)
961
962 static_assert(sizeof(VideoControl) == 34, "Invalid struct size!");
963
964 /**
965 * Video and Still Image Payload Headers.
966 * Every Payload Transfer containing video or still-image sample data must start with a Payload Header.
967 *
968 * @see http://www.cajunbot.com/wiki/images/8/85/USB_Video_Class_1.1.pdf
969 */
970 class OCEAN_SYSTEM_USB_VIDEO_EXPORT PayloadHeader
971 {
972 public:
973
974 /**
975 * Creates a new payload header object from memory.
976 * @param buffer The memory buffer in which the header is located, must be valid
977 * @param size The size of the buffer, in bytes, with range [1, infinity)
978 */
979 PayloadHeader(const uint8_t* buffer, const size_t size);
980
981 /**
982 * Returns whether the frame id toggling between 0 and 1 every time a new video frame begins.
983 * For frame-based formats, this bit toggles between 0 and 1 every time a new video frame begins.
984 * For stream-based formats, this bit toggles between 0 and 1 at the start of each new codec-specific segment.
985 * @return The frame id, with range [0, 1]
986 */
987 inline uint8_t toggledFrameId() const;
988
989 /**
990 * Returns whether the payload marks the end of the current video or still image frame.
991 * @return True, if so
992 */
993 inline bool isEndOfFrame() const;
994
995 /**
996 * Returns whether the dwPresentationTime field is being sent as part of the header.
997 * @return True, if so
998 */
999 inline bool hasPresentationTime() const;
1000
1001 /**
1002 * Returns whether the dwSourceClock field is being sent as part of the header.
1003 * @return True, if so
1004 */
1005 inline bool hasSourceClockReference() const;
1006
1007 /**
1008 * Returns whether the following data is part of a still image frame, and is only used for methods 2 and 3 of still image capture.
1009 */
1010 inline bool isStillImage() const;
1011
1012 /**
1013 * Returns whether there was an error in the video or still image transmission for this payload.
1014 * @return True, if so
1015 */
1016 inline bool hasError() const;
1017
1018 /**
1019 * Returns whether the payload is the last header group in the packet.
1020 * @return True, if so
1021 */
1022 inline bool isEndOfHeader() const;
1023
1024 /**
1025 * Returns the presentation time stamp (PTS).
1026 * @return The presentation time stamp, if hasPresentationTime() == true
1027 */
1028 inline uint32_t sourceTimeClock() const;
1029
1030 /**
1031 * Returns the bus frame counter part of the scrSourceClock field.
1032 * @return The bus frame counter, with range [0, 2^11-1], if hasPresentationTime() == true
1033 */
1034 inline uint16_t busFrameCounter() const;
1035
1036 public:
1037
1038 /**
1039 * Length of the payload header in bytes including this field.
1040 */
1041 uint8_t bHeaderLength_ = 0u;
1042
1043 /**
1044 * Provides information on the sample data following the header, as well as the availability of optional header fields in this header.
1045 *
1046 * D0:
1047 * Frame ID – For frame-based formats, this bit toggles between 0 and 1 every time a new video frame begins.
1048 * For stream-based formats, this bit toggles between 0 and 1 at the start of each new codec-specific segment.
1049 * This behavior is required for frame-based payload formats (e.g., DV) and is optional for stream-based payload formats (e.g., MPEG-2 TS).
1050 * For stream-based formats, support for this bit must be indicated via the bmFramingInfo field of the Video Probe and Commit controls (see section 4.3.1.1, “Video Probe and Commit Controls”).
1051 *
1052 * D1:
1053 * End of Frame – This bit is set if the following payload data marks the end of the current video or still image frame (for frame- based formats), or to indicate the end of a codec-specific segment (for stream-based formats).
1054 * This behavior is optional for all payload formats. For stream-based formats, support for this bit must be indicated via the bmFramingInfo field of the Video Probe and Commit Controls (see section 4.3.1.1, “Video Probe and Commit Controls”).
1055 *
1056 * D2:
1057 * Presentation Time – This bit is set if the dwPresentationTime field is being sent as part of the header.
1058 *
1059 * D3:
1060 * Source Clock Reference – This bit is set if the dwSourceClock field is being sent as part of the header.
1061 *
1062 * D4:
1063 * Reserved
1064 *
1065 * D5:
1066 * Still Image – This bit is set if the following data is part of a still image frame, and is only used for methods 2 and 3 of still image capture.
1067 *
1068 * D6:
1069 * Error – This bit is set if there was an error in the video or still image transmission for this payload.
1070 * The Stream Error Code control would reflect the cause of the error.
1071 *
1072 * D7:
1073 * End of header – This bit is set if this is the last header group in the packet, where the header group refers to this field and any optional fields identified by the bits in this field (Defined for future extension).
1074 */
1075 uint8_t bmHeaderInfo_ = 0u;
1076
1077 /**
1078 * Presentation Time Stamp (PTS).
1079 *
1080 * The source clock time in native device clock units when the raw frame capture begins.
1081 * This field may be repeated for multiple payload transfers comprising a single video frame, with the restriction that the value shall remain the same throughout that video frame.
1082 * The PTS is in the same units as specified in the dwClockFrequency field of the Video Probe Control response.
1083 */
1084 uint32_t dwPresentationTime_ = 0u;
1085
1086 /**
1087 * A two-part Source Clock Reference (SCR) value.
1088 *
1089 * D31..D0:
1090 * Source Time Clock in native device clock units.
1091 *
1092 * D42..D32:
1093 * 1KHz SOF token counter
1094 *
1095 * D47..D43: Reserved, set to zero.
1096 *
1097 * The least-significant 32 bits (D31..D0) contain clock values sampled from the System Time Clock (STC) at the source.
1098 * The clock resolution shall be according to the dwClockFrequency field of the Probe and Commit response of the device as defined in Table 4-47 of this specification.
1099 * This value shall comply with the associated stream payload specification.
1100 *
1101 * The times at which the STC is sampled must be correlated with the USB Bus Clock.
1102 * To that end, the next most significant 11 bits of the SCR (D42..D32) contain a 1 KHz SOF counter, representing the frame number at the time the STC was sampled.
1103 * The STC is sampled at arbitrary SOF boundaries.
1104 * The SOF counter is the same size and frequency as the frame number associated with USB SOF tokens; however it is not required to match the current frame number.
1105 * This allows implementations using a chipset that can trigger on SOF tokens (but not accurately obtain the Frame number) to keep their own frame counters.
1106 *
1107 * The most-significant 5 bits (D47..D43) are reserved, and must be set to zero.
1108 * The maximum interval between Payload Headers containing SCR values is 100ms, or the video frame interval, whichever is greater. Shorter intervals are permitted.
1109 */
1110 uint8_t scrSourceClock_[6] = {};
1111 };
1112
1113 public:
1114
1115 /**
1116 * Default constructor creating an invalid video device.
1117 */
1118 VideoDevice() = default;
1119
1120 /**
1121 * Creates a new video device based on a valid device.
1122 * @param device The device which will be converted into a video device, must be valid
1123 */
1124 explicit VideoDevice(Device&& device);
1125
1126 /**
1127 * Destructs this video device and releases all associated resources.
1128 */
1129 ~VideoDevice() override;
1130
1131 /**
1132 * Extracts the relevant properties for a specific stream this device supports.
1133 * @param descriptorFormatIndex The video format index specifying the format descriptor of the stream delivering this sample, must be valid
1134 * @param descriptorFrameIndex The video frame index specifying the frame descriptor of the stream delivering this sample, must be valid
1135 * @param width The resulting width of the stream, in pixels, with range [1, infinity)
1136 * @param height The resulting height of the stream, in pixels, with range [1, infinity)
1137 * @param pixelFormat The resulting pixel format of the stream, valid only if stream type is DST_UNCOMPRESSED
1138 * @param encodingFormat The resulting encoding format of the stream, valid only if stream type is DST_FRAME_BASED
1139 * @return The resulting stream type, DST_INVALID if the properties could not be extracted
1140 */
1141 DeviceStreamType extractStreamProperties(const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, unsigned int& width, unsigned int& height, FrameType::PixelFormat& pixelFormat, VSFrameBasedVideoFormatDescriptor::EncodingFormat& encodingFormat) const;
1142
1143 /**
1144 * Starts the video device.
1145 * In case, the device is already started, nothing will happen.
1146 * @param preferredWidth The preferred width of the stream, in pixel, with range [1, infinity), 0 to use a default width
1147 * @param preferredHeight The preferred height of the stream, in pixel, with range [1, infinity), 0 to use a default height
1148 * @param preferredFrameRate The preferred frame rate, in Hz, with range (0, infinity), 0 to use a default frame rate
1149 * @param preferredDeviceStreamType The preferred device stream type, DST_INVALID to use a default stream type
1150 * @param preferredPixelFormat The preferred pixel format, will be ignored for streams which do not have a device stream type DST_UNCOMPRESSED
1151 * @param preferredEncodingFormat The preferred encoding format, will be ignored for streams which do not have a device stream type DST_FRAME_BASED
1152 * @return True, if the stream could be started
1153 * @see isStarted(), stopStream(), extractStreamProperties().
1154 */
1155 bool start(const unsigned int preferredWidth = 0u, const unsigned int preferredHeight = 0u, const double preferredFrameRate = 0.0, const DeviceStreamType preferredDeviceStreamType = DST_INVALID, const FrameType::PixelFormat preferredPixelFormat = FrameType::FORMAT_UNDEFINED, const VSFrameBasedVideoFormatDescriptor::EncodingFormat preferredEncodingFormat = VSFrameBasedVideoFormatDescriptor::EF_INVALID);
1156
1157 /**
1158 * Stops the video device.
1159 * @return True, if succeeded
1160 */
1161 bool stop();
1162
1163 /**
1164 * Returns whether auto focus is activated or deactivated.
1165 * @param value The resulting auto focus state; True, if activated; False, if deactivated
1166 * @return True, if succeeded; False, if in case of an error or if the device does not support auto focus
1167 * @see setAutoFocus().
1168 */
1169 bool autoFocus(bool &value);
1170
1171 /**
1172 * Activate or deactivate the auto focus of this device.
1173 * @param value True, to activate the auto focus; False, to deactivate the auto focus
1174 * @return True, if succeeded; False, if in case of an error or if the device does not support auto focus
1175 * @see autoFocus().
1176 */
1177 bool setAutoFocus(const bool value);
1178
1179 /**
1180 * Sets the absolute focus of this device.
1181 * @param value The absolute focus value to set, in the domain of the device's focus range, with range [minValue, maxValue]
1182 * @return True, if succeeded; False, if in case of an error or if the device does not support to set the absolute focus
1183 * @see absoluteFocus().
1184 */
1185 bool setAbsoluteFocus(const float value);
1186
1187 /**
1188 * Returns the device's absolute focus.
1189 * @param minValue Optional resulting minimal focus value, in the domain of the device's focus range, nullptr if not of interest
1190 * @param currentValue Optional resulting current focus value, in the domain of the device's focus range, nullptr if not of interest
1191 * @param maxValue Optional resulting maximal focus value, in the domain of the device's focus range, nullptr if not of interest
1192 * @return True, if succeeded; False, if in case of an error or if the device does not support absolute focus
1193 * @see setAbsoluteFocus().
1194 */
1195 bool absoluteFocus(float* minValue, float* currentValue, float* maxValue);
1196
1197 /**
1198 * Returns the supported auto exposure modes.
1199 * @param value The resulting value with supported modes
1200 * @return True, if succeeded
1201 * @see setAutoExposureMode().
1202 */
1203 bool supportedAutoExposureModes(uint8_t& value) const;
1204
1205 /**
1206 * Returns the current auto exposure mode.
1207 * @param value The resulting value of the auto exposure mode
1208 * @return True, if succeeded; False, if in case of an error or if the device does not support the auto exposure mode
1209 * @see setAutoExposureMode(), supportedAutoExposureModes().
1210 */
1211 bool autoExposureMode(uint8_t &value) const;
1212
1213 /**
1214 * Sets the auto exposure mode.
1215 * @param value The value of the auto exposure mode to set
1216 * @return True, if succeeded; False, if in case of an error or if the device does not support the auto exposure mode
1217 * @see autoExposureMode(), supportedAutoExposureModes().
1218 */
1219 bool setAutoExposureMode(const uint8_t value);
1220
1221 /**
1222 * Returns the absolute exposure duration of this device.
1223 * @param minValue Optional resulting minimal exposure duration, in seconds, nullptr if not of interest
1224 * @param currentValue Optional resulting current exposure duration, in seconds, nullptr if not of interest
1225 * @param maxValue Optional resulting maximal exposure duration, in seconds, nullptr if not of interest
1226 * @return True, if succeeded
1227 * @see setAbsoluteExposure().
1228 */
1229 bool absoluteExposure(double* minValue, double* currentValue, double* maxValue);
1230
1231 /**
1232 * Sets the absolute exposure duration of this device.
1233 * @param value The exposure duration to be set, in seconds, with range (0, infinity), 0 for auto exposure
1234 * @return True, if succeeded
1235 * @see absoluteExposure().
1236 */
1237 bool setAbsoluteExposure(const double value);
1238
1239 /**
1240 * Returns the next sample from this device.
1241 * Once a sample has been processed, it should be given back to the device so that it can be reused by the device.
1242 * @param pendingSamples Optional resulting number of samples which are still in the queue (not including the returned sample), nullptr if not of interest
1243 * @return The next sample, nullptr if currently no sample is available
1244 * @see giveSampleBack().
1245 */
1246 SharedSample nextSample(size_t* pendingSamples = nullptr);
1247
1248 /**
1249 * Gives a sample back to this device so that it can be reused by the device.
1250 * @param sample The sample to give back, must be valid
1251 * @see nextSample().
1252 */
1254
1255 /**
1256 * Returns the video streaming interface functionality of this device.
1257 * @return The device's video streaming interface
1258 */
1259 inline const VideoStreamingInterface& videoStreamingInterface() const;
1260
1261 /**
1262 * Returns whether this video device has an active stream.
1263 * @return True, if so
1264 * @see startStream().
1265 */
1266 inline bool isStarted() const;
1267
1268 /**
1269 * Returns whether this video device is valid and ready to be used.
1270 * @return True, if so; False, if e.g., not all devices of the USB device could be accessed
1271 */
1272 inline bool isValid() const;
1273
1274 /**
1275 * Translates a device stream type to a string.
1276 * @param deviceStreamType The stream type to translate
1277 * @return The translated type as string, 'Invalid' if the type is invalid or unknown
1278 */
1279 static std::string translateDeviceStreamType(const DeviceStreamType deviceStreamType);
1280
1281 protected:
1282
1283 /**
1284 * Initializes the control interface.
1285 * @return True, if succeeded
1286 */
1288
1289 /**
1290 * Parses all interfaces of this device.
1291 * @return True, if succeeded
1292 */
1294
1295 /**
1296 * Releases everything start() has created before it failed.
1297 * Needs to be called with 'lock_' locked.
1298 */
1300
1301 /**
1302 * Parses a video interface of this device.
1303 * @param interfaceDescriptor The libusb interface descriptor of a video interface to parse, with bInterfaceClass == LIBUSB_CLASS_VIDEO
1304 * @return True, if succeeded
1305 */
1306 bool parseVideoInterface(const libusb_interface_descriptor& interfaceDescriptor);
1307
1308 /**
1309 * Processes the payload which has been received from the device via a USB transfer.
1310 * @param bufferPointers The buffers holding the payload, at least one
1311 */
1312 void processPayload(const BufferPointers& bufferPointers);
1313
1314 /**
1315 * Libusb status transfer callback function.
1316 * @param usbTransfer The transfer object which has been completed, failed, or canceled.
1317 * @return True, the transfer should be resubmitted
1318 */
1319 bool libStatusCallback(libusb_transfer& usbTransfer);
1320
1321 /**
1322 * Libusb stream transfer callback function.
1323 * The transfer is re-submitted from within this function, while the transfer lock is still held.
1324 * @param usbTransfer The transfer object which has been completed, failed, or canceled.
1325 */
1326 void libusbStreamCallback(libusb_transfer& usbTransfer);
1327
1328 /**
1329 * Static libusb status transfer callback function.
1330 * @param usbTransfer The transfer object which has been completed, failed, or canceled.
1331 */
1332 static void LIBUSB_CALL libStatusCallback(libusb_transfer* usbTransfer);
1333
1334 /**
1335 * Static libusb stream transfer callback function.
1336 * @param usbTransfer The transfer object which has been completed, failed, or canceled.
1337 */
1338 static void LIBUSB_CALL libusbStreamCallback(libusb_transfer* usbTransfer);
1339
1340 /**
1341 * Disabled copy constructor.
1342 */
1343 VideoDevice(const VideoDevice&) = delete;
1344
1345 /**
1346 * Disabled move constructor.
1347 */
1349
1350 /**
1351 * Disabled copy operator.
1352 * @return Reference to this object
1353 */
1355
1356 /**
1357 * Disabled move operator.
1358 * @return Reference to this object
1359 */
1361
1362 public:
1363
1364 /// The video control interface of this device.
1366
1367 /// The video streaming interface of this device.
1369
1370 /// True, if the control interface has been initialized.
1371 bool initializeControlInterfaceInitialized_ = false;
1372
1373 /// The libusb device configuration descriptor, nullptr if not yet initialized
1374 libusb_config_descriptor* usbConfigDescriptor_ = nullptr;
1375
1376 /// The index of the descriptor format which is currently active/streaming.
1377 uint8_t activeDescriptorFormatIndex_ = 0u;
1378
1379 /// The index of the descriptor frame which is currently active/streaming.
1380 uint8_t activeDescriptorFrameIndex_ = 0u;
1381
1382 /// The clock frequency of the active stream.
1383 uint32_t activeClockFrequency_ = 0u;
1384
1385 /// The maximal size of one sample.
1386 size_t maximalSampleSize_ = 0;
1387
1388 /// The transfer object for interrupts.
1390
1391 /// The buffer the interrupt transfer is writing into, one per device.
1392 uint8_t interruptTransferBuffer_[64] = {};
1393
1394 /// The lock for the stream and interrupt transfers, declared before everything it guards.
1396
1397 /// The streaming transfer objects.
1399
1400 /// The map mapping transfer pointers to indices.
1402
1403 /// The memory for the individual streaming transfer objects.
1404 std::vector<Memory> streamingTransferMemories_;
1405
1406 /// True, if the video device has an active stream which has been started.
1407 bool isStarted_ = false;
1408
1409 /// True, if the video device is currently stopping
1410 bool isStopping_ = false;
1411
1412 /// The lock for the samples, declared before everything it guards.
1414
1415 /// The currently active sample which is receiving sample data from the device (but not yet filled).
1417
1418 /// The queue with all processed samples waiting to be grabbed by an external entity.
1420
1421 /// The reusable samples which waiting to be filled.
1423
1424 /// Reusable buffer pointers to extract buffers from USB transfers.
1426
1427 /// The subscription for the detached kernel driver (if necessary/possible).
1429
1430 /// The subscription for the claimed video control interface.
1432
1433 /// The subscription for the claimed video stream interface.
1435};
1436
1438{
1439 constexpr uint8_t checkBit = (1u << 0u);
1440
1441 return bmHeaderInfo_ & checkBit;
1442}
1443
1445{
1446 constexpr uint8_t checkBit = (1u << 1u);
1447
1448 return (bmHeaderInfo_ & checkBit) != 0u;
1449}
1450
1452{
1453 constexpr uint8_t checkBit = (1u << 2u);
1454
1455 return (bmHeaderInfo_ & checkBit) != 0u;
1456}
1457
1459{
1460 constexpr uint8_t checkBit = (1u << 3u);
1461
1462 return (bmHeaderInfo_ & checkBit) != 0u;
1463}
1464
1466{
1467 constexpr uint8_t checkBit = (1u << 5u);
1468
1469 return (bmHeaderInfo_ & checkBit) != 0u;
1470}
1471
1473{
1474 constexpr uint8_t checkBit = (1u << 6u);
1475
1476 return (bmHeaderInfo_ & checkBit) != 0u;
1477}
1478
1480{
1481 constexpr uint8_t checkBit = (1u << 7u);
1482
1483 return (bmHeaderInfo_ & checkBit) != 0u;
1484}
1485
1487{
1488 ocean_assert(hasSourceClockReference());
1489
1490 uint32_t result;
1491 memcpy(&result, scrSourceClock_, sizeof(uint32_t));
1492
1493 return result;
1494}
1495
1497{
1498 ocean_assert(hasSourceClockReference());
1499
1500 uint16_t result;
1501 memcpy(&result, scrSourceClock_ + 4, sizeof(uint16_t));
1502
1503 return result & uint16_t(0x07FFu);
1504}
1505
1507{
1508 return descriptorFormatIndex_;
1509}
1510
1512{
1513 return descriptorFrameIndex_;
1514}
1515
1516inline const void* VideoDevice::Sample::data() const
1517{
1518 return buffer_.data();
1519}
1520
1521inline size_t VideoDevice::Sample::size() const
1522{
1523 return position_;
1524}
1525
1527{
1528 return mayContainError_;
1529}
1530
1532{
1533 return isValid_;
1534}
1535
1537{
1538 ocean_assert(isValid());
1539
1540 return uncompressedVideoStreams_;
1541}
1542
1544{
1545 ocean_assert(isValid());
1546
1547 return frameBasedVideoStreams_;
1548}
1549
1551{
1552 ocean_assert(isValid());
1553
1554 return mjpegVideoStreams_;
1555}
1556
1558{
1559 return vsInputHeaderDescriptor_.isValid();
1560}
1561
1566
1567inline bool VideoDevice::isStarted() const
1568{
1569 const ScopedLock scopedLock(lock_);
1570
1571 return isStarted_;
1572}
1573
1580
1581}
1582
1583}
1584
1585}
1586
1587}
1588
1589#endif // META_OCEAN_SYSTEM_USB_VIDEO_VIDEO_DEVICE_H
PixelFormat
Definition of all pixel formats available in the Ocean framework.
Definition Frame.h:183
This class implements a recursive lock object.
Definition Lock.h:31
This class implements a scoped lock object for recursive lock objects.
Definition Lock.h:147
This class wraps an unmanaged object (or reference) which needs to be released after usage.
Definition ScopedObject.h:156
This class implements a subscription object which can be used unique subscriptions to e....
Definition ScopedSubscription.h:28
This class wraps a libusb device.
Definition system/usb/Device.h:49
bool isValid() const
Returns whether this device is valid.
Definition system/usb/Device.h:383
Lock lock_
The device's lock.
Definition system/usb/Device.h:356
std::vector< BufferPointer > BufferPointers
Definition of a vector holding buffer pointers.
Definition system/usb/Device.h:72
Class-Specific VC Interface Descriptor (VC_HEADER).
Definition VCDescriptor.h:84
Color Matching Descriptor (VS_COLORFORMAT).
Definition VSDescriptor.h:761
Frame Based Payload Video Format Descriptor (VS_FORMAT_FRAME_BASED).
Definition VSDescriptor.h:492
EncodingFormat
Definition of individual encoding formats.
Definition VSDescriptor.h:499
Input Header Descriptor (VS_INPUT_HEADER).
Definition VSDescriptor.h:93
MJPEG Video Format Descriptor (VS_FORMAT_MJPEG).
Definition VSDescriptor.h:864
UncompressedVideoFormatDescriptor (VS_FORMAT_UNCOMPRESSED)
Definition VSDescriptor.h:235
This class implements functions for a Camera Control terminal.
Definition VideoDevice.h:856
static bool getFocusAbsolute(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint16_t &value)
Executes a probe request for an absolute focus interface.
static bool getFocusAuto(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, bool &value)
Executes a probe request for an auto focus interface.
static bool setFocusAbsolute(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint16_t value)
Executes a commit request for an auto focus interface.
static bool getAutoExposureMode(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint8_t &value)
Executes a probe request for an auto exposure interface.
static bool setAutoExposureMode(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint8_t value)
Executes a commit request for an auto exposure interface.
static bool getExposureAbsolute(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const RequestCode requestCode, uint32_t &value)
Executes a probe request for an absolute exposure interface.
static bool setFocusAuto(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const bool value)
Executes a commit request for an auto focus interface.
static bool setExposureAbsolute(libusb_device_handle *usbDeviceHandle, const uint8_t terminalId, const uint8_t interfaceIndex, const uint32_t value)
Executes a commit request for an absolute exposure interface.
static bool executeControl(libusb_device_handle *usbDeviceHandle, const uint8_t bmRequestType, const uint8_t bRequest, const uint16_t wValue, const uint16_t wIndex, void *buffer, const size_t size, const unsigned int timeout=5000u)
Executes a control commit or probe request.
RequestCode
Definition of the individual Video Class-Specific Request Codes.
Definition VideoDevice.h:530
Video and Still Image Payload Headers.
Definition VideoDevice.h:971
bool hasError() const
Returns whether there was an error in the video or still image transmission for this payload.
Definition VideoDevice.h:1472
PayloadHeader(const uint8_t *buffer, const size_t size)
Creates a new payload header object from memory.
bool isEndOfFrame() const
Returns whether the payload marks the end of the current video or still image frame.
Definition VideoDevice.h:1444
bool hasSourceClockReference() const
Returns whether the dwSourceClock field is being sent as part of the header.
Definition VideoDevice.h:1458
uint16_t busFrameCounter() const
Returns the bus frame counter part of the scrSourceClock field.
Definition VideoDevice.h:1496
bool isStillImage() const
Returns whether the following data is part of a still image frame, and is only used for methods 2 and...
Definition VideoDevice.h:1465
uint8_t toggledFrameId() const
Returns whether the frame id toggling between 0 and 1 every time a new video frame begins.
Definition VideoDevice.h:1437
uint32_t sourceTimeClock() const
Returns the presentation time stamp (PTS).
Definition VideoDevice.h:1486
bool hasPresentationTime() const
Returns whether the dwPresentationTime field is being sent as part of the header.
Definition VideoDevice.h:1451
uint8_t bmHeaderInfo_
Provides information on the sample data following the header, as well as the availability of optional...
Definition VideoDevice.h:1075
bool isEndOfHeader() const
Returns whether the payload is the last header group in the packet.
Definition VideoDevice.h:1479
This class holds the data of a media sample.
Definition VideoDevice.h:74
Sample()=default
Default constructor creating an invalid sample object.
std::string toString() const
Returns a string with the relevant information of this sample.
static uint64_t earlierTimestamp(const uint64_t timestampA, const uint64_t timestampB)
Returns the earlier timestamp of the two given timestamps while both timestamps are wrapped around 2^...
std::vector< uint8_t > buffer_
The payload buffer which can be appended with payload packets.
Definition VideoDevice.h:190
bool mayContainError() const
Returns whether this sample may contain errors (e.g., because there was a transmission error).
Definition VideoDevice.h:1526
void adoptStream(const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, const uint32_t dwClockFrequency, const size_t capacity)
Adopts the stream a pooled sample is reused for.
void reset()
Resets the sample so that it can be reused.
Sample(const size_t capacity, const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, const uint32_t dwClockFrequency)
Creates a new sample associated with a specific stream configuration.
bool append(const PayloadHeader &payloadHeader, const void *data, const size_t size)
Appends a payload packet to the sample.
static bool isPlausiblePayloadDelay(const double sPayloadDelay)
Returns whether a payload delay is plausible.
uint8_t descriptorFormatIndex() const
Returns the video format index specifying the format descriptor of the stream delivering this sample.
Definition VideoDevice.h:1506
size_t size() const
Returns the size of the sample.
Definition VideoDevice.h:1521
const void * data() const
Returns the buffer of this sample.
Definition VideoDevice.h:1516
Timestamp determineCaptureTimestamp() const
Determines the timestamp the sample was captured.
uint8_t descriptorFrameIndex() const
Returns the video frame index specifying the frame descriptor of the stream delivering this sample,...
Definition VideoDevice.h:1511
static int unwrapTimestamps(uint64_t &timestampA, uint64_t &timestampB)
Unwraps two timestamps while both are wrapped around 2^32.
Video Probe and Commit Controls.
Definition VideoDevice.h:586
static bool executeVideoControlProbe(libusb_device_handle *usbDeviceHandle, const uint8_t interfaceIndex, VideoControl &videoControl, const size_t videoControlSize, const uint8_t bRequest=RC_GET_CUR)
Executes a video probe control request.
std::string toString() const
Returns a string with the content of this object.
static bool proposeVideoControlProbe(libusb_device_handle *usbDeviceHandle, const uint8_t interfaceIndex, const VideoControl &videoControl, const size_t videoControlSize)
Proposes a video control to the device, the first step of the UVC stream negotiation.
static bool executeVideoControlCommit(libusb_device_handle *usbDeviceHandle, const uint8_t interfaceIndex, const VideoControl &videoControl, const size_t videoControlSize, const uint8_t bRequest=RC_SET_CUR)
Executes a video commit control request.
This class combines the video control interface functionality.
Definition VideoDevice.h:245
std::vector< VCSelectorUnitDescriptor > vcSelectorUnitDescriptors_
The selector unit descriptors.
Definition VideoDevice.h:279
VideoControlInterface(const libusb_interface_descriptor &interfaceDescriptor, libusb_device_handle *usbDeviceHandle)
Creates a new video control interface based on a given interface descriptor.
bool isValid() const
Returns whether this interface object is valid.
Definition VideoDevice.h:1531
std::vector< VCProcessingUnitDescriptor > vcProcessingUnitDescriptors_
The processing unit descriptors.
Definition VideoDevice.h:282
std::vector< VCExtensionUnitDescriptor > vcExtensionUnitDescriptors_
The extension unit descriptors.
Definition VideoDevice.h:285
VCHeaderDescriptor vcHeaderDescriptor_
The descriptor of the header interface.
Definition VideoDevice.h:273
std::vector< VCInputTerminalDescriptor > vcInputTerminalDescriptors_
The input terminal descriptors.
Definition VideoDevice.h:276
VideoControlInterface()=default
Default constructor creating an invalid interface.
This class implements a frame-based video stream.
Definition VideoDevice.h:347
VSFrameBasedVideoFormatDescriptor vsFrameBasedVideoFormatDescriptor_
The format descriptor of the frame-based stream.
Definition VideoDevice.h:351
std::vector< VSFrameBasedFrameDescriptor > vsFrameBasedFrameDescriptors_
The frame descriptors of the frame-based stream.
Definition VideoDevice.h:354
This class implements a Mjpeg video stream.
Definition VideoDevice.h:361
std::vector< VSMJPEGVideoFrameDescriptor > vsMJPEGVideoFrameDescriptors_
The frame descriptors of the Mjpeg stream.
Definition VideoDevice.h:368
VSMJPEGVideoFormatDescriptor vsMJPEGVideoFormatDescriptor_
The format descriptor of the Mjpeg stream.
Definition VideoDevice.h:365
This class implements an uncompressed video stream.
Definition VideoDevice.h:333
VSUncompressedVideoFormatDescriptor vsUncompressedVideoFormatDescriptor_
The format descriptor of the uncompressed stream.
Definition VideoDevice.h:337
std::vector< VSUncompressedVideoFrameDescriptor > vsUncompressedVideoFrameDescriptors_
The frame descriptors of the uncompressed stream.
Definition VideoDevice.h:340
This class implements the base class for all video streams.
Definition VideoDevice.h:322
VSColorMatchingDescriptor vsColorMatchingDescriptor_
The color matching descriptor of the stream.
Definition VideoDevice.h:326
This class combines the video streaming interface functionality.
Definition VideoDevice.h:301
static float determineResolutionFactor(const T &frameDescriptor, const unsigned int preferredWidth, const unsigned int preferredHeight, const unsigned int defaultPixels=1280u *720u)
Returns a factor describing how well the resolution of a descriptor matches a preferred image resolut...
std::vector< UncompressedVideoStream > UncompressedVideoStreams
Definition of a vector holding UncompressedVideoStream objects.
Definition VideoDevice.h:374
std::vector< MJPEGVideoStream > MJPEGVideoStreams
Definition of a vector holding MJPEGVideoStream objects.
Definition VideoDevice.h:384
VSInputHeaderDescriptor vsInputHeaderDescriptor_
The descriptor of the input header interface.
Definition VideoDevice.h:465
const UncompressedVideoStreams & uncompressedVideoStreams() const
Returns the available uncompressed video streams.
Definition VideoDevice.h:1536
const FrameBasedVideoStreams & frameBasedVideoStreams() const
Returns the available frame-based video streams.
Definition VideoDevice.h:1543
bool parseAdditionalInterface(const libusb_interface_descriptor &interfaceDescriptor, libusb_device_handle *usbDeviceHandle)
Parses an additional interface and adds it to this streaming interface object.
std::map< float, PriorityTriple > PriorityMap
Definition of an ordered map mapping priorities to triples combining formats, frames,...
Definition VideoDevice.h:314
MJPEGVideoStreams mjpegVideoStreams_
The Mjpeg-based video streams.
Definition VideoDevice.h:474
FrameBasedVideoStreams frameBasedVideoStreams_
The frame-based video streams.
Definition VideoDevice.h:471
VideoStreamingInterface()=default
Creates an invalid interface object.
PriorityMap findBestMatchingStream(const unsigned int preferredWidth, const unsigned int preferredHeight, const double preferredFrameRate, const DeviceStreamType deviceStreamType=DST_INVALID, const FrameType::PixelFormat pixelFormat=FrameType::FORMAT_UNDEFINED, VSFrameBasedVideoFormatDescriptor::EncodingFormat encodingFormat=VSFrameBasedVideoFormatDescriptor::EF_INVALID)
Returns a priority map with best matching stream configurations.
std::vector< FrameBasedVideoStream > FrameBasedVideoStreams
Definition of a vector holding FrameBasedVideoStream objects.
Definition VideoDevice.h:379
UncompressedVideoStreams uncompressedVideoStreams_
The uncompressed video streams.
Definition VideoDevice.h:468
bool isValid() const
Returns whether this interface object is valid.
Definition VideoDevice.h:1557
static float determineFrameRateFactor(const T &frameDescriptor, const double preferredFrameRate, uint32_t &frameInterval, const double defaultFrameRate)
Returns a factor describing how well one of the frame rates of a descriptor matches a preferred frame...
const MJPEGVideoStreams & mjpegVideoStreams() const
Returns the available Mjpeg video streams.
Definition VideoDevice.h:1550
This class implements a USB video device.
Definition VideoDevice.h:47
VideoStreamingInterface videoStreamingInterface_
The video streaming interface of this device.
Definition VideoDevice.h:1368
std::vector< Memory > streamingTransferMemories_
The memory for the individual streaming transfer objects.
Definition VideoDevice.h:1404
VideoControlInterface videoControlInterface_
The video control interface of this device.
Definition VideoDevice.h:1365
void releaseStartedStream()
Releases everything start() has created before it failed.
static std::string translateDeviceStreamType(const DeviceStreamType deviceStreamType)
Translates a device stream type to a string.
DeviceStreamType
Definition of individual USB UVC device stream types.
Definition VideoDevice.h:59
@ DST_UNCOMPRESSED
A stream composed of uncompressed video frames.
Definition VideoDevice.h:63
@ DST_MJPEG
A stream based on MJpeg.
Definition VideoDevice.h:65
VideoInterfaceSubclass
Definition of USB UVC Video Interface Subclass Codes.
Definition VideoDevice.h:492
Lock transferLock_
The lock for the stream and interrupt transfers, declared before everything it guards.
Definition VideoDevice.h:1395
ScopedSubscription claimedVideoStreamInterfaceSubscription_
The subscription for the claimed video stream interface.
Definition VideoDevice.h:1434
~VideoDevice() override
Destructs this video device and releases all associated resources.
VideoDevice & operator=(VideoDevice &&)=delete
Disabled move operator.
bool autoFocus(bool &value)
Returns whether auto focus is activated or deactivated.
void libusbStreamCallback(libusb_transfer &usbTransfer)
Libusb stream transfer callback function.
bool parseInterfaces()
Parses all interfaces of this device.
VideoDevice(Device &&device)
Creates a new video device based on a valid device.
VideoDevice(VideoDevice &&)=delete
Disabled move constructor.
bool setAutoExposureMode(const uint8_t value)
Sets the auto exposure mode.
bool isStarted_
True, if the video device has an active stream which has been started.
Definition VideoDevice.h:1407
ScopedSubscription claimedVideoControlInterfaceSubscription_
The subscription for the claimed video control interface.
Definition VideoDevice.h:1431
bool absoluteExposure(double *minValue, double *currentValue, double *maxValue)
Returns the absolute exposure duration of this device.
bool stop()
Stops the video device.
bool setAutoFocus(const bool value)
Activate or deactivate the auto focus of this device.
BufferPointers reusableBufferPointers_
Reusable buffer pointers to extract buffers from USB transfers.
Definition VideoDevice.h:1425
bool supportedAutoExposureModes(uint8_t &value) const
Returns the supported auto exposure modes.
Lock samplesLock_
The lock for the samples, declared before everything it guards.
Definition VideoDevice.h:1413
VideoDevice(const VideoDevice &)=delete
Disabled copy constructor.
DeviceStreamType extractStreamProperties(const uint8_t descriptorFormatIndex, const uint8_t descriptorFrameIndex, unsigned int &width, unsigned int &height, FrameType::PixelFormat &pixelFormat, VSFrameBasedVideoFormatDescriptor::EncodingFormat &encodingFormat) const
Extracts the relevant properties for a specific stream this device supports.
bool parseVideoInterface(const libusb_interface_descriptor &interfaceDescriptor)
Parses a video interface of this device.
static void LIBUSB_CALL libStatusCallback(libusb_transfer *usbTransfer)
Static libusb status transfer callback function.
void processPayload(const BufferPointers &bufferPointers)
Processes the payload which has been received from the device via a USB transfer.
bool setAbsoluteExposure(const double value)
Sets the absolute exposure duration of this device.
bool isStarted() const
Returns whether this video device has an active stream.
Definition VideoDevice.h:1567
static void LIBUSB_CALL libusbStreamCallback(libusb_transfer *usbTransfer)
Static libusb stream transfer callback function.
ScopedSubscription detachedKernelDriverSubscription_
The subscription for the detached kernel driver (if necessary/possible).
Definition VideoDevice.h:1428
SharedSample activeSample_
The currently active sample which is receiving sample data from the device (but not yet filled).
Definition VideoDevice.h:1416
bool libStatusCallback(libusb_transfer &usbTransfer)
Libusb status transfer callback function.
const VideoStreamingInterface & videoStreamingInterface() const
Returns the video streaming interface functionality of this device.
Definition VideoDevice.h:1562
bool setAbsoluteFocus(const float value)
Sets the absolute focus of this device.
bool absoluteFocus(float *minValue, float *currentValue, float *maxValue)
Returns the device's absolute focus.
bool isValid() const
Returns whether this video device is valid and ready to be used.
Definition VideoDevice.h:1574
bool start(const unsigned int preferredWidth=0u, const unsigned int preferredHeight=0u, const double preferredFrameRate=0.0, const DeviceStreamType preferredDeviceStreamType=DST_INVALID, const FrameType::PixelFormat preferredPixelFormat=FrameType::FORMAT_UNDEFINED, const VSFrameBasedVideoFormatDescriptor::EncodingFormat preferredEncodingFormat=VSFrameBasedVideoFormatDescriptor::EF_INVALID)
Starts the video device.
void giveSampleBack(SharedSample &&sample)
Gives a sample back to this device so that it can be reused by the device.
ControlSelectors
Definition VideoDevice.h:504
bool initializeControlInterfaceInitialized_
True, if the control interface has been initialized.
Definition VideoDevice.h:1371
std::queue< SharedSample > SampleQueue
Definition of a queue holding samples.
Definition VideoDevice.h:236
VideoDevice()=default
Default constructor creating an invalid video device.
bool autoExposureMode(uint8_t &value) const
Returns the current auto exposure mode.
SampleQueue sampleQueue_
The queue with all processed samples waiting to be grabbed by an external entity.
Definition VideoDevice.h:1419
Samples reusableSamples_
The reusable samples which waiting to be filled.
Definition VideoDevice.h:1422
TransferIndexMap transferIndexMap_
The map mapping transfer pointers to indices.
Definition VideoDevice.h:1401
ScopedTransfers streamingTransfers_
The streaming transfer objects.
Definition VideoDevice.h:1398
ScopedTransfer interruptTransfer_
The transfer object for interrupts.
Definition VideoDevice.h:1389
bool initializeControlInterface()
Initializes the control interface.
SharedSample nextSample(size_t *pendingSamples=nullptr)
Returns the next sample from this device.
std::vector< SharedSample > Samples
Definition of a vector holding samples.
Definition VideoDevice.h:231
std::shared_ptr< Sample > SharedSample
Definition of a shared pointer holding a Sample.
Definition VideoDevice.h:226
VideoDevice & operator=(const VideoDevice &)=delete
Disabled copy operator.
This class implements a timestamp.
Definition Timestamp.h:64
This class implements a triple object able to hold three individual elements.
Definition Triple.h:28
std::vector< ScopedTransfer > ScopedTransfers
Definition of a vector holding scoped libusb transfer objects.
Definition system/usb/USB.h:68
std::shared_ptr< VideoDevice > SharedVideoDevice
Definition of a shared pointer holding a VideoDevice.
Definition VideoDevice.h:39
std::unordered_map< libusb_transfer *, size_t > TransferIndexMap
Definition of an unordered map mapping libusb transfer points to indices.
Definition system/usb/USB.h:73
The namespace covering the entire Ocean framework.
Definition Accessor.h:15