QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
QtVideoRecorder.cc
Go to the documentation of this file.
1#include "QtVideoRecorder.h"
2
3#include <algorithm>
4#include <optional>
5#include <utility>
6
7#include <QtCore/QDateTime>
8#include <QtCore/QEventLoop>
9#include <QtCore/QFile>
10#include <QtCore/QFileInfo>
11#include <QtCore/QMetaEnum>
12#include <QtCore/QMimeType>
13#include <QtCore/QTimer>
14#include <QtCore/QUrl>
15#include <QtMultimedia/QMediaMetaData>
16
17#include "QGCLoggingCategory.h"
18
19QGC_LOGGING_CATEGORY(QtVideoRecorderLog, "Video.QtVideoRecorder")
20
21namespace {
22
23QString fileSuffix(const QMediaFormat& format)
24{
25 switch (format.fileFormat()) {
26 case QMediaFormat::Matroska:
27 return QStringLiteral("mkv");
28 case QMediaFormat::QuickTime:
29 return QStringLiteral("mov");
30 case QMediaFormat::MPEG4:
31 return QStringLiteral("mp4");
32 default:
33 return format.mimeType().preferredSuffix();
34 }
35}
36
38constexpr QMediaFormat::FileFormat kRecordingContainers[] = {QMediaFormat::MPEG4, QMediaFormat::Matroska,
39 QMediaFormat::QuickTime};
40
42constexpr QMediaFormat::VideoCodec kFallbackCodecs[] = {
43 QMediaFormat::VideoCodec::H264, QMediaFormat::VideoCodec::H265, QMediaFormat::VideoCodec::AV1,
44 QMediaFormat::VideoCodec::VP9, QMediaFormat::VideoCodec::MPEG4, QMediaFormat::VideoCodec::MPEG2,
45};
46
47std::optional<QMediaFormat> encodableFormat(QMediaFormat::FileFormat container, QMediaFormat::VideoCodec codec)
48{
49 QMediaFormat format(container);
50 format.setVideoCodec(codec);
51 return format.isSupported(QMediaFormat::Encode) ? std::optional(format) : std::nullopt;
52}
53
54void removeIfEmpty(const QString& file)
55{
56 const QFileInfo info(file);
57 if (info.exists() && (info.size() == 0)) {
58 (void) QFile::remove(file);
59 }
60}
61
62} // namespace
63
65 : QObject(parent)
66 , _recorder(new QMediaRecorder(this))
67{
68 (void) connect(_recorder, &QMediaRecorder::recorderStateChanged, this, &QtVideoRecorder::_onRecorderStateChanged);
69 (void) connect(_recorder, &QMediaRecorder::errorOccurred, this,
70 [this](QMediaRecorder::Error, const QString& errorString) { _onRecorderError(errorString); });
71 // The first encoded frame starts the recording: Qt reports RecordingState before its encoder is set up.
72 (void) connect(_recorder, &QMediaRecorder::durationChanged, this, [this](qint64 duration) {
73 if (!_recording && (duration > 0) && (_recorder->recorderState() == QMediaRecorder::RecordingState)) {
74 _recording = true;
75 emit recordingStarted(_recordingFile);
76 emit recordingChanged(true);
77 }
78 });
79}
80
82
83QList<QMediaFormat> QtVideoRecorder::recordingFormats(QMediaFormat::FileFormat container,
84 QMediaFormat::VideoCodec codec)
85{
86 QList<QMediaFormat::FileFormat> containers{container};
87 for (const QMediaFormat::FileFormat other : kRecordingContainers) {
88 if (!containers.contains(other)) {
89 containers.append(other);
90 }
91 }
92 QList<QMediaFormat> formats;
93 if (codec != QMediaFormat::VideoCodec::Unspecified) {
94 for (const QMediaFormat::FileFormat candidate : std::as_const(containers)) {
95 if (const std::optional<QMediaFormat> format = encodableFormat(candidate, codec)) {
96 formats.append(*format);
97 break;
98 }
99 }
100 }
101 for (const QMediaFormat::FileFormat candidate : std::as_const(containers)) {
102 QList<QMediaFormat> fallbacks;
103 for (const QMediaFormat::VideoCodec fallback : kFallbackCodecs) {
104 if (const std::optional<QMediaFormat> format = encodableFormat(candidate, fallback)) {
105 fallbacks.append(*format);
106 }
107 }
108 if (!fallbacks.isEmpty()) {
109 for (const QMediaFormat& format : std::as_const(fallbacks)) {
110 if (!formats.contains(format)) {
111 formats.append(format);
112 }
113 }
114 break;
115 }
116 }
117 return formats;
118}
119
121{
122 QList<QMediaFormat::VideoCodec> codecs(std::begin(kFallbackCodecs), std::end(kFallbackCodecs));
123 const QMetaEnum codecEnum = QMetaEnum::fromType<QMediaFormat::VideoCodec>();
124 for (int i = 0; i < codecEnum.keyCount(); i++) {
125 const auto codec = static_cast<QMediaFormat::VideoCodec>(codecEnum.value(i));
126 if ((codec != QMediaFormat::VideoCodec::Unspecified) && !codecs.contains(codec)) {
127 codecs.append(codec);
128 }
129 }
130
131 QStringList keys;
132 for (const QMediaFormat::VideoCodec codec : std::as_const(codecs)) {
133 const bool encodable = std::ranges::any_of(kRecordingContainers, [codec](QMediaFormat::FileFormat container) {
134 return encodableFormat(container, codec).has_value();
135 });
136 if (encodable) {
137 keys.append(QString::fromLatin1(codecEnum.valueToKey(static_cast<int>(codec))));
138 }
139 }
140 return keys;
141}
142
143QMediaFormat::VideoCodec QtVideoRecorder::recordingCodec(const QString& key)
144{
145 bool ok = false;
146 const int value = QMetaEnum::fromType<QMediaFormat::VideoCodec>().keyToValue(key.toLatin1().constData(), &ok);
147 return ok ? static_cast<QMediaFormat::VideoCodec>(value) : QMediaFormat::VideoCodec::Unspecified;
148}
149
150QString QtVideoRecorder::recordingCodecName(const QString& key)
151{
152 return QMediaFormat::videoCodecDescription(recordingCodec(key));
153}
154
156{
157 switch (format) {
159 return QMediaFormat::Matroska;
161 return QMediaFormat::QuickTime;
163 break;
164 }
165 return QMediaFormat::MPEG4;
166}
167
168QMediaRecorder::Quality QtVideoRecorder::recordingQuality(int value)
169{
170 const bool valid = (value >= QMediaRecorder::VeryLowQuality) && (value <= QMediaRecorder::VeryHighQuality);
171 return valid ? static_cast<QMediaRecorder::Quality>(value) : QMediaRecorder::HighQuality;
172}
173
174void QtVideoRecorder::start(const QString& file, QMediaFormat::FileFormat container, QMediaFormat::VideoCodec codec,
175 QMediaRecorder::Quality quality)
176{
177 _pendingFormats = recordingFormats(container, codec);
178 if (_pendingFormats.isEmpty()) {
179 qCWarning(QtVideoRecorderLog) << "No video encoder:" << file;
180 emit recordingFinished(file, tr("No video encoder is available"));
181 return;
182 }
183 const QFileInfo info(file);
184 _recordingBase = QStringLiteral("%1/%2").arg(info.path(), info.completeBaseName());
185 _quality = quality;
186 _stopRequested = false;
187 _recordNextFormat();
188}
189
190void QtVideoRecorder::_recordNextFormat()
191{
192 const QMediaFormat format = _pendingFormats.takeFirst();
193 _recordingFile = QStringLiteral("%1.%2").arg(_recordingBase, fileSuffix(format));
194 _recordingError.clear();
195 qCDebug(QtVideoRecorderLog) << "record" << _recordingFile << format.fileFormat() << format.videoCodec();
196 _recorder->setMediaFormat(format);
197 // Qt defect, seen in Qt 6.12.0 on Android: the recorder opens the encoder with a time base of one frame, then
198 // stamps the frames in the muxer's (1/15360 s in MP4). MediaCodec takes them for seconds apart and spends several
199 // times the bit rate Qt worked out from the quality: 45 Mbit/s rather than 6 for 1080p at High on a Snapdragon
200 // 778G. No setting of the recorder corrects the times; a lower quality still makes a smaller file.
201 _recorder->setQuality(_quality);
202 // Tagged with the time it starts and the application, as GStreamer's recordings are (RecordingBranch).
203 QMediaMetaData metaData;
204 metaData.insert(QMediaMetaData::Date, QDateTime::currentDateTimeUtc());
205 metaData.insert(QMediaMetaData::Comment, VideoReceiver::recordingComment());
206 _recorder->setMetaData(metaData);
207 _recorder->setOutputLocation(QUrl::fromLocalFile(_recordingFile));
208 _recorder->record();
209}
210
211void QtVideoRecorder::_retryNextFormat()
212{
213 if (_stopRequested || active() || _pendingFormats.isEmpty()) {
214 return;
215 }
216 _recordNextFormat();
217}
218
220{
221 _stopRequested = true;
222 _recorder->stop();
223}
224
225void QtVideoRecorder::stopAndWait(std::chrono::milliseconds timeout)
226{
227 if (!_recording) {
228 stop();
229 return;
230 }
231 QEventLoop loop;
232 QTimer::singleShot(timeout, &loop, &QEventLoop::quit);
233 (void) connect(this, &QtVideoRecorder::recordingChanged, &loop, [&loop](bool recording) {
234 if (!recording) {
235 loop.quit();
236 }
237 });
238 stop();
239 if (_recording) {
240 (void) loop.exec();
241 }
242}
243
244void QtVideoRecorder::_onRecorderStateChanged(QMediaRecorder::RecorderState state)
245{
246 if (state != QMediaRecorder::StoppedState) {
247 return;
248 }
249 if (_recording) {
250 _recording = false;
251 emit recordingFinished(_recordingFile, _recordingError);
252 emit recordingChanged(false);
253 } else {
254 _onRecordingNotStarted();
255 }
256}
257
258void QtVideoRecorder::_onRecorderError(const QString& errorString)
259{
260 qCWarning(QtVideoRecorderLog) << "Recording error:" << _recordingFile << errorString;
261 _recordingError = errorString;
262 // A recorder that is still running reports the end when it stops.
263 if (!_recording && (_recorder->recorderState() == QMediaRecorder::StoppedState)) {
264 _onRecordingNotStarted();
265 }
266}
267
268void QtVideoRecorder::_onRecordingNotStarted()
269{
270 removeIfEmpty(_recordingFile);
271 if (_recordingError.isEmpty() || _stopRequested) {
272 return;
273 }
274 if (!_pendingFormats.isEmpty() && _recorder->captureSession()) {
275 qCDebug(QtVideoRecorderLog) << "Encoder failed, trying the next format:" << _recordingError;
276 // Not from the recorder's own signal.
277 QMetaObject::invokeMethod(this, &QtVideoRecorder::_retryNextFormat, Qt::QueuedConnection);
278 return;
279 }
280 const QString error = std::exchange(_recordingError, QString());
281 emit recordingFinished(_recordingFile, error);
282}
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static QList< QMediaFormat > recordingFormats(QMediaFormat::FileFormat container, QMediaFormat::VideoCodec codec=QMediaFormat::VideoCodec::Unspecified)
bool recording() const
From the first encoded frame until the recorder stops.
void recordingChanged(bool recording)
static QMediaFormat::VideoCodec recordingCodec(const QString &key)
The codec of key key, as recordingCodecs() names it; Unspecified for an empty or unknown key.
static QMediaFormat::FileFormat container(VideoReceiver::FileFormat format)
The container of format.
void recordingFinished(const QString &file, const QString &error)
error is empty for a recording that finished normally.
QtVideoRecorder(QObject *parent=nullptr)
static QStringList recordingCodecs()
void recordingStarted(const QString &file)
void stopAndWait(std::chrono::milliseconds timeout=kFinishTimeout)
static QMediaRecorder::Quality recordingQuality(int value)
The quality of value value, one of VideoSettings::uvcRecordingQuality's; HighQuality for any other.
static QString recordingCodecName(const QString &key)
The name of the codec of key key, such as "H.264", for display.
void start(const QString &file, QMediaFormat::FileFormat container, QMediaFormat::VideoCodec codec=QMediaFormat::VideoCodec::Unspecified, QMediaRecorder::Quality quality=QMediaRecorder::HighQuality)
~QtVideoRecorder() override
bool active() const
Recording, or waiting for the first frame to encode.
FileFormat
Values are persisted by VideoSettings::recordingFormat.
static QString recordingComment()
The comment recordings carry, of GStreamer and of a USB camera alike: the application and its version...
QByteArray format(const QList< LogEntry > &entries, int fmt)