Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qvideoframe.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3
4#include "qvideoframe.h"
5
6#include <QtCore/qdebug.h>
7#include <QtCore/qsize.h>
8#include <QtCore/qvariant.h>
9
10#include <QtGui/qimage.h>
11#include <QtGui/qtextlayout.h>
12#include <QtGui/qpainter.h>
13
14#include <QtMultimedia/private/qimagevideobuffer_p.h>
15#include <QtMultimedia/private/qmemoryvideobuffer_p.h>
16#include <QtMultimedia/private/qmultimediautils_p.h>
17#include <QtMultimedia/private/qvideoframe_p.h>
18#include <QtMultimedia/private/qvideoframeconverter_p.h>
19#include <QtMultimedia/private/qvideotexturehelper_p.h>
20
21#include <rhi/qrhi.h>
22
24
25QT_DEFINE_QESDP_SPECIALIZATION_DTOR(QVideoFramePrivate);
26
27/*!
28 \class QVideoFrame
29 \brief The QVideoFrame class represents a frame of video data.
30 \inmodule QtMultimedia
31
32 \ingroup multimedia
33 \ingroup multimedia_video
34
35 A QVideoFrame encapsulates the pixel data of a video frame, and information about the frame.
36
37 Video frames can come from several places - decoded \l {QMediaPlayer}{media}, a
38 \l {QCamera}{camera}, or generated programmatically. The way pixels are described in these
39 frames can vary greatly, and some pixel formats offer greater compression opportunities at
40 the expense of ease of use.
41
42 A video frame can also have timestamp information associated with it. These timestamps can be
43 used to determine when to start and stop displaying the frame.
44
45 \section1 Explicit Sharing
46
47 QVideoFrame objects can consume a significant amount of memory or system resources and
48 should not be held for longer than required by the application. QVideoFrame is explicitly
49 shared: copy construction and copy assignment are shallow, so a copy refers to the same
50 underlying frame, and any change made through one instance also applies to all of its copies.
51
52 copyToCpuMemory() returns a deep copy that is not shared with the original and holds its data
53 in CPU memory. Use it to keep a frame that is backed by system resources for longer, for
54 example to reduce memory pressure, or to modify a frame without affecting its other shared
55 copies. The result is invalid if the copy fails; check isValid().
56
57 \section1 Mapping Video Frames to Memory
58
59 The pixel contents of a video frame can be mapped to memory using the map() function. After
60 a successful call to map(), the video data can be accessed through various functions. Some of
61 the YUV pixel formats provide the data in several planes. The planeCount() method will return
62 the amount of planes that being used.
63
64 While mapped, the video data of each plane can accessed using the bits() function, which
65 returns a pointer to a buffer. The size of this buffer is given by the mappedBytes() function,
66 and the size of each line is given by bytesPerLine(). The return value of the handle()
67 function may also be used to access frame data using the internal buffer's native APIs
68 (for example - an OpenGL texture handle).
69
70 \note A mapping should only be held for a short time and be released as
71 early as possible with unmap().
72
73 \sa QAbstractVideoBuffer, QVideoFrameFormat, QVideoFrame::MapMode, copyToCpuMemory()
74*/
75
76#if QT_DEPRECATED_SINCE(6, 13)
77/*!
78 \enum QVideoFrame::HandleType
79 \deprecated [6.13] QVideoFrame::HandleType is deprecated and will be removed in a future
80 Qt version.
81
82 Identifies the type of a video buffers handle.
83
84 \value NoHandle
85 The buffer has no handle, its data can only be accessed by mapping the buffer.
86 \value RhiTextureHandle
87 The handle of the buffer is defined by The Qt Rendering Hardware Interface
88 (RHI). RHI is Qt's internal graphics abstraction for 3D APIs, such as
89 OpenGL, Vulkan, Metal, and Direct 3D.
90
91 \sa handleType()
92*/
93#endif
94
95
96/*!
97 Constructs a null video frame.
98*/
99QVideoFrame::QVideoFrame()
100{
101}
102
103#if QT_DEPRECATED_SINCE(6, 8)
104
105/*!
106 \internal
107 Constructs a video frame from a \a buffer with the given pixel \a format and \a size in pixels.
108
109 \note This doesn't increment the reference count of the video buffer.
110*/
111QVideoFrame::QVideoFrame(QAbstractVideoBuffer *buffer, const QVideoFrameFormat &format)
112 : d(new QVideoFramePrivate(format, std::unique_ptr<QAbstractVideoBuffer>(buffer)))
113{
114}
115
116/*!
117 \internal
118*/
119QAbstractVideoBuffer *QVideoFrame::videoBuffer() const
120{
121 return d ? d->videoBuffer.get() : nullptr;
122}
123
124#endif
125
126/*!
127 Constructs a video frame of the given pixel \a format.
128
129*/
130QVideoFrame::QVideoFrame(const QVideoFrameFormat &format)
131 : d(new QVideoFramePrivate(format))
132{
133 auto *textureDescription = QVideoTextureHelper::textureDescription(format.pixelFormat());
134 qsizetype bytes = textureDescription->bytesForSize(format.frameSize());
135 if (bytes > 0) {
136 QByteArray data;
137 data.resize(bytes);
138
139 // Check the memory was successfully allocated.
140 if (!data.isEmpty())
141 d->videoBuffer = std::make_unique<QMemoryVideoBuffer>(
142 data, textureDescription->strideForWidth(format.frameWidth()));
143 }
144}
145
146/*!
147 Constructs a QVideoFrame from a QImage.
148 \since 6.8
149
150 If the QImage::Format matches one of the formats in
151 QVideoFrameFormat::PixelFormat, the QVideoFrame will hold an instance of
152 the \a image and use that format without any pixel format conversion.
153 In this case, pixel data will be copied only if you call \l{QVideoFrame::map}
154 with \c WriteOnly flag while keeping the original image.
155
156 Otherwise, if the QImage::Format matches none of video formats,
157 the image is first converted to a supported (A)RGB format using
158 QImage::convertedTo() with the Qt::AutoColor flag.
159 This may incur a performance penalty.
160
161 If QImage::isNull() evaluates to true for the input QImage, the
162 QVideoFrame will be invalid and QVideoFrameFormat::isValid() will
163 return false.
164
165 \sa QVideoFrameFormat::pixelFormatFromImageFormat()
166 \sa QImage::convertedTo()
167 \sa QImage::isNull()
168*/
169QVideoFrame::QVideoFrame(const QImage &image)
170{
171 auto buffer = std::make_unique<QImageVideoBuffer>(image);
172
173 // If the QImage::Format is not convertible to QVideoFrameFormat,
174 // QImageVideoBuffer automatically converts image to a compatible
175 // (A)RGB format.
176 const QImage &bufferImage = buffer->underlyingImage();
177
178 if (bufferImage.isNull())
179 return;
180
181 // `bufferImage` is now supported by QVideoFrameFormat::pixelFormatFromImageFormat()
182 QVideoFrameFormat format = {
183 bufferImage.size(), QVideoFrameFormat::pixelFormatFromImageFormat(bufferImage.format())
184 };
185
186 Q_ASSERT(format.isValid());
187
188 d = new QVideoFramePrivate{ std::move(format), std::move(buffer) };
189}
190
191/*!
192 Constructs a QVideoFrame from a \l QAbstractVideoBuffer.
193
194 \since 6.8
195
196 The specified \a videoBuffer refers to an instance a reimplemented
197 \l QAbstractVideoBuffer. The instance is expected to contain a preallocated custom
198 video buffer and must implement \l QAbstractVideoBuffer::format,
199 \l QAbstractVideoBuffer::map, and \l QAbstractVideoBuffer::unmap for GPU content.
200
201 If \a videoBuffer is null or gets an invalid \l QVideoFrameFormat,
202 the constructors creates an invalid video frame.
203
204 The created frame will hold ownership of the specified video buffer for its lifetime.
205 Considering that QVideoFrame is implemented via a shared private object,
206 the specified video buffer will be destroyed upon destruction of the last copy
207 of the created video frame.
208
209 Note, if a video frame has been passed to \l QMediaRecorder or a rendering pipeline,
210 the lifetime of the frame is undefined, and the media recorder can destroy it
211 in a different thread.
212
213 QVideoFrame will contain own instance of QVideoFrameFormat.
214 Upon invoking \l setStreamFrameRate, \l setMirrored, or \l setRotation,
215 the inner format can be modified, and \l surfaceFormat will return
216 a detached instance.
217
218 \sa QAbstractVideoBuffer, QVideoFrameFormat
219*/
220QVideoFrame::QVideoFrame(std::unique_ptr<QAbstractVideoBuffer> videoBuffer)
221{
222 if (!videoBuffer)
223 return;
224
225 QVideoFrameFormat format = videoBuffer->format();
226 if (!format.isValid())
227 return;
228
229 Q_ASSERT(!dynamic_cast<QHwVideoBuffer *>(videoBuffer.get())
230 && "QHwVideoBuffer is not supported in this constructor. Use "
231 "QVideoFramePrivate::createFrame instead.");
232
233 d = new QVideoFramePrivate{ std::move(format), std::move(videoBuffer) };
234}
235
236/*!
237 Constructs a shallow copy of \a other. The two instances refer to the same frame, see
238 \l {QVideoFrame#Explicit Sharing}{explicit sharing}.
239
240 \sa copyToCpuMemory()
241*/
242QVideoFrame::QVideoFrame(const QVideoFrame &other) = default;
243
244/*!
245 \fn QVideoFrame::QVideoFrame(QVideoFrame &&other)
246
247 Constructs a QVideoFrame by moving from \a other.
248*/
249
250/*!
251 \fn void QVideoFrame::swap(QVideoFrame &other) noexcept
252
253 Swaps the current video frame with \a other.
254*/
255
256/*!
257 \fn QVideoFrame &QVideoFrame::operator=(QVideoFrame &&other)
258
259 Moves \a other into this QVideoFrame.
260*/
261
262/*!
263 Assigns a shallow copy of \a other to this video frame. Both instances refer to the same
264 frame, see \l {QVideoFrame#Explicit Sharing}{explicit sharing}.
265
266 \sa copyToCpuMemory()
267*/
268QVideoFrame &QVideoFrame::operator =(const QVideoFrame &other) = default;
269
270/*!
271 \return \c true if this QVideoFrame and \a other reflect the same frame.
272 */
273bool QVideoFrame::operator==(const QVideoFrame &other) const
274{
275 // Due to explicit sharing we just compare the QSharedData which in turn compares the pointers.
276 return d == other.d;
277}
278
279/*!
280 \return \c true if this QVideoFrame and \a other do not reflect the same frame.
281 */
282bool QVideoFrame::operator!=(const QVideoFrame &other) const
283{
284 return d != other.d;
285}
286
287/*!
288 Destroys a video frame.
289*/
290QVideoFrame::~QVideoFrame() = default;
291
292/*!
293 Identifies whether a video frame is valid.
294
295 An invalid frame has no video buffer associated with it.
296
297 Returns true if the frame is valid, and false if it is not.
298*/
299bool QVideoFrame::isValid() const
300{
301 return d && d->videoBuffer && d->format.pixelFormat() != QVideoFrameFormat::Format_Invalid;
302}
303
304/*!
305 Returns the pixel format of this video frame.
306*/
307QVideoFrameFormat::PixelFormat QVideoFrame::pixelFormat() const
308{
309 return d ? d->format.pixelFormat() : QVideoFrameFormat::Format_Invalid;
310}
311
312/*!
313 Returns the surface format of this video frame.
314*/
315QVideoFrameFormat QVideoFrame::surfaceFormat() const
316{
317 return d ? d->format : QVideoFrameFormat{};
318}
319
320#if QT_DEPRECATED_SINCE(6, 13)
321/*!
322 Returns the type of a video frame's handle.
323 \deprecated [6.13] QVideoFrame::handleType() is deprecated and will be removed in a future
324 Qt version.
325
326 Always returns NoHandle.
327*/
328QT_WARNING_PUSH
329QT_WARNING_DISABLE_DEPRECATED
330QVideoFrame::HandleType QVideoFrame::handleType() const
331{
332 return QVideoFrame::NoHandle;
333}
334QT_WARNING_POP
335#endif
336
337/*!
338 Returns the dimensions of a video frame.
339*/
340QSize QVideoFrame::size() const
341{
342 return d ? d->format.frameSize() : QSize();
343}
344
345/*!
346 Returns the width of a video frame.
347*/
348int QVideoFrame::width() const
349{
350 return size().width();
351}
352
353/*!
354 Returns the height of a video frame.
355*/
356int QVideoFrame::height() const
357{
358 return size().height();
359}
360
361/*!
362 Identifies if a video frame's contents are currently mapped to system memory.
363
364 This is a convenience function which checks that the \l {QVideoFrame::MapMode}{MapMode}
365 of the frame is not equal to QVideoFrame::NotMapped.
366
367 Returns true if the contents of the video frame are mapped to system memory, and false
368 otherwise.
369
370 \sa mapMode(), QVideoFrame::MapMode
371*/
372
373bool QVideoFrame::isMapped() const
374{
375 return d && d->mapMode != QVideoFrame::NotMapped;
376}
377
378/*!
379 Identifies if the mapped contents of a video frame will be persisted when the frame is unmapped.
380
381 This is a convenience function which checks if the \l {QVideoFrame::MapMode}{MapMode}
382 contains the QVideoFrame::WriteOnly flag.
383
384 Returns true if the video frame will be updated when unmapped, and false otherwise.
385
386 \note The result of altering the data of a frame that is mapped in read-only mode is undefined.
387 Depending on the buffer implementation the changes may be persisted, or worse alter a shared
388 buffer.
389
390 \sa mapMode(), QVideoFrame::MapMode
391*/
392bool QVideoFrame::isWritable() const
393{
394 return d && (d->mapMode & QVideoFrame::WriteOnly);
395}
396
397/*!
398 Identifies if the mapped contents of a video frame were read from the frame when it was mapped.
399
400 This is a convenience function which checks if the \l {QVideoFrame::MapMode}{MapMode}
401 contains the QVideoFrame::WriteOnly flag.
402
403 Returns true if the contents of the mapped memory were read from the video frame, and false
404 otherwise.
405
406 \sa mapMode(), QVideoFrame::MapMode
407*/
408bool QVideoFrame::isReadable() const
409{
410 return d && (d->mapMode & QVideoFrame::ReadOnly);
411}
412
413/*!
414 \enum QVideoFrame::MapMode
415
416 Enumerates how a video buffer's data is mapped to system memory.
417
418 \value NotMapped
419 The video buffer is not mapped to memory.
420 \value ReadOnly
421 The mapped memory is populated with data from the video buffer when mapped,
422 but the content of the mapped memory may be discarded when unmapped.
423 \value WriteOnly
424 The mapped memory is uninitialized when mapped, but the possibly modified
425 content will be used to populate the video buffer when unmapped.
426 \value ReadWrite
427 The mapped memory is populated with data from the video
428 buffer, and the video buffer is repopulated with the content of the mapped
429 memory when it is unmapped.
430
431 \sa mapMode(), map()
432*/
433
434/*!
435 Returns the mode a video frame was mapped to system memory in.
436
437 \sa map(), QVideoFrame::MapMode
438*/
439QVideoFrame::MapMode QVideoFrame::mapMode() const
440{
441 return d ? d->mapMode : QVideoFrame::NotMapped;
442}
443
444/*!
445 Maps the contents of a video frame to system (CPU addressable) memory.
446
447 In some cases the video frame data might be stored in video memory or otherwise inaccessible
448 memory, so it is necessary to map a frame before accessing the pixel data. This may involve
449 copying the contents around, so avoid mapping and unmapping unless required.
450
451 The map \a mode indicates whether the contents of the mapped memory should be read from and/or
452 written to the frame. If the map mode includes the \c QVideoFrame::ReadOnly flag the
453 mapped memory will be populated with the content of the video frame when initially mapped. If the map
454 mode includes the \c QVideoFrame::WriteOnly flag the content of the possibly modified
455 mapped memory will be written back to the frame when unmapped.
456
457 While mapped the contents of a video frame can be accessed directly through the pointer returned
458 by the bits() function.
459
460 When access to the data is no longer needed, be sure to call the unmap() function to release the
461 mapped memory and possibly update the video frame contents. A mapping should only be held for
462 a short time and be released as early as possible.
463
464 If the video frame has been mapped in read only mode, it is permissible to map it
465 multiple times in read only mode (and unmap it a corresponding number of times). In all
466 other cases it is necessary to unmap the frame first before mapping a second time.
467
468 \note Writing to memory that is mapped as read-only is undefined, and may result in changes
469 to shared data or crashes.
470
471 Returns true if the frame was mapped to memory in the given \a mode and false otherwise.
472
473 \sa unmap(), mapMode(), bits()
474*/
475bool QVideoFrame::map(QVideoFrame::MapMode mode)
476{
477 if (!d || !d->videoBuffer || d->format.frameSize().isEmpty())
478 return false;
479
480 QMutexLocker lock(&d->mapMutex);
481 if (mode == QVideoFrame::NotMapped)
482 return false;
483
484 if (d->mappedCount > 0) {
485 //it's allowed to map the video frame multiple times in read only mode
486 if (d->mapMode == QVideoFrame::ReadOnly && mode == QVideoFrame::ReadOnly) {
487 d->mappedCount++;
488 return true;
489 }
490
491 return false;
492 }
493
494 Q_ASSERT(d->mapData.data[0] == nullptr);
495 Q_ASSERT(d->mapData.bytesPerLine[0] == 0);
496 Q_ASSERT(d->mapData.planeCount == 0);
497 Q_ASSERT(d->mapData.dataSize[0] == 0);
498
499 d->mapData = d->videoBuffer->map(mode);
500 if (d->mapData.planeCount == 0)
501 return false;
502
503 d->mapMode = mode;
504
505 if (d->mapData.planeCount == 1) {
506 auto pixelFmt = d->format.pixelFormat();
507 // If the plane count is 1 derive the additional planes for planar formats.
508 switch (pixelFmt) {
509 case QVideoFrameFormat::Format_Invalid:
510 case QVideoFrameFormat::Format_ARGB8888:
511 case QVideoFrameFormat::Format_ARGB8888_Premultiplied:
512 case QVideoFrameFormat::Format_XRGB8888:
513 case QVideoFrameFormat::Format_BGRA8888:
514 case QVideoFrameFormat::Format_BGRA8888_Premultiplied:
515 case QVideoFrameFormat::Format_BGRX8888:
516 case QVideoFrameFormat::Format_ABGR8888:
517 case QVideoFrameFormat::Format_XBGR8888:
518 case QVideoFrameFormat::Format_RGBA8888:
519 case QVideoFrameFormat::Format_RGBX8888:
520 case QVideoFrameFormat::Format_AYUV:
521 case QVideoFrameFormat::Format_AYUV_Premultiplied:
522 case QVideoFrameFormat::Format_UYVY:
523 case QVideoFrameFormat::Format_YUYV:
524 case QVideoFrameFormat::Format_Y8:
525 case QVideoFrameFormat::Format_Y16:
526 case QVideoFrameFormat::Format_Jpeg:
527 case QVideoFrameFormat::Format_SamplerExternalOES:
528 case QVideoFrameFormat::Format_SamplerRect:
529 // Single plane or opaque format.
530 break;
531 case QVideoFrameFormat::Format_YUV420P:
532 case QVideoFrameFormat::Format_YUV420P10:
533 case QVideoFrameFormat::Format_YUV422P:
534 case QVideoFrameFormat::Format_YV12: {
535 // The UV stride is usually half the Y stride and is 32-bit aligned.
536 // However it's not always the case, at least on Windows where the
537 // UV planes are sometimes not aligned.
538 // We calculate the stride using the UV byte count to always
539 // have a correct stride.
540 const int height = this->height();
541 const int yStride = d->mapData.bytesPerLine[0];
542 const int uvHeight = pixelFmt == QVideoFrameFormat::Format_YUV422P ? height : height / 2;
543 Q_ASSERT(uvHeight > 0);
544 const int uvSize = d->mapData.dataSize[0] - yStride * height;
545 const int uvStride = uvSize / 2 / uvHeight;
546
547 // Three planes, the second and third vertically (and horizontally for other than Format_YUV422P formats) subsampled.
548 d->mapData.planeCount = 3;
549 d->mapData.bytesPerLine[2] = d->mapData.bytesPerLine[1] = uvStride;
550 d->mapData.dataSize[0] = yStride * height;
551 d->mapData.dataSize[2] = d->mapData.dataSize[1] = uvStride * uvHeight;
552 d->mapData.data[1] = d->mapData.data[0] + d->mapData.dataSize[0];
553 d->mapData.data[2] = d->mapData.data[1] + d->mapData.dataSize[1];
554 break;
555 }
556 case QVideoFrameFormat::Format_NV12:
557 case QVideoFrameFormat::Format_NV21:
558 case QVideoFrameFormat::Format_IMC2:
559 case QVideoFrameFormat::Format_IMC4:
560 case QVideoFrameFormat::Format_P010:
561 case QVideoFrameFormat::Format_P016: {
562 // Semi planar, Full resolution Y plane with interleaved subsampled U and V planes.
563 d->mapData.planeCount = 2;
564 d->mapData.bytesPerLine[1] = d->mapData.bytesPerLine[0];
565 int size = d->mapData.dataSize[0];
566 d->mapData.dataSize[0] = (d->mapData.bytesPerLine[0] * height());
567 d->mapData.dataSize[1] = size - d->mapData.dataSize[0];
568 d->mapData.data[1] = d->mapData.data[0] + d->mapData.dataSize[0];
569 break;
570 }
571 case QVideoFrameFormat::Format_IMC1:
572 case QVideoFrameFormat::Format_IMC3: {
573 // Three planes, the second and third vertically and horizontally subsumpled,
574 // but with lines padded to the width of the first plane.
575 d->mapData.planeCount = 3;
576 d->mapData.bytesPerLine[2] = d->mapData.bytesPerLine[1] = d->mapData.bytesPerLine[0];
577 d->mapData.dataSize[0] = (d->mapData.bytesPerLine[0] * height());
578 d->mapData.dataSize[1] = (d->mapData.bytesPerLine[0] * height() / 2);
579 d->mapData.dataSize[2] = (d->mapData.bytesPerLine[0] * height() / 2);
580 d->mapData.data[1] = d->mapData.data[0] + d->mapData.dataSize[0];
581 d->mapData.data[2] = d->mapData.data[1] + d->mapData.dataSize[1];
582 break;
583 }
584 }
585 }
586
587 d->mappedCount++;
588
589 // unlock mapMutex to avoid potential deadlock imageMutex <--> mapMutex
590 lock.unlock();
591
592 if ((mode & QVideoFrame::WriteOnly) != 0) {
593 QMutexLocker lock(&d->imageMutex);
594 d->image = {};
595 }
596
597 return true;
598}
599
600/*!
601 Releases the memory mapped by the map() function.
602
603 If the \l {QVideoFrame::MapMode}{MapMode} included the QVideoFrame::WriteOnly
604 flag this will persist the current content of the mapped memory to the video frame.
605
606 unmap() should not be called if map() function failed.
607
608 \sa map()
609*/
610void QVideoFrame::unmap()
611{
612 if (!d || !d->videoBuffer)
613 return;
614
615 QMutexLocker lock(&d->mapMutex);
616
617 if (d->mappedCount == 0) {
618 qWarning() << "QVideoFrame::unmap() was called more times then QVideoFrame::map()";
619 return;
620 }
621
622 d->mappedCount--;
623
624 if (d->mappedCount == 0) {
625 d->mapData = {};
626 d->mapMode = QVideoFrame::NotMapped;
627 d->videoBuffer->unmap();
628 }
629}
630
631/*!
632 Returns the number of bytes in a scan line of a \a plane.
633
634 This value is only valid while the frame data is \l {map()}{mapped}.
635
636 \sa bits(), map(), mappedBytes(), planeCount()
637 \since 5.4
638*/
639
640int QVideoFrame::bytesPerLine(int plane) const
641{
642 if (!d)
643 return 0;
644 return plane >= 0 && plane < d->mapData.planeCount ? d->mapData.bytesPerLine[plane] : 0;
645}
646
647/*!
648 Returns a pointer to the start of the frame data buffer for a \a plane.
649
650 This value is only valid while the frame data is \l {map()}{mapped}.
651
652 Changes made to data accessed via this pointer (when mapped with write access)
653 are only guaranteed to have been persisted when unmap() is called and when the
654 buffer has been mapped for writing.
655
656 \sa map(), mappedBytes(), bytesPerLine(), planeCount()
657 \since 5.4
658*/
659uchar *QVideoFrame::bits(int plane)
660{
661 if (!d)
662 return nullptr;
663 return plane >= 0 && plane < d->mapData.planeCount ? d->mapData.data[plane] : nullptr;
664}
665
666/*!
667 Returns a pointer to the start of the frame data buffer for a \a plane.
668
669 This value is only valid while the frame data is \l {map()}{mapped}.
670
671 If the buffer was not mapped with read access, the contents of this
672 buffer will initially be uninitialized.
673
674 \sa map(), mappedBytes(), bytesPerLine(), planeCount()
675 \since 5.4
676*/
677const uchar *QVideoFrame::bits(int plane) const
678{
679 if (!d)
680 return nullptr;
681 return plane >= 0 && plane < d->mapData.planeCount ? d->mapData.data[plane] : nullptr;
682}
683
684/*!
685 Returns the number of bytes occupied by plane \a plane of the mapped frame data.
686
687 This value is only valid while the frame data is \l {map()}{mapped}.
688
689 \sa map()
690*/
691int QVideoFrame::mappedBytes(int plane) const
692{
693 if (!d)
694 return 0;
695 return plane >= 0 && plane < d->mapData.planeCount ? d->mapData.dataSize[plane] : 0;
696}
697
698/*!
699 Returns the number of planes in the video frame.
700
701 \sa map()
702 \since 5.4
703*/
704
705int QVideoFrame::planeCount() const
706{
707 if (!d)
708 return 0;
709 return d->format.planeCount();
710}
711
712/*!
713 Returns the presentation time (in microseconds) when the frame should be displayed.
714
715 An invalid time is represented as -1.
716
717*/
718qint64 QVideoFrame::startTime() const
719{
720 if (!d)
721 return -1;
722 return d->startTime;
723}
724
725/*!
726 Sets the presentation \a time (in microseconds) when the frame should initially be displayed.
727
728 An invalid time is represented as -1.
729
730*/
731void QVideoFrame::setStartTime(qint64 time)
732{
733 if (!d)
734 return;
735 d->startTime = time;
736}
737
738/*!
739 Returns the presentation time (in microseconds) when a frame should stop being displayed.
740
741 An invalid time is represented as -1.
742
743*/
744qint64 QVideoFrame::endTime() const
745{
746 if (!d)
747 return -1;
748 return d->endTime;
749}
750
751/*!
752 Sets the presentation \a time (in microseconds) when a frame should stop being displayed.
753
754 An invalid time is represented as -1.
755
756*/
757void QVideoFrame::setEndTime(qint64 time)
758{
759 if (!d)
760 return;
761 d->endTime = time;
762}
763
764#if QT_DEPRECATED_SINCE(6, 7)
765/*!
766 \enum QVideoFrame::RotationAngle
767 \deprecated [6.7] Use QtVideo::Rotation instead.
768
769 The angle of the clockwise rotation that should be applied to a video
770 frame before displaying.
771
772 \value Rotation0 No rotation required, the frame has correct orientation
773 \value Rotation90 The frame should be rotated by 90 degrees
774 \value Rotation180 The frame should be rotated by 180 degrees
775 \value Rotation270 The frame should be rotated by 270 degrees
776*/
777
778/*!
779 \fn void QVideoFrame::setRotationAngle(RotationAngle)
780 \deprecated [6.7] Use \c QVideoFrame::setRotation instead.
781
782 Sets the \a angle the frame should be rotated clockwise before displaying.
783*/
784
785/*!
786 \fn QVideoFrame::RotationAngle QVideoFrame::rotationAngle() const
787 \deprecated [6.7] Use \c QVideoFrame::rotation instead.
788
789 Returns the angle the frame should be rotated clockwise before displaying.
790*/
791
792#endif
793
794
795/*!
796 Sets the \a angle the frame should be rotated clockwise before displaying.
797
798 Transformations of \c QVideoFrame, specifically rotation and mirroring,
799 are used only for displaying the video frame and are applied on top
800 of the surface transformation, which is determined by \l QVideoFrameFormat.
801 Rotation is applied before mirroring.
802
803 Default value is \c QtVideo::Rotation::None.
804*/
805void QVideoFrame::setRotation(QtVideo::Rotation angle)
806{
807 if (d)
808 d->presentationTransformation.rotation = angle;
809}
810
811/*!
812 Returns the angle the frame should be rotated clockwise before displaying.
813
814 Transformations of \c QVideoFrame, specifically rotation and mirroring,
815 are used only for displaying the video frame and are applied on top
816 of the surface transformation, which is determined by \l QVideoFrameFormat.
817 Rotation is applied before mirroring.
818 */
819QtVideo::Rotation QVideoFrame::rotation() const
820{
821 return d ? d->presentationTransformation.rotation : QtVideo::Rotation::None;
822}
823
824/*!
825 Sets whether the frame should be \a mirrored around its vertical axis before displaying.
826
827 Transformations of \c QVideoFrame, specifically rotation and mirroring,
828 are used only for displaying the video frame and are applied on top
829 of the surface transformation, which is determined by \l QVideoFrameFormat.
830 Mirroring is applied after rotation.
831
832 Mirroring is typically needed for video frames coming from a front camera of a mobile device.
833
834 Default value is \c false.
835*/
836void QVideoFrame::setMirrored(bool mirrored)
837{
838 if (d)
839 d->presentationTransformation.mirroredHorizontallyAfterRotation = mirrored;
840}
841
842/*!
843 Returns whether the frame should be mirrored around its vertical axis before displaying.
844
845 Transformations of \c QVideoFrame, specifically rotation and mirroring,
846 are used only for displaying the video frame and are applied on top
847 of the surface transformation, which is determined by \l QVideoFrameFormat.
848 Mirroring is applied after rotation.
849
850 Mirroring is typically needed for video frames coming from a front camera of a mobile device.
851*/
852bool QVideoFrame::mirrored() const
853{
854 return d && d->presentationTransformation.mirroredHorizontallyAfterRotation;
855}
856
857/*!
858 Sets the frame \a rate of a video stream in frames per second.
859*/
860void QVideoFrame::setStreamFrameRate(qreal rate)
861{
862 if (d)
863 d->format.setStreamFrameRate(rate);
864}
865
866/*!
867 Returns the frame rate of a video stream in frames per second.
868*/
869qreal QVideoFrame::streamFrameRate() const
870{
871 return d ? d->format.streamFrameRate() : 0.;
872}
873
874/*!
875 Converts current video frame to image.
876
877 The conversion is based on the current pixel data and
878 the \l {QVideoFrame::surfaceFormat}{surface format}.
879 Transformations of the frame don't impact the result
880 since they are applied for presentation only.
881
882 \since 5.15
883*/
884QImage QVideoFrame::toImage() const
885{
886 if (!isValid())
887 return {};
888
889 QMutexLocker lock(&d->imageMutex);
890
891 if (d->image.isNull())
892 d->image = qImageFromVideoFrame(*this, qNormalizedSurfaceTransformation(d->format));
893
894 return d->image;
895}
896
897/*!
898 Returns a deep copy of this video frame, with its pixel data held in CPU memory.
899
900 Unlike the copy constructor, the returned frame is not shared with this frame, see
901 \l {QVideoFrame#Explicit Sharing}{explicit sharing}.
902
903 The copy has the same size, pixel format, timing, subtitle text and rotation/mirroring as this
904 frame. Mapping the copy with \l map() does not involve the hardware that produced this frame.
905
906 Copying a frame that is backed by hardware memory reads the frame back to CPU memory,
907 which can be expensive.
908
909 \note The copy can fail if mapping the underlying QAbstractVideoBuffer fails. In that case, the
910 returned frame is invalid.
911
912 \since 6.13
913 \sa map(), toImage()
914*/
915QVideoFrame QVideoFrame::copyToCpuMemory() const
916{
917 return QVideoFramePrivate::copyToCpuMemory(*this);
918}
919
920/*!
921 Returns the subtitle text that should be rendered together with this video frame.
922*/
923QString QVideoFrame::subtitleText() const
924{
925 return d ? d->subtitleText : QString();
926}
927
928/*!
929 Sets the subtitle text that should be rendered together with this video frame to \a text.
930*/
931void QVideoFrame::setSubtitleText(const QString &text)
932{
933 if (!d)
934 return;
935 d->subtitleText = text;
936}
937
938/*!
939 Uses a QPainter, \a{painter}, to render this QVideoFrame to \a rect.
940 The PaintOptions \a options can be used to specify a background color and
941 how \a rect should be filled with the video.
942
943 \note that rendering will usually happen without hardware acceleration when
944 using this method.
945*/
946void QVideoFrame::paint(QPainter *painter, const QRectF &rect, const PaintOptions &options)
947{
948 if (!isValid()) {
949 painter->fillRect(rect, options.backgroundColor);
950 return;
951 }
952
953 QRectF targetRect = rect;
954 QSizeF size = qRotatedFramePresentationSize(*this);
955
956 size.scale(targetRect.size(), options.aspectRatioMode);
957
958 if (options.aspectRatioMode == Qt::KeepAspectRatio) {
959 targetRect = QRect(0, 0, size.width(), size.height());
960 targetRect.moveCenter(rect.center());
961 // we might not be drawing every pixel, fill the leftovers black
962 if (options.backgroundColor != Qt::transparent && rect != targetRect) {
963 if (targetRect.top() > rect.top()) {
964 QRectF top(rect.left(), rect.top(), rect.width(), targetRect.top() - rect.top());
965 painter->fillRect(top, Qt::black);
966 }
967 if (targetRect.left() > rect.left()) {
968 QRectF top(rect.left(), targetRect.top(), targetRect.left() - rect.left(), targetRect.height());
969 painter->fillRect(top, Qt::black);
970 }
971 if (targetRect.right() < rect.right()) {
972 QRectF top(targetRect.right(), targetRect.top(), rect.right() - targetRect.right(), targetRect.height());
973 painter->fillRect(top, Qt::black);
974 }
975 if (targetRect.bottom() < rect.bottom()) {
976 QRectF top(rect.left(), targetRect.bottom(), rect.width(), rect.bottom() - targetRect.bottom());
977 painter->fillRect(top, Qt::black);
978 }
979 }
980 }
981
982 if (map(QVideoFrame::ReadOnly)) {
983 const QTransform oldTransform = painter->transform();
984 QTransform transform = oldTransform;
985 transform.translate(targetRect.center().x() - size.width()/2,
986 targetRect.center().y() - size.height()/2);
987 painter->setTransform(transform);
988
989 const bool hasPresentationTransformation =
990 d->presentationTransformation != VideoTransformation{};
991
992 // Use cache for images without presentation transform
993 const QImage image = hasPresentationTransformation
994 ? qImageFromVideoFrame(*this, qNormalizedFrameTransformation(*this))
995 : toImage();
996
997 painter->drawImage({{}, size}, image, {{},image.size()});
998 painter->setTransform(oldTransform);
999
1000 unmap();
1001 } else if (isValid()) {
1002 // #### error handling
1003 } else {
1004 painter->fillRect(rect, Qt::black);
1005 }
1006
1007 if ((options.paintFlags & PaintOptions::DontDrawSubtitles) || d->subtitleText.isEmpty())
1008 return;
1009
1010 // draw subtitles
1011 QVideoTextureHelper::SubtitleLayout layout;
1012 layout.update(targetRect.size().toSize(), this->subtitleText());
1013 layout.draw(painter, targetRect.topLeft());
1014}
1015
1016#ifndef QT_NO_DEBUG_STREAM
1017static QString qFormatTimeStamps(qint64 start, qint64 end)
1018{
1019 // Early out for invalid.
1020 if (start < 0)
1021 return QLatin1String("[no timestamp]");
1022
1023 bool onlyOne = (start == end);
1024
1025 // [hh:]mm:ss.ms
1026 const int s_millis = start % 1000000;
1027 start /= 1000000;
1028 const int s_seconds = start % 60;
1029 start /= 60;
1030 const int s_minutes = start % 60;
1031 start /= 60;
1032
1033 if (onlyOne) {
1034 if (start > 0)
1035 return QStringLiteral("@%1:%2:%3.%4")
1036 .arg(start, 1, 10, QLatin1Char('0'))
1037 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1038 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1039 .arg(s_millis, 2, 10, QLatin1Char('0'));
1040 return QStringLiteral("@%1:%2.%3")
1041 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1042 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1043 .arg(s_millis, 2, 10, QLatin1Char('0'));
1044 }
1045
1046 if (end == -1) {
1047 // Similar to start-start, except it means keep displaying it?
1048 if (start > 0)
1049 return QStringLiteral("%1:%2:%3.%4 - forever")
1050 .arg(start, 1, 10, QLatin1Char('0'))
1051 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1052 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1053 .arg(s_millis, 2, 10, QLatin1Char('0'));
1054 return QStringLiteral("%1:%2.%3 - forever")
1055 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1056 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1057 .arg(s_millis, 2, 10, QLatin1Char('0'));
1058 }
1059
1060 const int e_millis = end % 1000000;
1061 end /= 1000000;
1062 const int e_seconds = end % 60;
1063 end /= 60;
1064 const int e_minutes = end % 60;
1065 end /= 60;
1066
1067 if (start > 0 || end > 0)
1068 return QStringLiteral("%1:%2:%3.%4 - %5:%6:%7.%8")
1069 .arg(start, 1, 10, QLatin1Char('0'))
1070 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1071 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1072 .arg(s_millis, 2, 10, QLatin1Char('0'))
1073 .arg(end, 1, 10, QLatin1Char('0'))
1074 .arg(e_minutes, 2, 10, QLatin1Char('0'))
1075 .arg(e_seconds, 2, 10, QLatin1Char('0'))
1076 .arg(e_millis, 2, 10, QLatin1Char('0'));
1077 return QStringLiteral("%1:%2.%3 - %4:%5.%6")
1078 .arg(s_minutes, 2, 10, QLatin1Char('0'))
1079 .arg(s_seconds, 2, 10, QLatin1Char('0'))
1080 .arg(s_millis, 2, 10, QLatin1Char('0'))
1081 .arg(e_minutes, 2, 10, QLatin1Char('0'))
1082 .arg(e_seconds, 2, 10, QLatin1Char('0'))
1083 .arg(e_millis, 2, 10, QLatin1Char('0'));
1084}
1085
1086# if QT_DEPRECATED_SINCE(6, 13)
1087QT_WARNING_PUSH
1088QT_WARNING_DISABLE_DEPRECATED
1089QDebug operator<<(QDebug dbg, QVideoFrame::HandleType type)
1090{
1091 QDebugStateSaver saver(dbg);
1092 dbg.nospace();
1093 switch (type) {
1094 case QVideoFrame::NoHandle:
1095 return dbg << "NoHandle";
1096 case QVideoFrame::RhiTextureHandle:
1097 return dbg << "RhiTextureHandle";
1098 }
1099 return dbg;
1100}
1101QT_WARNING_POP
1102# endif
1103
1104QDebug operator<<(QDebug dbg, const QVideoFrame& f)
1105{
1106 QDebugStateSaver saver(dbg);
1107 dbg.nospace();
1108 dbg << "QVideoFrame(" << f.size() << ", "
1109 << f.pixelFormat() << ", "
1110 << f.mapMode() << ", "
1111 << qFormatTimeStamps(f.startTime(), f.endTime()).toLatin1().constData();
1112 dbg << ')';
1113 return dbg;
1114}
1115#endif
1116
1117QVideoFrame QVideoFramePrivate::copyToCpuMemory(const QVideoFrame &source)
1118{
1119 QAbstractVideoBuffer *sourceBuffer = buffer(source);
1120 if (!sourceBuffer)
1121 return {};
1122
1123 auto copy = QMultiPlaneMemoryVideoBuffer::copyFrom(*sourceBuffer);
1124 if (!copy)
1125 return {};
1126
1127 QVideoFrame clone = createFrame(std::move(copy), source.surfaceFormat());
1128
1129 QVideoFramePrivate *cloneHandle = handle(clone);
1130 cloneHandle->startTime = source.startTime();
1131 cloneHandle->endTime = source.endTime();
1132 cloneHandle->subtitleText = source.subtitleText();
1133 cloneHandle->presentationTransformation = source.d->presentationTransformation;
1134 return clone;
1135}
1136
1137QT_END_NAMESPACE
Combined button and popup list for selecting options.
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
static QString qFormatTimeStamps(qint64 start, qint64 end)