diff options
| author | Anton <anton@picapica.im> | 2026-12-05 16:19:13 +0400 |
|---|---|---|
| committer | Anton <anton@picapica.im> | 2026-12-05 16:19:13 +0400 |
| commit | 59b0bdc4b0ff24dfaef0cfaed4051cfa0405379b (patch) | |
| tree | 1cb39f54be7123aabb78b3edfbb3d960f7279f3b | |
| parent | c3298beb0779a8cc09b6d4ea0d2132c0612ea776 (diff) | |
| download | pica-pica-59b0bdc4b0ff24dfaef0cfaed4051cfa0405379b.tar.gz pica-pica-59b0bdc4b0ff24dfaef0cfaed4051cfa0405379b.zip | |
pica-client: improve hwaccel probing and aligning bitrate with framerateqr_codes
| -rw-r--r-- | pica-client/audiovideocallcontroller.cpp | 10 | ||||
| -rw-r--r-- | pica-client/callquality.cpp | 30 | ||||
| -rw-r--r-- | pica-client/callquality.h | 23 | ||||
| -rw-r--r-- | pica-client/callsettings.cpp | 23 | ||||
| -rw-r--r-- | pica-client/callsettings.h | 21 | ||||
| -rw-r--r-- | pica-client/dialogs/settingsdialog.cpp | 308 | ||||
| -rw-r--r-- | pica-client/dialogs/settingsdialog.h | 41 | ||||
| -rw-r--r-- | pica-client/videodevice.cpp | 387 | ||||
| -rw-r--r-- | pica-client/videodevice.h | 51 |
9 files changed, 700 insertions, 194 deletions
diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 5a79c06..5f24e73 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -92,12 +92,6 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(cam, SIGNAL(streamChanged(QString,int,int)), this, SLOT(video_stream_changed(QString,int,int))); cam_thread.start(); - // The presets choose among the hardware encoders that work, which takes - // opening each of them to find out. Done now, on the camera's thread, - // rather than holding up the first call's video. - if (CallSettings::load().qualityPreset != CallQualityCustom) - QMetaObject::invokeMethod(cam, "probeHardwareEncoders", Qt::QueuedConnection); - remotevideo = new VideoDevice(); remotevideo->moveToThread(&remotevideo_thread); remotevideo_thread.start(); @@ -337,7 +331,9 @@ void AudioVideoCallController::startVideoPipeline() // Anything but Custom replaces most of what configureCapture() was just // given, within that limit - see VideoDevice::setQualityPreset(). QMetaObject::invokeMethod(cam, "setQualityPreset", Qt::QueuedConnection, - Q_ARG(int, (int)cs.qualityPreset)); + Q_ARG(int, (int)cs.qualityPreset), + Q_ARG(QStringList, VideoDevice::HardwareEncoderNames( + VideoDevice::PresetHardwareEncoders(cs.videoEncodingAcceleration)))); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see diff --git a/pica-client/callquality.cpp b/pica-client/callquality.cpp index 33289a1..eebf8c4 100644 --- a/pica-client/callquality.cpp +++ b/pica-client/callquality.cpp @@ -197,6 +197,36 @@ static void chooseEncoder(CallQualityPreset preset, const QList<CallHardwareEnco *acceleration = 0; } +QList<CallHardwareEncoder> callUsableHardwareEncoders(const QList<CallHardwareEncoder> &builtIn, + const QStringList &working, + int accelerationFlags) +{ + QList<CallHardwareEncoder> usable; + int verified = 0; + + for (int i = 0; i < builtIn.size(); i++) + { + const CallHardwareEncoder &e = builtIn.at(i); + + if ((accelerationFlags & e.acceleration) && working.contains(e.encoder)) + { + usable << e; + verified |= e.acceleration; + } + } + + for (int i = 0; i < builtIn.size(); i++) + { + const CallHardwareEncoder &e = builtIn.at(i); + + if ((accelerationFlags & e.acceleration) && !(verified & e.acceleration) && + e.codec == QLatin1String("h264")) + usable << e; + } + + return usable; +} + // The highest of rates, at most maxRate, at which size stays within // pixelRateCap. 0 if there is none. static int bestFrameRate(const QSize &size, const QList<int> &rates, int maxRate, double pixelRateCap) diff --git a/pica-client/callquality.h b/pica-client/callquality.h index a147433..48ad77f 100644 --- a/pica-client/callquality.h +++ b/pica-client/callquality.h @@ -22,6 +22,7 @@ #include <QMetaType> #include <QSize> #include <QString> +#include <QStringList> // What the call quality presets other than CallQualityCustom turn into: the // codec, hardware encoder, picture size, frame rate and bitrate a call starts @@ -29,12 +30,13 @@ // call. // // Nothing in here touches FFmpeg, a camera or the settings database. Its inputs -// are what VideoDevice found out - the camera's sizes and rates, the hardware -// encoders that work - so that the decisions can be tested on their own, see +// are what VideoDevice and the settings found out - the camera's sizes and +// rates, the hardware encoders that work - so that the decisions can be tested on their own, see // tests/test_callquality. -// One hardware encoder that opened and encoded a frame on this machine, as -// found by VideoDevice::ProbeHardwareEncoders(). +// One hardware encoder FFmpeg has for a call codec - see +// VideoDevice::HardwareEncodersBuiltIn() - and, handed to callPlanVideo(), one +// a preset may use. struct CallHardwareEncoder { // FFmpeg codec name, one of kCallVideoCodecs. @@ -108,12 +110,23 @@ QList<QSize> callVideoSizeLadder(const QSize &top); // What a call made with `preset` sends. camera is what the camera offers, // empty when it could not be asked; peerLimit the recommended resolution of // the peer's 0x70/0x71, a dimension of 0 being unlimited; hardware the -// encoders that work here, in the order VideoDevice would try them. +// encoders it may use, see callUsableHardwareEncoders(). // // Not for CallQualityCustom, whose settings are used as they are. CallVideoPlan callPlanVideo(CallQualityPreset preset, const QList<CallCameraSize> &camera, const QSize &peerLimit, const QList<CallHardwareEncoder> &hardware); +// The hardware encoders a preset may use, out of the ones this build has: +// those of an acceleration the user left enabled on the "Video Devices" tab +// that the probe on the "Presets" tab found working - `working` names them. +// An acceleration enabled with none of its encoders known to work, because +// the probe failed or never ran and the user ticked it anyway, gets its H.264 +// encoder, the one a GPU is likeliest to have; a call falls back to the CPU if +// it does not open. Encoders known to work come first. +QList<CallHardwareEncoder> callUsableHardwareEncoders(const QList<CallHardwareEncoder> &builtIn, + const QStringList &working, + int accelerationFlags); + // The audio codec and bitrate a call is made with: the stored ones for // CallQualityCustom, the preset's otherwise. CallAudioPlan callPlanAudio(const CallSettings &cs); diff --git a/pica-client/callsettings.cpp b/pica-client/callsettings.cpp index 630f8e3..17ae382 100644 --- a/pica-client/callsettings.cpp +++ b/pica-client/callsettings.cpp @@ -243,3 +243,26 @@ CallSettings CallSettings::load() return cs; } + +static QString hardwareEncoderProbeKey(const QString &encoder) +{ + return QString("call.%1_probe_success").arg(encoder); +} + +HardwareEncoderProbe CallSettings::loadHardwareEncoderProbe(const QString &encoder) +{ + Settings st(config_dbname); + const QVariant value = st.loadValue(hardwareEncoderProbeKey(encoder), QVariant()); + + if (value.isNull()) + return HardwareEncoderNotProbed; + + return value.toBool() ? HardwareEncoderWorks : HardwareEncoderFailed; +} + +void CallSettings::storeHardwareEncoderProbe(const QString &encoder, bool works) +{ + Settings st(config_dbname); + + st.storeValue(hardwareEncoderProbeKey(encoder), works ? "1" : "0"); +} diff --git a/pica-client/callsettings.h b/pica-client/callsettings.h index 38f8681..063e4d2 100644 --- a/pica-client/callsettings.h +++ b/pica-client/callsettings.h @@ -106,7 +106,8 @@ extern const int kIncomingVideoLimitSizeCount; // picture size, frame rate and hardware encoder a call is made with. All but // CallQualityCustom work these out when the call starts, from what the camera // offers, what the peer asked for in its 0x70/0x71 and which hardware encoders -// turn out to work on this machine - see callquality.h. +// may be used - enabled on the "Video Devices" tab and, as far as is known, +// working on this machine, see HardwareEncoderProbe and callquality.h. enum CallQualityPreset { // The largest picture and frame rate there is, at the bitrate it needs. @@ -123,6 +124,19 @@ enum CallQualityPreset CallQualityCustom }; +// What the probe on the "Presets" tab found out about one hardware encoder, +// kept as "call.<encoder>_probe_success" - "call.h264_vaapi_probe_success". +// The record is written as failed before the probe runs and only turned into +// a success once the encoder has opened and encoded a frame, so a driver that +// takes the program down with it leaves a failure behind and is not probed +// again by itself - only when the user asks for it. +enum HardwareEncoderProbe +{ + HardwareEncoderNotProbed, + HardwareEncoderFailed, + HardwareEncoderWorks +}; + struct CallSettings { // Everything below except the incoming video limit and the decoding @@ -165,6 +179,11 @@ struct CallSettings // settings database - not from a capture or playback loop, see // AudioDevice::SetLinuxDriverName() for why. static CallSettings load(); + + // The probe record of one hardware encoder, by FFmpeg encoder name. The + // same threading rule as load(). + static HardwareEncoderProbe loadHardwareEncoderProbe(const QString &encoder); + static void storeHardwareEncoderProbe(const QString &encoder, bool works); }; // The rate a given audio codec is captured and encoded at, and announced at in diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp index b0eb6a5..84ca651 100644 --- a/pica-client/dialogs/settingsdialog.cpp +++ b/pica-client/dialogs/settingsdialog.cpp @@ -40,6 +40,7 @@ #include <QEvent> #include <QTabWidget> #include <QTimer> +#include <QShowEvent> #include <QHeaderView> #include <QMessageBox> #include <QHostAddress> @@ -112,7 +113,12 @@ SettingsDialog::SettingsDialog(QWidget *parent) : // Refreshed along with the camera's formats, which are filled before the // Presets tab is built. lbQualitySummary = nullptr; - hwProbeRequested = false; + btHwProbe = nullptr; + hwProbeState = HwProbeIdle; + hwProbeSecondsLeft = 0; + hwProbeOffered = false; + hwProbeAccelerations = 0; + hwProbeCloseRequested = false; // Same problem, one step further along: videoPreview is watched for its own // resizes and answers them by telling testDecoder what size to decode to, @@ -129,6 +135,7 @@ SettingsDialog::SettingsDialog(QWidget *parent) : QVBoxLayout *settingsLayout = new QVBoxLayout(); QTabWidget *tabW = new QTabWidget(this); + tabWidget = tabW; QWidget* directc2ctab = new QWidget(0); QWidget* soundstab = new QWidget(0); QWidget* multilogintab = new QWidget(0); @@ -136,6 +143,7 @@ SettingsDialog::SettingsDialog(QWidget *parent) : QWidget* videodevtab = new QWidget(0); QWidget* calltab = new QWidget(0); QWidget* presetstab = new QWidget(0); + presetsTab = presetstab; QVBoxLayout *directc2cLayout = new QVBoxLayout(); QVBoxLayout *multiloginlayout = new QVBoxLayout(); @@ -560,9 +568,10 @@ SettingsDialog::SettingsDialog(QWidget *parent) : connect(videoPreviewGpu->widget(), SIGNAL(renderingFailed(QString)), this, SLOT(videoTestRenderFailed(QString))); #endif - lbVideoPresetHint = new QLabel(tr("The resolution, frame rate, compressed formats and hardware " - "encoding a call uses are chosen by the call quality preset. " - "Select \"Custom\" on the Presets tab to set them here."), this); + lbVideoPresetHint = new QLabel(tr("The resolution, frame rate and compressed formats a call uses " + "are chosen by the call quality preset. Select \"Custom\" on " + "the Presets tab to set them here. The preset encodes on the " + "GPU only where hardware encoding is enabled below."), this); lbVideoPresetHint->setWordWrap(true); videodevLayout->addWidget(videoDev); @@ -790,17 +799,36 @@ SettingsDialog::SettingsDialog(QWidget *parent) : tr("The codecs, bitrates, picture size, frame rate and hardware encoding set on the Call " "Settings and Video Devices tabs.")); - gbQuality->setLayout(qualityLayout); + btHwProbe = new QPushButton(gbQuality); + hwProbeTimer = new QTimer(this); + hwProbeTimer->setInterval(1000); + connect(btHwProbe, SIGNAL(clicked()), this, SLOT(hardwareProbeClicked())); + connect(hwProbeTimer, SIGNAL(timeout()), this, SLOT(hardwareProbeTick())); + connect(testCam, SIGNAL(hardwareEncoderProbed(QString,bool)), this, SLOT(hardwareEncoderProbed(QString,bool))); + connect(testCam, SIGNAL(hardwareEncodersProbed()), this, SLOT(hardwareEncodersProbed())); - lbQualitySummary = new QLabel(this); + // Nothing to probe in a build without hardware encoders. + btHwProbe->setVisible(!VideoDevice::HardwareEncodersBuiltIn().isEmpty()); + updateHardwareProbeButton(); + qualityLayout->addWidget(btHwProbe, 0, Qt::AlignLeft); + + lbQualitySummary = new QLabel(gbQuality); lbQualitySummary->setWordWrap(true); lbQualitySummary->setTextInteractionFlags(Qt::TextSelectableByMouse); + qualityLayout->addWidget(lbQualitySummary); - connect(testCam, SIGNAL(hardwareEncodersProbed()), this, SLOT(hardwareEncodersProbed())); + gbQuality->setLayout(qualityLayout); + + // Which GPU encoders a preset may use is up to these. + for (VideoAcceleration a : { VideoAccelerationVaapi, VideoAccelerationD3d12va, + VideoAccelerationMediaFoundation }) + { + if (QCheckBox *cb = encodingCheckBox(a)) + connect(cb, &QCheckBox::toggled, this, [this]() { updateCallQualitySummary(); }); + } QVBoxLayout *presetsLayout = new QVBoxLayout(); presetsLayout->addWidget(gbQuality); - presetsLayout->addWidget(lbQualitySummary); presetsLayout->addStretch(1); presetstab->setLayout(presetsLayout); @@ -811,6 +839,11 @@ SettingsDialog::SettingsDialog(QWidget *parent) : tabW->addTab(videodevtab, tr("Video Devices")); tabW->addTab(calltab, tr("Call Settings")); tabW->addTab(soundstab, tr("Sounds")); + // After the tabs are added: adding the first one makes it the current one. + connect(tabW, &QTabWidget::currentChanged, this, [this]() { + if (tabWidget->currentWidget() == presetsTab) + offerHardwareProbe(); + }); settingsLayout->addWidget(tabW); QHBoxLayout *buttonsLayout = new QHBoxLayout; @@ -1191,7 +1224,9 @@ void SettingsDialog::toggleVideoTest() // As a call with no limit from the other side would; Adaptive stays where // it starts, there being no peer to report back. QMetaObject::invokeMethod(testCam, "setQualityPreset", Qt::QueuedConnection, - Q_ARG(int, (int)selectedQualityPreset())); + Q_ARG(int, (int)selectedQualityPreset()), + Q_ARG(QStringList, VideoDevice::HardwareEncoderNames( + VideoDevice::PresetHardwareEncoders(selectedVideoEncodingAcceleration())))); QMetaObject::invokeMethod(testCam, "Capture", Qt::QueuedConnection); // The decoder is only started once the camera has settled on a format, @@ -1786,19 +1821,9 @@ void SettingsDialog::updateCallQualityWidgets() videoFps->setEnabled(custom); cbPreferCompressed->setEnabled(custom); - // The decoding side is left alone: what the peer sends is decoded the same - // whatever the preset. The encoding side is enabled only where - // offerAcceleration() did not grey it out to begin with. -#ifdef HAVE_VAAPI - cbVaapiEncoding->setEnabled(custom && VideoDevice::AccelerationBuiltIn(VideoAccelerationVaapi, true)); -#endif -#ifdef HAVE_D3D12VA - cbD3d12vaEncoding->setEnabled(custom && VideoDevice::AccelerationBuiltIn(VideoAccelerationD3d12va, true)); -#endif -#ifdef Q_OS_WIN - cbMediaFoundationEncoding->setEnabled(custom && - VideoDevice::AccelerationBuiltIn(VideoAccelerationMediaFoundation, true)); -#endif + // The acceleration checkboxes are left alone: the decoding side applies + // whatever the preset, and the encoding side says which GPU encoders a + // preset may use. lbCallPresetHint->setVisible(!custom); lbVideoPresetHint->setVisible(!custom); @@ -1819,36 +1844,38 @@ void SettingsDialog::updateCallQualitySummary() return; const CallQualityPreset preset = selectedQualityPreset(); - QList<CallHardwareEncoder> hardware; + const QList<CallHardwareEncoder> builtIn = VideoDevice::HardwareEncodersBuiltIn(); + QStringList encoders; - if (!VideoDevice::HardwareEncodersProbed(&hardware)) + for (int i = 0; i < builtIn.size(); i++) { - lbQualitySummary->setText(tr("Finding out which hardware video encoders work on this computer...")); + const CallHardwareEncoder &e = builtIn.at(i); + const QString name = QString(QLatin1String("%1 (%2)")) + .arg(videoCodecDisplayName(e.codec), e.encoder); - // On testCam's thread rather than here: it takes a while, and on - // Windows Media Foundation does not work on this thread. A video test - // that is running holds it up until it stops. - if (!hwProbeRequested) + switch (CallSettings::loadHardwareEncoderProbe(e.encoder)) { - hwProbeRequested = true; - QMetaObject::invokeMethod(testCam, "probeHardwareEncoders", Qt::QueuedConnection); + case HardwareEncoderWorks: + encoders << tr("%1 works").arg(name); + break; + case HardwareEncoderFailed: + encoders << tr("%1 does not work").arg(name); + break; + case HardwareEncoderNotProbed: + default: + encoders << tr("%1 not probed yet").arg(name); + break; } - - return; } - QStringList encoders; - - for (int i = 0; i < hardware.size(); i++) - encoders << QString(QLatin1String("%1 (%2)")) - .arg(videoCodecDisplayName(hardware.at(i).codec), hardware.at(i).encoder); - - QString text = tr("Hardware video encoders that work on this computer: %1.") - .arg(encoders.isEmpty() ? tr("none, video is encoded on the CPU") - : encoders.join(QLatin1String(", "))); + QString text = builtIn.isEmpty() + ? tr("This build has no hardware video encoders: video is encoded on the CPU.") + : tr("Hardware video encoders: %1.").arg(encoders.join(QLatin1String(", "))); if (preset != CallQualityCustom) { + const QList<CallHardwareEncoder> hardware = + VideoDevice::PresetHardwareEncoders(selectedVideoEncodingAcceleration()); const CallVideoPlan video = callPlanVideo(preset, VideoDevice::CallCameraSizes(videoFormats), QSize(0, 0), hardware); CallSettings cs; @@ -1878,9 +1905,183 @@ void SettingsDialog::updateCallQualitySummary() lbQualitySummary->setText(text); } +QCheckBox *SettingsDialog::encodingCheckBox(VideoAcceleration acceleration) const +{ + switch (acceleration) + { +#ifdef HAVE_VAAPI + case VideoAccelerationVaapi: + return cbVaapiEncoding; +#endif +#ifdef HAVE_D3D12VA + case VideoAccelerationD3d12va: + return cbD3d12vaEncoding; +#endif +#ifdef Q_OS_WIN + case VideoAccelerationMediaFoundation: + return cbMediaFoundationEncoding; +#endif + default: + return nullptr; + } +} + +void SettingsDialog::updateHardwareProbeButton() +{ + switch (hwProbeState) + { + case HwProbeCountdown: + btHwProbe->setText(hwProbeSecondsLeft == 1 + ? tr("Probing hardware acceleration capabilities in 1 second, press to cancel") + : tr("Probing hardware acceleration capabilities in %1 seconds, press to cancel") + .arg(hwProbeSecondsLeft)); + btHwProbe->setEnabled(true); + break; + + case HwProbeRunning: + btHwProbe->setText(tr("Probing hardware acceleration capabilities...")); + btHwProbe->setEnabled(false); + break; + + case HwProbeIdle: + default: + btHwProbe->setText(tr("Probe hardware acceleration capabilities")); + btHwProbe->setEnabled(true); + break; + } +} + +void SettingsDialog::offerHardwareProbe() +{ + if (hwProbeOffered || hwProbeState != HwProbeIdle) + return; + + hwProbeOffered = true; + + // Only encoders that were never probed: one recorded as not working may + // be the one that crashed the program last time. + const QList<CallHardwareEncoder> builtIn = VideoDevice::HardwareEncodersBuiltIn(); + bool unprobed = false; + + for (int i = 0; i < builtIn.size() && !unprobed; i++) + unprobed = CallSettings::loadHardwareEncoderProbe(builtIn.at(i).encoder) == HardwareEncoderNotProbed; + + if (!unprobed) + return; + + hwProbeState = HwProbeCountdown; + hwProbeSecondsLeft = 3; + hwProbeTimer->start(); + updateHardwareProbeButton(); +} + +void SettingsDialog::hardwareProbeTick() +{ + if (--hwProbeSecondsLeft > 0) + { + updateHardwareProbeButton(); + return; + } + + hwProbeTimer->stop(); + startHardwareProbe(true); +} + +void SettingsDialog::hardwareProbeClicked() +{ + if (hwProbeState == HwProbeCountdown) + { + hwProbeTimer->stop(); + hwProbeState = HwProbeIdle; + updateHardwareProbeButton(); + return; + } + + if (hwProbeState == HwProbeIdle) + startHardwareProbe(false); +} + +void SettingsDialog::startHardwareProbe(bool unprobedOnly) +{ + const QList<CallHardwareEncoder> builtIn = VideoDevice::HardwareEncodersBuiltIn(); + QStringList encoders; + + hwProbeAccelerations = 0; + + for (int i = 0; i < builtIn.size(); i++) + { + if (unprobedOnly && + CallSettings::loadHardwareEncoderProbe(builtIn.at(i).encoder) != HardwareEncoderNotProbed) + continue; + + encoders << builtIn.at(i).encoder; + hwProbeAccelerations |= builtIn.at(i).acceleration; + } + + if (encoders.isEmpty()) + { + hwProbeState = HwProbeIdle; + updateHardwareProbeButton(); + return; + } + + // All of them recorded as failed before any is opened: if a driver + // takes the program down, none of them is probed again by itself. + for (int i = 0; i < encoders.size(); i++) + CallSettings::storeHardwareEncoderProbe(encoders.at(i), false); + + // The probe runs on testCam's thread, which a running test keeps busy. + if (videoTestRunning) + stopVideoTest(); + + hwProbeState = HwProbeRunning; + updateHardwareProbeButton(); + // Storing the checkboxes now would store them as they were before the + // probe; see also reject(). + btOk->setEnabled(false); + + // On testCam's thread rather than here: it takes a while, and on Windows + // Media Foundation does not work on this thread. + QMetaObject::invokeMethod(testCam, "probeHardwareEncoders", Qt::QueuedConnection, + Q_ARG(QStringList, encoders)); +} + +void SettingsDialog::hardwareEncoderProbed(QString encoder, bool works) +{ + if (works) + CallSettings::storeHardwareEncoderProbe(encoder, true); +} + void SettingsDialog::hardwareEncodersProbed() { + const QList<CallHardwareEncoder> builtIn = VideoDevice::HardwareEncodersBuiltIn(); + + // Each acceleration that was probed is enabled if any of its encoders + // works, and disabled otherwise - the user can still tick it. + for (VideoAcceleration a : { VideoAccelerationVaapi, VideoAccelerationD3d12va, + VideoAccelerationMediaFoundation }) + { + QCheckBox *cb = encodingCheckBox(a); + bool works = false; + + if (!cb || !(hwProbeAccelerations & a) || !cb->isEnabled()) + continue; + + for (int i = 0; i < builtIn.size() && !works; i++) + works = builtIn.at(i).acceleration == a && + CallSettings::loadHardwareEncoderProbe(builtIn.at(i).encoder) == HardwareEncoderWorks; + + cb->setChecked(works); + } + + hwProbeState = HwProbeIdle; + hwProbeAccelerations = 0; + updateHardwareProbeButton(); + btOk->setEnabled(true); updateCallQualitySummary(); + + if (hwProbeCloseRequested) + reject(); } void SettingsDialog::callAudioCodecChanged() @@ -2280,13 +2481,34 @@ void SettingsDialog::OK() if (!validateAddrTable()) return; + hwProbeTimer->stop(); storeSettings(); done(1); } void SettingsDialog::Cancel() { - done(0); + reject(); +} + +void SettingsDialog::reject() +{ + if (hwProbeState == HwProbeRunning) + { + hwProbeCloseRequested = true; + return; + } + + hwProbeTimer->stop(); + QDialog::reject(); +} + +void SettingsDialog::showEvent(QShowEvent *event) +{ + QDialog::showEvent(event); + + if (tabWidget->currentWidget() == presetsTab) + offerHardwareProbe(); } void SettingsDialog::loadSettings() diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h index 3525cbf..062617b 100644 --- a/pica-client/dialogs/settingsdialog.h +++ b/pica-client/dialogs/settingsdialog.h @@ -55,6 +55,13 @@ public: // without the dialog changing size at all. bool eventFilter(QObject *watched, QEvent *event) override; + // Held off while the hardware encoder probe runs, see hwProbeCloseRequested. + void reject() override; + +protected: + // Offers the hardware encoder probe if the dialog opens on the Presets tab. + void showEvent(QShowEvent *event) override; + signals: public slots: @@ -105,8 +112,35 @@ private: // camera, and which hardware encoders work. Null until built, which is // after the camera lists that refresh it. QLabel *lbQualitySummary; - // The hardware encoder probe has been asked of testCam's thread. - bool hwProbeRequested; + + QTabWidget *tabWidget; + QWidget *presetsTab; + + // The hardware encoder probe, run on testCam's thread from the button in + // "Call quality" - see HardwareEncoderProbe for why it is not simply run. + // Encoders that were never probed are probed after a countdown the first + // time the Presets tab is shown; the button cancels the countdown, and + // otherwise probes every encoder again. + enum HwProbeState { HwProbeIdle, HwProbeCountdown, HwProbeRunning }; + QPushButton *btHwProbe; + QTimer *hwProbeTimer; + HwProbeState hwProbeState; + int hwProbeSecondsLeft; + // The countdown has been offered on this opening of the dialog. Only + // once, so that a cancelled one stays cancelled until the next opening. + bool hwProbeOffered; + // VideoAcceleration flags of the encoders being probed: the encoding + // checkboxes of these follow the result. + int hwProbeAccelerations; + // The dialog was closed while probing; it closes once the probe is done, + // so that a successful one gets recorded. + bool hwProbeCloseRequested; + void offerHardwareProbe(); + void startHardwareProbe(bool unprobedOnly); + void updateHardwareProbeButton(); + // The encoding checkbox of one acceleration; null for one this build has + // none for. + QCheckBox *encodingCheckBox(VideoAcceleration acceleration) const; // Say on the tabs the custom settings live on that a preset is deciding // them instead. QLabel *lbCallPresetHint; @@ -381,6 +415,9 @@ private slots: // choose - see audioBitrateKbps. void callAudioCodecChanged(); void callQualityChanged(); + void hardwareProbeClicked(); + void hardwareProbeTick(); + void hardwareEncoderProbed(QString encoder, bool works); void hardwareEncodersProbed(); // Device names are driver specific, so all three lists have to be filled // again when the driver changes. Only ever connected on Linux. diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp index 2d15d45..0fcb01c 100644 --- a/pica-client/videodevice.cpp +++ b/pica-client/videodevice.cpp @@ -167,6 +167,23 @@ static const struct }; #endif +// What the frames given to an encoder are timestamped in: the 90 kHz clock of +// RTP video. Fine enough that a frame's timestamp says when the camera took it, +// which is what libvpx budgets its bits by - see encoderFollowsTimestamps(). +static const AVRational kEncoderTimeBase = { 1, 90000 }; + +// Whether an encoder takes the time between frames from their timestamps, as +// opposed to from the framerate it was opened with. libvpx does. x264 can, but +// not with tune=zerolatency, which turns its variable frame rate input off - +// turning it back on holds every frame back until the next one arrives, to +// learn its duration. Every hardware encoder FFmpeg has and libx265 go by the +// framerate as well. Those are reopened at the rate the camera delivers +// instead, see runTranscodeLoop(). +static bool encoderFollowsTimestamps(const QString &encoderName) +{ + return encoderName == QLatin1String("libvpx-vp9"); +} + static int videoEncoderIndex(const QString &codec) { for (unsigned int i = 0; i < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); i++) @@ -802,6 +819,7 @@ void VideoDevice::configureCapture(QString deviceName, int width, int height, in m_preferCompressed = preferCompressed; m_acceleration = acceleration; m_preset = CallQualityCustom; + m_hardwareEncoders.clear(); // Reports about the previous call's video say nothing about this one. takeReports(); @@ -813,9 +831,22 @@ void VideoDevice::limitCaptureSize(int width, int height) m_maxHeight = qMax(0, height); } -void VideoDevice::setQualityPreset(int preset) +void VideoDevice::setQualityPreset(int preset, QStringList hardwareEncoders) { + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + m_preset = preset; + m_hardwareEncoders.clear(); + + // In the order given, which is the order of preference. + for (int n = 0; n < hardwareEncoders.size(); n++) + { + for (int i = 0; i < builtIn.size(); i++) + { + if (builtIn.at(i).encoder == hardwareEncoders.at(n)) + m_hardwareEncoders << builtIn.at(i); + } + } } void VideoDevice::reportReception(const CallReceptionReport &report) @@ -837,9 +868,18 @@ QList<CallReceptionReport> VideoDevice::takeReports() return reports; } -void VideoDevice::probeHardwareEncoders() +void VideoDevice::probeHardwareEncoders(QStringList encoders) { - ProbeHardwareEncoders(); + for (int i = 0; i < encoders.size(); i++) + { + const bool works = ProbeHardwareEncoder(encoders.at(i)); + + qDebug() << QString("Hardware encoder %1: %2").arg(encoders.at(i), + works ? QStringLiteral("works") + : QStringLiteral("does not work")); + emit hardwareEncoderProbed(encoders.at(i), works); + } + emit hardwareEncodersProbed(); } @@ -1317,7 +1357,7 @@ void VideoDevice::Capture() if (m_planned) { m_plan = callPlanVideo((CallQualityPreset)m_preset, CallCameraSizes(formats), - QSize(m_maxWidth, m_maxHeight), ProbeHardwareEncoders()); + QSize(m_maxWidth, m_maxHeight), m_hardwareEncoders); m_codec = m_plan.codec; m_acceleration = m_plan.acceleration; @@ -1636,7 +1676,7 @@ static AVCodecContext *openHwEncoder(const AVCodec *enc, AVBufferRef *hw_device_ enc_ctx->width = width; enc_ctx->height = height; enc_ctx->pix_fmt = hw_pix_fmt; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -1684,7 +1724,7 @@ static AVCodecContext *openMediaFoundationEncoder(const AVCodec *enc, int width, // What the hardware encoders take natively; YUV420P would be converted // inside the encoder instead of by the scaler we run anyway. enc_ctx->pix_fmt = AV_PIX_FMT_NV12; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -1985,7 +2025,7 @@ static bool openVideoEncoder(int encIdx, int acceleration, int width, int height enc_ctx->width = width; enc_ctx->height = height; enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - enc_ctx->time_base = av_inv_q(frameRate); + enc_ctx->time_base = kEncoderTimeBase; enc_ctx->framerate = frameRate; enc_ctx->bit_rate = bitrate; enc_ctx->gop_size = gopSize; @@ -2089,22 +2129,8 @@ out: return works; } -static QMutex s_probeMutex; -static bool s_probed = false; -static QList<CallHardwareEncoder> s_hardwareEncoders; - -QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() +QList<CallHardwareEncoder> VideoDevice::HardwareEncodersBuiltIn() { - QMutexLocker locker(&s_probeMutex); - - if (s_probed) - return s_hardwareEncoders; - -#ifdef Q_OS_WIN - // Media Foundation will not work otherwise, see ComMultithreadedScope. - ComMultithreadedScope comApartment; -#endif - #if LIBAVFORMAT_VERSION_MAJOR < 58 avcodec_register_all(); #endif @@ -2115,11 +2141,7 @@ QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() VideoAccelerationVaapi, VideoAccelerationD3d12va, VideoAccelerationMediaFoundation }; - // A common call size and rate: a GPU that cannot encode this is no use - // for a call either. - const AVRational frameRate = { 30, 1 }; - - qDebug() << "Finding out which hardware video encoders work - failures below are expected"; + QList<CallHardwareEncoder> encoders; for (unsigned int c = 0; c < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); c++) { @@ -2146,62 +2168,84 @@ QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() #endif } - // Not even built in: nothing to try, and nothing worth a warning. if (!name || !avcodec_find_encoder_by_name(name)) continue; - VideoEncoderSession es; - QString error; + CallHardwareEncoder e; - if (!openVideoEncoder((int)c, kAccelerations[a], 1280, 720, frameRate, 2000000, 60, - false, &es, &error)) - continue; + e.codec = QLatin1String(kVideoEncoders[c].codec); + e.acceleration = kAccelerations[a]; + e.encoder = QLatin1String(name); + encoders << e; + } + } - if (encoderWorks(es.ctx)) - { - CallHardwareEncoder e; + return encoders; +} - e.codec = QLatin1String(kVideoEncoders[c].codec); - e.acceleration = kAccelerations[a]; - e.encoder = es.name; - s_hardwareEncoders << e; - } - else - { - qWarning() << QString("The %1 encoder opened but did not encode a frame").arg(es.name); - } +bool VideoDevice::ProbeHardwareEncoder(const QString &encoder) +{ +#ifdef Q_OS_WIN + // Media Foundation will not work otherwise, see ComMultithreadedScope. + ComMultithreadedScope comApartment; +#endif - closeVideoEncoder(&es); + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + + for (int i = 0; i < builtIn.size(); i++) + { + if (builtIn.at(i).encoder != encoder) + continue; + + // A common call size and rate: a GPU that cannot encode this is no + // use for a call either. + const AVRational frameRate = { 30, 1 }; + VideoEncoderSession es; + QString error; + + if (!openVideoEncoder(videoEncoderIndex(builtIn.at(i).codec), builtIn.at(i).acceleration, + 1280, 720, frameRate, 2000000, 60, false, &es, &error)) + { + qWarning() << QString("Probing %1: %2").arg(encoder, error); + return false; } - } - QStringList names; + const bool works = encoderWorks(es.ctx); - for (int i = 0; i < s_hardwareEncoders.size(); i++) - names << s_hardwareEncoders.at(i).encoder; + if (!works) + qWarning() << QString("Probing %1: opened, but did not encode a frame").arg(encoder); - qDebug() << "Hardware video encoders that work here:" - << (names.isEmpty() ? QStringLiteral("none") : names.join(QLatin1String(", "))); + closeVideoEncoder(&es); - s_probed = true; + return works; + } - return s_hardwareEncoders; + qWarning() << QString("Probing %1: not in this build").arg(encoder); + return false; } -bool VideoDevice::HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders) +QList<CallHardwareEncoder> VideoDevice::PresetHardwareEncoders(int encodingAcceleration) { - // Not waiting is the point: a probe that is running holds the lock. - if (!s_probeMutex.tryLock()) - return false; + const QList<CallHardwareEncoder> builtIn = HardwareEncodersBuiltIn(); + QStringList working; + + for (int i = 0; i < builtIn.size(); i++) + { + if (CallSettings::loadHardwareEncoderProbe(builtIn.at(i).encoder) == HardwareEncoderWorks) + working << builtIn.at(i).encoder; + } - const bool probed = s_probed; + return callUsableHardwareEncoders(builtIn, working, encodingAcceleration); +} - if (probed && encoders) - *encoders = s_hardwareEncoders; +QStringList VideoDevice::HardwareEncoderNames(const QList<CallHardwareEncoder> &encoders) +{ + QStringList names; - s_probeMutex.unlock(); + for (int i = 0; i < encoders.size(); i++) + names << encoders.at(i).encoder; - return probed; + return names; } QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureFormat> &formats) @@ -2220,10 +2264,6 @@ QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureForma return sizes; } -// CallQualityAdaptive: how much a bitrate change has to amount to before an -// encoder that cannot take one while running is reopened for it - each reopen -// starts with a keyframe - and how far apart reopens for increases are kept. -// Decreases are not held back: they are what stops the loss. // The size Preview() asks the camera for: the wanted one if the camera lists // it, otherwise the largest it lists that is no bigger, or failing that the // smallest it has. A camera that could not be enumerated is asked for the @@ -2482,9 +2522,60 @@ void VideoDevice::Preview() avformat_close_input(&ifmt_ctx); } +// CallQualityAdaptive: how much a bitrate change has to amount to before an +// encoder that cannot take one while running is reopened for it - each reopen +// starts with a keyframe - and how far apart reopens for increases are kept. +// Decreases are not held back: they are what stops the loss. static const double kReopenBitrateStep = 0.15; static const int kReopenIntervalMs = 5000; +// An encoder that goes by the framerate it was opened with is reopened at the +// rate the camera actually delivers once that is this far off, measured over +// kFrameRateWindowUs, and no more often than every kFrameRateReopenIntervalMs: +// a camera in a dim room halves its rate to expose longer, and a hardware +// encoder still budgeting for the full rate would send half the bitrate. +static const double kFrameRateReopenStep = 0.2; +static const int64_t kFrameRateWindowUs = 3000000; +static const int kFrameRateReopenIntervalMs = 10000; + +// When each picture was taken, in microseconds from the first: the camera's +// own timestamps where it gives them, our clock where it does not or where +// they jump - backwards, or by more than a second, as a camera stamping from +// the wall clock does when the clock is set. +class CaptureClock +{ +public: + CaptureClock() : m_started(false), m_lastCamera(AV_NOPTS_VALUE), m_lastWall(0), m_now(0) {} + + int64_t next(int64_t cameraTimestamp, AVRational cameraTimeBase, int64_t wallUs) + { + if (m_started) + { + int64_t delta = -1; + + if (cameraTimestamp != AV_NOPTS_VALUE && m_lastCamera != AV_NOPTS_VALUE) + delta = av_rescale_q(cameraTimestamp - m_lastCamera, cameraTimeBase, AVRational{ 1, 1000000 }); + + if (delta <= 0 || delta > 1000000) + delta = wallUs - m_lastWall; + + m_now += qMax<int64_t>(delta, 0); + } + + m_started = true; + m_lastCamera = cameraTimestamp; + m_lastWall = wallUs; + + return m_now; + } + +private: + bool m_started; + int64_t m_lastCamera; + int64_t m_lastWall; + int64_t m_now; +}; + void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) { const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); @@ -2498,7 +2589,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // packet waits this long for a picture, so it is a latency figure as much // as a bandwidth one - hence deriving it from the real rate rather than // from a fixed frame count. - const int gopSize = qMax(1, (int)av_q2d(frameRate) * 2); + auto gopSizeFor = [](AVRational rate) { return qMax(1, (int)(av_q2d(rate) * 2)); }; // What gets encoded: the camera's picture as it is, or for a preset that // sends less than the camera captures, scaled down. @@ -2529,7 +2620,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) QString encoderError; if (!openVideoEncoder(encIdx, m_acceleration, encodeSize.width(), encodeSize.height(), - frameRate, m_bitrate, gopSize, true, &encoder, &encoderError)) + frameRate, m_bitrate, gopSizeFor(frameRate), true, &encoder, &encoderError)) { qWarning() << encoderError; emit errorOccurred(encoderError); @@ -2585,6 +2676,16 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) int64_t currentBitrate = m_bitrate; qint64 lastReopen = 0; + // The rate the encoder was opened for, and what the camera delivers: + // frames counted since rateWindowStart, in captureClock's time. The first + // window is not gone by: a camera takes a moment to settle into its rate. + AVRational encoderRate = frameRate; + CaptureClock captureClock; + int64_t rateWindowStart = -1; + int rateWindowFrames = 0; + bool rateSettled = false; + int64_t lastPts = AV_NOPTS_VALUE; + clock.start(); if (adaptive) @@ -2594,7 +2695,6 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) AVPacket *in_pkt = av_packet_alloc(); AVFrame *cam_frame = av_frame_alloc(); AVPacket *out_pkt = av_packet_alloc(); - int64_t pts = 0; bool loggedReadError = false; bool loggedScaleError = false; bool loggedEncodeError = false; @@ -2621,6 +2721,42 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) while (avcodec_receive_frame(dec_ctx, cam_frame) == 0) { + const int64_t captureUs = captureClock.next(cam_frame->best_effort_timestamp, in_st->time_base, + clock.nsecsElapsed() / 1000); + + // What the encoder is to be reopened with, if anything changes. + QSize wantedSize = encodeSize; + int64_t wantedBitrate = currentBitrate; + AVRational wantedRate = encoderRate; + bool reopen = false; + + if (rateWindowStart < 0) + rateWindowStart = captureUs; + else + rateWindowFrames++; + + if (rateWindowFrames > 0 && captureUs - rateWindowStart >= kFrameRateWindowUs) + { + const double measured = rateWindowFrames * 1000000.0 / (captureUs - rateWindowStart); + + rateWindowStart = captureUs; + rateWindowFrames = 0; + + if (rateSettled && !encoderFollowsTimestamps(encoder.name) && + qAbs(measured / av_q2d(encoderRate) - 1.0) > kFrameRateReopenStep && + (lastReopen == 0 || clock.elapsed() - lastReopen >= kFrameRateReopenIntervalMs)) + { + wantedRate = AVRational{ qMax(1, qRound(measured)), 1 }; + reopen = av_cmp_q(wantedRate, encoderRate) != 0; + + if (reopen) + qDebug() << QString("The camera delivers %1 fps, reopening %2 for that instead of %3") + .arg(measured, 0, 'f', 1).arg(encoder.name).arg(av_q2d(encoderRate)); + } + + rateSettled = true; + } + // Between frames, so that a new encoder starts with a whole one. if (adaptive) { @@ -2636,11 +2772,13 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) m_fragmentsSent = 0; } - const QSize wantedSize = rate.size(); - const int64_t wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; - bool reopen = wantedSize != encodeSize; + wantedSize = rate.size(); + wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; - if (!reopen && wantedBitrate != currentBitrate) + if (wantedSize != encodeSize) + reopen = true; + + if (wantedBitrate != currentBitrate) { const double ratio = (double)wantedBitrate / currentBitrate; @@ -2659,68 +2797,69 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) reopen = true; } } + } - // A failed reopen is not retried for every frame. - if (reopen && lastReopen != 0 && clock.elapsed() - lastReopen < 1000) - reopen = false; + // A failed reopen is not retried for every frame. + if (reopen && lastReopen != 0 && clock.elapsed() - lastReopen < 1000) + reopen = false; - if (reopen) - { - VideoEncoderSession next; - QString error; + if (reopen) + { + VideoEncoderSession next; + QString error; - lastReopen = clock.elapsed(); + lastReopen = clock.elapsed(); - if (openVideoEncoder(encIdx, m_acceleration, wantedSize.width(), wantedSize.height(), - frameRate, wantedBitrate, gopSize, true, &next, &error)) - { - AVFrame *next_frame = allocEncoderFrame(next.ctx); + if (openVideoEncoder(encIdx, m_acceleration, wantedSize.width(), wantedSize.height(), + wantedRate, wantedBitrate, gopSizeFor(wantedRate), true, &next, &error)) + { + AVFrame *next_frame = allocEncoderFrame(next.ctx); - if (next_frame) + if (next_frame) + { + // What the old encoder still holds goes out first; a + // low latency one holds nothing. + if (avcodec_send_frame(encoder.ctx, nullptr) == 0) { - // What the old encoder still holds goes out - // first; a low latency one holds nothing. - if (avcodec_send_frame(encoder.ctx, nullptr) == 0) + while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) { - while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) - { - emitFragments(out_pkt->data, out_pkt->size); - av_packet_unref(out_pkt); - } + emitFragments(out_pkt->data, out_pkt->size); + av_packet_unref(out_pkt); } + } - closeVideoEncoder(&encoder); - av_frame_free(&enc_frame); - - encoder = next; - enc_frame = next_frame; - currentBitrate = wantedBitrate; + closeVideoEncoder(&encoder); + av_frame_free(&enc_frame); - // The scaler targets the encoder's size and format. - if (sws) - { - sws_freeContext(sws); - sws = nullptr; - } + encoder = next; + enc_frame = next_frame; + currentBitrate = wantedBitrate; + encoderRate = wantedRate; - if (wantedSize != encodeSize) - { - encodeSize = wantedSize; - emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); - } + // The scaler targets the encoder's size and format. + if (sws) + { + sws_freeContext(sws); + sws = nullptr; } - else + + if (wantedSize != encodeSize) { - closeVideoEncoder(&next); - qWarning() << "Could not allocate encoder frame, keeping the encoder as it is"; + encodeSize = wantedSize; + emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); } } else { - qWarning() << QString("Could not reopen the video encoder (%1), keeping it as it is") - .arg(error); + closeVideoEncoder(&next); + qWarning() << "Could not allocate encoder frame, keeping the encoder as it is"; } } + else + { + qWarning() << QString("Could not reopen the video encoder (%1), keeping it as it is") + .arg(error); + } } AVCodecContext *enc_ctx = encoder.ctx; @@ -2771,7 +2910,19 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) enc_frame->data, enc_frame->linesize); av_frame_unref(cam_frame); - enc_frame->pts = pts++; + // When the camera took the picture rather than a frame count: a + // camera that delivers fewer frames than it said it would would + // otherwise have each one budgeted for the time of a frame it + // skipped, by the encoders that go by timestamps - see + // encoderFollowsTimestamps(). A new encoder could start over, but + // carrying on from where the last one was is no harm. + int64_t pts = av_rescale_q(captureUs, AVRational{ 1, 1000000 }, enc_ctx->time_base); + + if (lastPts != AV_NOPTS_VALUE && pts <= lastPts) + pts = lastPts + 1; + + lastPts = pts; + enc_frame->pts = pts; // What actually goes to the encoder: the staging frame itself, or // a GPU surface holding a copy of it for an encoder that draws on diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h index 50f8684..72bce36 100644 --- a/pica-client/videodevice.h +++ b/pica-client/videodevice.h @@ -198,11 +198,13 @@ public: // A CallQualityPreset. For any but CallQualityCustom, Capture() puts the // preset's plan in place of the codec, bitrate, size, frame rate and // acceleration given to configureCapture() - worked out from what the - // camera offers, the limit above and the hardware encoders that work, see + // camera offers, the limit above and hardwareEncoders, see // callPlanVideo() - and never forwards the camera's own stream, which - // would leave nothing to plan. Queued after configureCapture(), which - // resets it to CallQualityCustom. - Q_INVOKABLE void setQualityPreset(int preset); + // would leave nothing to plan. hardwareEncoders are the FFmpeg names of + // the GPU encoders the preset may use, most preferred first, as + // PresetHardwareEncoders() gives them. Queued after configureCapture(), + // which resets it to CallQualityCustom. + Q_INVOKABLE void setQualityPreset(int preset, QStringList hardwareEncoders); // One 0x79 report from the peer of the call, for CallQualityAdaptive to // follow - see CallRateController. Ignored with any other preset. Safe to @@ -210,11 +212,12 @@ public: // same reason enqueueFrame() is. void reportReception(const CallReceptionReport &report); - // Runs ProbeHardwareEncoders() on this device's thread and emits - // hardwareEncodersProbed() when it is done. For a caller on a thread that - // must not block, or that Media Foundation will not work on - a Windows - // GUI thread is in COM's single-threaded apartment. - Q_INVOKABLE void probeHardwareEncoders(); + // Runs ProbeHardwareEncoder() for each of `encoders` on this device's + // thread, emitting hardwareEncoderProbed() after each and + // hardwareEncodersProbed() at the end. For a caller on a thread that must + // not block, or that Media Foundation will not work on - a Windows GUI + // thread is in COM's single-threaded apartment. + Q_INVOKABLE void probeHardwareEncoders(QStringList encoders); // Allows Capture()/Play() to run for the call this pair of ids names, // until Close() - the same arrangement as AudioDevice::openSession(). To @@ -374,6 +377,7 @@ signals: void streamChanged(QString codec, int width, int height); // See probeHardwareEncoders(). + void hardwareEncoderProbed(QString encoder, bool works); void hardwareEncodersProbed(); public: @@ -405,16 +409,26 @@ public: // what the settings dialog needs to know before offering it. static bool AccelerationBuiltIn(VideoAcceleration acceleration, bool encoding); - // The hardware encoders that work on this machine: each one FFmpeg has - // for a call codec, through each acceleration this build offers, that - // opens on this machine's GPU and encodes a frame. In the order Capture() - // tries them. Found out once per run - opening an encoder takes up to a - // fraction of a second - and blocks until then, so call it from a thread - // that may wait. Thread-safe. - static QList<CallHardwareEncoder> ProbeHardwareEncoders(); + // Every hardware encoder FFmpeg has for a call codec, through each + // acceleration this build offers, in the order Capture() tries them. + // Whether this machine's GPU can use one is for ProbeHardwareEncoder(). + static QList<CallHardwareEncoder> HardwareEncodersBuiltIn(); - // The same, without waiting: false while the probe has not run yet. - static bool HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders); + // Whether one of those, by FFmpeg encoder name, opens on this machine's GPU + // and encodes a frame. Takes up to a fraction of a second, and a broken + // driver can crash the program instead of answering - which is why the + // settings dialog runs it only after a countdown that can be cancelled, and + // records each one as failed before running it, see HardwareEncoderProbe. + static bool ProbeHardwareEncoder(const QString &encoder); + + // The hardware encoders a preset may use with the given VideoAcceleration + // flags enabled, going by the stored probe records - see + // callUsableHardwareEncoders(). Reads the settings database, so the same + // threading rule as CallSettings::load(). + static QList<CallHardwareEncoder> PresetHardwareEncoders(int encodingAcceleration); + + // Their FFmpeg names, as setQualityPreset() takes them. + static QStringList HardwareEncoderNames(const QList<CallHardwareEncoder> &encoders); // The sizes and rates of CaptureFormats() as the call quality planning // takes them. @@ -433,6 +447,7 @@ private: bool m_preferCompressed; // see setQualityPreset() int m_preset; + QList<CallHardwareEncoder> m_hardwareEncoders; // What Capture() made of a preset; m_planned is false for // CallQualityCustom, which encodes at m_width x m_height. CallVideoPlan m_plan; |
