diff options
| author | Anton <anton@picapica.im> | 2026-11-29 23:38:25 +0400 |
|---|---|---|
| committer | Anton <anton@picapica.im> | 2026-11-29 23:38:25 +0400 |
| commit | 56863d74399c8d7354a00bc8ddc87b924ef870ab (patch) | |
| tree | bd9e44c438f974f80aa6cfef59fe842d3e128ee7 /pica-client | |
| parent | d6ce3a2226bda81cce96c61f0a73fb1516adbd0b (diff) | |
| download | pica-pica-call_quality_presets.tar.gz pica-pica-call_quality_presets.zip | |
pica-client: new presets tab, call quality presetscall_quality_presets
Diffstat (limited to 'pica-client')
| -rw-r--r-- | pica-client/audiovideocallcontroller.cpp | 57 | ||||
| -rw-r--r-- | pica-client/audiovideocallcontroller.h | 8 | ||||
| -rw-r--r-- | pica-client/callquality.cpp | 529 | ||||
| -rw-r--r-- | pica-client/callquality.h | 184 | ||||
| -rw-r--r-- | pica-client/callsettings.cpp | 14 | ||||
| -rw-r--r-- | pica-client/callsettings.h | 26 | ||||
| -rw-r--r-- | pica-client/dialogs/settingsdialog.cpp | 255 | ||||
| -rw-r--r-- | pica-client/dialogs/settingsdialog.h | 27 | ||||
| -rw-r--r-- | pica-client/skynet.cpp | 27 | ||||
| -rw-r--r-- | pica-client/skynet.h | 6 | ||||
| -rw-r--r-- | pica-client/videodevice.cpp | 673 | ||||
| -rw-r--r-- | pica-client/videodevice.h | 58 |
12 files changed, 1740 insertions, 124 deletions
diff --git a/pica-client/audiovideocallcontroller.cpp b/pica-client/audiovideocallcontroller.cpp index 55bcf3a..5a79c06 100644 --- a/pica-client/audiovideocallcontroller.cpp +++ b/pica-client/audiovideocallcontroller.cpp @@ -19,6 +19,7 @@ #include "skynet.h" #include "settings.h" #include "callsettings.h" +#include "callquality.h" #include "accounts.h" #include <QByteArray> #include <QDebug> @@ -49,6 +50,7 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) connect(skynet, SIGNAL(IncomingVideoPacket(QByteArray,quint16,quint32,QByteArray)), this, SLOT(incoming_video_packet(QByteArray,quint16,quint32,QByteArray))); connect(skynet, SIGNAL(CallMediaTransportChanged(QByteArray,bool,QString,quint32)), this, SLOT(media_transport_changed(QByteArray,bool,QString,quint32))); + connect(skynet, SIGNAL(CallReceptionReported(QByteArray,CallReceptionReport)), this, SLOT(reception_reported(QByteArray,CallReceptionReport))); // Earpiece tones (ringback/busy/unreachable) and the incoming call bell // are played by two TonePlayer instances, each living on its own @@ -87,8 +89,15 @@ AudioVideoCallController::AudioVideoCallController(QObject *parent) cam->moveToThread(&cam_thread); connect(cam, SIGNAL(captureStarted(QString,int,int,double)), this, SLOT(video_capture_started(QString,int,int,double))); connect(cam, SIGNAL(packetReady(QByteArray,bool)), this, SLOT(send_video_packet(QByteArray,bool))); + 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(); @@ -167,7 +176,8 @@ void AudioVideoCallController::startAudioPipeline() { Settings st(config_dbname); QString capDev = st.loadValue("audio.capture_device", "default").toString(); - const CallSettings cs = CallSettings::load(); + // The stored codec and bitrate, or the preset's. + const CallAudioPlan audio = callPlanAudio(CallSettings::load()); // What we capture and encode at, announced to the peer in the 0x74 // message. It follows from the codec - see callAudioSampleRate(). @@ -175,12 +185,12 @@ void AudioVideoCallController::startAudioPipeline() // The playback direction is NOT this: it follows whatever the peer // announces in its own 0x74 (see incoming_audio_params()), so a call with // a peer that picked a different codec or rate keeps working. - const int sampleRate = callAudioSampleRate(cs.audioCodec); + const int sampleRate = callAudioSampleRate(audio.codec); // G.722 and A-law spend a fixed number of bits per sample and have no rate // to ask for; the setting only means anything to Opus. - const int bitrate = callAudioBitrateAdjustable(cs.audioCodec) - ? cs.audioBitrateKbps * 1000 + const int bitrate = callAudioBitrateAdjustable(audio.codec) + ? audio.bitrateKbps * 1000 : 0; m_audioSeq = 0; @@ -227,10 +237,10 @@ void AudioVideoCallController::startAudioPipeline() // encoding right away - the peer's decoder is only ready once it has // processed this 0x74 message, but since the call is carried over TCP, // packets sent immediately after are guaranteed to arrive after it. - skynet->SendAudioParams(m_peer_id, cs.audioCodec, (quint16)sampleRate); + skynet->SendAudioParams(m_peer_id, audio.codec, (quint16)sampleRate); QMetaObject::invokeMethod(microphone, "configureCapture", Qt::QueuedConnection, - Q_ARG(QString, capDev), Q_ARG(QString, cs.audioCodec), + Q_ARG(QString, capDev), Q_ARG(QString, audio.codec), Q_ARG(int, sampleRate), Q_ARG(int, bitrate), Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); QMetaObject::invokeMethod(microphone, "Capture", Qt::QueuedConnection); @@ -268,6 +278,7 @@ void AudioVideoCallController::startVideoPipeline() // Before anything is queued for them - see MediaCallSession. And before // the check for a camera below: remotevideo does not depend on having one. m_videoPlaybackStarted = false; + m_remoteVideoCodec.clear(); cam->openSession(m_caller_id, m_callee_id); remotevideo->openSession(m_caller_id, m_callee_id); @@ -323,6 +334,10 @@ void AudioVideoCallController::startVideoPipeline() QMetaObject::invokeMethod(cam, "limitCaptureSize", Qt::QueuedConnection, Q_ARG(int, m_peerRecommendedResolution.width()), Q_ARG(int, m_peerRecommendedResolution.height())); + // 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)); QMetaObject::invokeMethod(cam, "Capture", Qt::QueuedConnection); // remotevideo is configured lazily, once the peer's own 0x75 (see @@ -669,6 +684,24 @@ void AudioVideoCallController::video_capture_started(QString codec, int width, i skynet->SendVideoParams(m_peer_id, codec, (quint16)width, (quint16)height); } +void AudioVideoCallController::video_stream_changed(QString codec, int width, int height) +{ + if (m_state != CallActive) + return; + + skynet->SendVideoParams(m_peer_id, codec, (quint16)width, (quint16)height); +} + +void AudioVideoCallController::reception_reported(QByteArray peer_id, CallReceptionReport report) +{ + if (m_state != CallActive || peer_id != m_peer_id) + return; + + // Direct call, not invokeMethod()/QueuedConnection - cam's thread is + // blocked inside Capture(), see stopAudioPipeline(). + cam->reportReception(report); +} + void AudioVideoCallController::send_video_packet(QByteArray data, bool is_last_fragment) { if (m_state != CallActive) @@ -742,16 +775,28 @@ void AudioVideoCallController::incoming_video_params(QByteArray peer_id, QString if (!m_videoPlaybackStarted) { m_videoPlaybackStarted = true; + m_remoteVideoCodec = codec; QMetaObject::invokeMethod(remotevideo, "configurePlayback", Qt::QueuedConnection, Q_ARG(QString, codec), Q_ARG(int, (int)width), Q_ARG(int, (int)height), Q_ARG(int, cs.videoDecodingAcceleration), Q_ARG(bool, vaapiRendering), Q_ARG(QByteArray, m_caller_id), Q_ARG(QByteArray, m_callee_id)); } + else if (codec == m_remoteVideoCodec) + { + // Only the picture size changed - the peer's adaptive quality stepping + // up or down. The decoder takes the size from the stream itself and + // follows it at the keyframe the new size starts with; restarting it + // would drop that keyframe along with whatever is queued, and leave + // the picture frozen until the next one. Nothing to restart Play() + // for either. + return; + } else { // The peer changed what it is sending in the middle of the call - as // in incoming_audio_params(). A fragment of a frame in the old format // that is still being put together is of no use to the new decoder. + m_remoteVideoCodec = codec; m_videoAssembler.reset(); remotevideo->changePlayback(codec, (int)width, (int)height, cs.videoDecodingAcceleration, vaapiRendering); diff --git a/pica-client/audiovideocallcontroller.h b/pica-client/audiovideocallcontroller.h index b7640fa..90a3d83 100644 --- a/pica-client/audiovideocallcontroller.h +++ b/pica-client/audiovideocallcontroller.h @@ -84,6 +84,9 @@ private: // decoder that is already running. bool m_audioPlaybackStarted; bool m_videoPlaybackStarted; + // The codec of the peer's last 0x75, for telling a new size of the same + // stream from a new stream. + QString m_remoteVideoCodec; // The recommended resolution from the peer's 0x70/0x71: the camera is // stepped down to fit it, see VideoDevice::limitCaptureSize(). A dimension @@ -176,6 +179,11 @@ private slots: void media_transport_changed(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); + // The peer's 0x79, passed on to the camera for CallQualityAdaptive. + void reception_reported(QByteArray peer_id, CallReceptionReport report); + // The camera moved to another picture size in the middle of the call. + void video_stream_changed(QString codec, int width, int height); + // Passes the window's video area on to the decoder, which produces frames // at that size rather than leaving the window to resize each one. void video_area_changed(QSize area); diff --git a/pica-client/callquality.cpp b/pica-client/callquality.cpp new file mode 100644 index 0000000..33289a1 --- /dev/null +++ b/pica-client/callquality.cpp @@ -0,0 +1,529 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, version 3. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#include "callquality.h" +#include <cmath> + +// callVideoBitrateKbps(): kbit/s = kBitrateScale * (pixels per second)^0.75, +// which puts H.264 at 2000 kbit/s for 1280x720 at 30fps, 3700 for 1920x1080 at +// 30, 880 for 640x480 at 30 and 250 for 320x180 at 30 - around where software +// encoders tuned for low latency stop looking noticeably better on a talking +// head for more bits. +static const double kBitrateScale = 0.00525; +static const double kBitrateExponent = 0.75; + +// How much of H.264's bitrate the other two need for the same picture. Less +// than the usual figures for them, which are for encoders given time to look +// ahead - the realtime x265 and libvpx settings gain less over x264's. +static const double kHevcBitrateFactor = 0.7; +static const double kVp9BitrateFactor = 0.75; + +// GPU encoders do without most of what makes a software encoder efficient. +static const double kHardwareBitrateFactor = 1.2; + +// Spread of what callVideoBitrateKbps() hands out. The top is the most the +// settings dialog accepts. +static const int kMinVideoBitrateKbps = 100; +static const int kMaxVideoBitrateKbps = 20000; + +// The most pixels per second each kind of encoder is asked for: 1080p at 30fps +// is about what one CPU core manages with x264 tuned for low latency, a GPU +// encoder takes 4K at 30fps in its stride. +static const double kSoftwarePixelRateCap = 1920.0 * 1080 * 30; +static const double kHardwarePixelRateCap = 3840.0 * 2160 * 30; + +// Frame rate ceilings. A call gains little from more than 30fps, and +// CallQualityAdaptive would rather spend the bandwidth on the picture size; +// CallQualityMax takes what the camera has, up to 60. +static const int kMaxPresetFrameRate = 60; +static const int kAdaptiveFrameRate = 30; +// Below this, motion visibly stutters: a larger size is not worth it. +static const int kSmoothFrameRate = 24; + +// CallQualityEconomy: at most VGA's pixel count, at about this rate, and this +// much of the bitrate a good picture would want. +static const int kEconomyMaxArea = 640 * 480; +static const int kEconomyFrameRate = 15; +static const double kEconomyBitrateFactor = 0.7; + +// Short sides of the sizes CallQualityAdaptive steps between. +static const int kLadderShortSides[] = { 1440, 1080, 720, 540, 360, 270, 180 }; + +// CallQualityAdaptive starts at the largest size of the ladder that is at +// most 720p, at this much of the bitrate it wants: the connection is not +// known yet, and sending more than it carries at the start means a call that +// begins with a frozen picture. +static const int kAdaptiveStartShortSide = 720; +static const double kAdaptiveStartFactor = 0.75; + +// When nothing could be found out about the camera: a few sizes nearly every +// one offers, at a rate nearly every one manages. +static const QSize kFallbackCameraSizes[] = { QSize(1280, 720), QSize(640, 480), QSize(320, 240) }; +static const int kFallbackFrameRate = 30; + +// Audio, Opus at the 16kHz callAudioSampleRate() runs it at: past about 32 +// kbit/s it has nothing left to add to wideband speech. +static const int kMaxAudioBitrateKbps = 40; +static const int kAdaptiveAudioBitrateKbps = 32; +static const int kEconomyAudioBitrateKbps = 16; + +// CallRateController, see callquality.h. +// +// A report with at least this much loss, or the audio this much later than +// usual, means the connection does not carry what is sent... +static const double kLossDecrease = 0.10; +static const int kDelayDecreaseMs = 300; +// ...and below this much loss and delay there is room for more. In between +// the bitrate is held where it is: a little loss on a wireless link is not +// always congestion, and going down for it would only cost picture. +static const double kLossIncrease = 0.02; +static const int kDelayIncreaseMs = 150; +// The steps. +static const double kLossDecreaseFactor = 0.75; +static const double kDelayDecreaseFactor = 0.85; +// Of what got through, with a queue building up: below it the queue drains. +static const double kDelayThroughputFactor = 0.9; +static const double kOutageDecreaseFactor = 0.5; +// Per second, so that how far the bitrate climbs does not depend on how +// often the peer reports. +static const double kIncreaseFactorPerSecond = 1.08; +static const int kMinIncreaseKbpsPerSecond = 16; +// No increase for this long after a decrease. +static const int kHoldAfterDecreaseMs = 4000; +// A whole period with nothing received although this many video packets went +// out is a connection that has stopped, not a quiet one. +static const int kOutagePackets = 10; +// The picture size steps down when the bitrate is below this much of what the +// current size wants, and up when it is at least this much of what the next +// size up wants - no sooner than kRungUpIntervalMs after the last step. +static const double kRungDownFactor = 0.5; +static const double kRungUpFactor = 0.75; +static const int kRungUpIntervalMs = 10000; + +static qint64 area(const QSize &s) +{ + return (qint64)s.width() * s.height(); +} + +static bool withinLimit(const QSize &size, const QSize &limit) +{ + return (limit.width() <= 0 || size.width() <= limit.width()) && + (limit.height() <= 0 || size.height() <= limit.height()); +} + +int callVideoBitrateKbps(const QSize &size, double frameRate, const QString &codec, bool hardware) +{ + const double pixelRate = (double)area(size) * qMax(1.0, frameRate); + double kbps = kBitrateScale * std::pow(pixelRate, kBitrateExponent); + + if (codec == QLatin1String("hevc")) + kbps *= kHevcBitrateFactor; + else if (codec == QLatin1String("vp9")) + kbps *= kVp9BitrateFactor; + + if (hardware) + kbps *= kHardwareBitrateFactor; + + // To 10 kbit/s, which is all the precision the figure has and reads + // better in the log and the settings dialog. + return qBound(kMinVideoBitrateKbps, qRound(kbps / 10.0) * 10, kMaxVideoBitrateKbps); +} + +QList<QSize> callVideoSizeLadder(const QSize &top) +{ + QList<QSize> ladder; + + if (top.width() <= 0 || top.height() <= 0) + return ladder; + + ladder << top; + + // By the shorter side, so that a portrait camera steps down the same way + // as a landscape one. + const int shortSide = qMin(top.width(), top.height()); + + for (unsigned int i = 0; i < sizeof(kLadderShortSides) / sizeof(kLadderShortSides[0]); i++) + { + if (kLadderShortSides[i] >= shortSide) + continue; + + const double f = (double)kLadderShortSides[i] / shortSide; + // Even, which 4:2:0 chroma needs. + ladder << QSize(qRound(top.width() * f / 2.0) * 2, qRound(top.height() * f / 2.0) * 2); + } + + return ladder; +} + +// Which codec and encoder a preset goes with. CallQualityEconomy wants the +// cheapest picture to produce - and to decode, on the peer's side, which H.264 +// is - from a GPU encoder; the other two the most picture per bit from one. +// Software encoding is always H.264, the one that runs in real time on a CPU +// at the sizes these presets ask for. +static void chooseEncoder(CallQualityPreset preset, const QList<CallHardwareEncoder> &hardware, + QString *codec, int *acceleration) +{ + static const char * const kQualityOrder[] = { "hevc", "vp9", "h264" }; + static const char * const kEconomyOrder[] = { "h264", "hevc", "vp9" }; + const char * const *order = preset == CallQualityEconomy ? kEconomyOrder : kQualityOrder; + + for (int c = 0; c < 3; c++) + { + for (int i = 0; i < hardware.size(); i++) + { + if (hardware.at(i).codec == QLatin1String(order[c])) + { + *codec = hardware.at(i).codec; + *acceleration = hardware.at(i).acceleration; + return; + } + } + } + + *codec = QStringLiteral("h264"); + *acceleration = 0; +} + +// 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) +{ + for (int i = 0; i < rates.size(); i++) + { + if (rates.at(i) <= maxRate && (double)area(size) * rates.at(i) <= pixelRateCap) + return rates.at(i); + } + + return 0; +} + +// The rate nearest to `wanted` from above, which the camera then has to drop +// the fewest frames from - or the highest it has, if every one is lower. +static int frameRateNear(const QList<int> &rates, int wanted) +{ + int best = 0; + + for (int i = 0; i < rates.size(); i++) + { + if (rates.at(i) >= wanted && (best == 0 || rates.at(i) < best)) + best = rates.at(i); + } + + if (best == 0 && !rates.isEmpty()) + best = rates.first(); + + return best > 0 ? best : wanted; +} + +CallVideoPlan callPlanVideo(CallQualityPreset preset, const QList<CallCameraSize> &cameraSizes, + const QSize &peerLimit, const QList<CallHardwareEncoder> &hardware) +{ + CallVideoPlan plan; + + chooseEncoder(preset, hardware, &plan.codec, &plan.acceleration); + + QList<CallCameraSize> camera = cameraSizes; + + if (camera.isEmpty()) + { + for (unsigned int i = 0; i < sizeof(kFallbackCameraSizes) / sizeof(kFallbackCameraSizes[0]); i++) + { + CallCameraSize s; + + s.size = kFallbackCameraSizes[i]; + s.frameRates << kFallbackFrameRate; + camera << s; + } + } + + // What the peer asked for rules out the rest, as long as something is + // left; when nothing is, the smallest the camera has - see 0x70 in the + // protocol specification. + QList<CallCameraSize> allowed; + + for (int i = 0; i < camera.size(); i++) + if (withinLimit(camera.at(i).size, peerLimit)) + allowed << camera.at(i); + + if (allowed.isEmpty()) + { + int smallest = 0; + + for (int i = 1; i < camera.size(); i++) + if (area(camera.at(i).size) < area(camera.at(smallest).size)) + smallest = i; + + allowed << camera.at(smallest); + } + + for (int i = 0; i < allowed.size(); i++) + if (allowed.at(i).frameRates.isEmpty()) + allowed[i].frameRates << kFallbackFrameRate; + + const bool hw = plan.acceleration != 0; + + if (preset == CallQualityEconomy) + { + int chosen = -1; + + for (int i = 0; i < allowed.size(); i++) + { + if (area(allowed.at(i).size) <= kEconomyMaxArea && + (chosen < 0 || area(allowed.at(i).size) > area(allowed.at(chosen).size))) + chosen = i; + } + + // A camera with nothing that small: capture at its smallest and scale + // down to the first size of the ladder that is. + if (chosen < 0) + { + chosen = 0; + + for (int i = 1; i < allowed.size(); i++) + if (area(allowed.at(i).size) < area(allowed.at(chosen).size)) + chosen = i; + } + + plan.captureSize = allowed.at(chosen).size; + plan.frameRate = frameRateNear(allowed.at(chosen).frameRates, kEconomyFrameRate); + plan.encodeSize = plan.captureSize; + + const QList<QSize> ladder = callVideoSizeLadder(plan.captureSize); + + for (int i = 0; i < ladder.size(); i++) + { + if (area(ladder.at(i)) <= kEconomyMaxArea) + { + plan.encodeSize = ladder.at(i); + break; + } + } + + plan.bitrateKbps = qMax(kMinVideoBitrateKbps, + qRound(callVideoBitrateKbps(plan.encodeSize, plan.frameRate, + plan.codec, hw) * kEconomyBitrateFactor / 10.0) * 10); + plan.maxBitrateKbps = plan.bitrateKbps; + + return plan; + } + + // CallQualityMax and CallQualityAdaptive: the largest picture that still + // moves smoothly, then the highest rate for it - what the encoder can keep + // up with deciding both. + const int maxRate = preset == CallQualityAdaptive ? kAdaptiveFrameRate : kMaxPresetFrameRate; + const double cap = hw ? kHardwarePixelRateCap : kSoftwarePixelRateCap; + int chosen = -1; + int chosenRate = 0; + + for (int i = 0; i < allowed.size(); i++) + { + const int rate = bestFrameRate(allowed.at(i).size, allowed.at(i).frameRates, maxRate, cap); + + if (rate <= 0) + continue; + + bool better = chosen < 0; + + if (!better) + { + const bool smooth = rate >= kSmoothFrameRate; + const bool chosenSmooth = chosenRate >= kSmoothFrameRate; + const qint64 a = area(allowed.at(i).size); + const qint64 chosenArea = area(allowed.at(chosen).size); + + if (smooth != chosenSmooth) + better = smooth; + else if (a != chosenArea) + better = a > chosenArea; + else + better = rate > chosenRate; + } + + if (better) + { + chosen = i; + chosenRate = rate; + } + } + + // Every size is beyond what the encoder keeps up with, at every rate the + // camera offers it at: the smallest, at its lowest rate. + if (chosen < 0) + { + chosen = 0; + + for (int i = 1; i < allowed.size(); i++) + if (area(allowed.at(i).size) < area(allowed.at(chosen).size)) + chosen = i; + + chosenRate = allowed.at(chosen).frameRates.last(); + } + + plan.captureSize = allowed.at(chosen).size; + plan.frameRate = chosenRate; + plan.maxBitrateKbps = callVideoBitrateKbps(plan.captureSize, plan.frameRate, plan.codec, hw); + + if (preset == CallQualityMax) + { + plan.encodeSize = plan.captureSize; + plan.bitrateKbps = plan.maxBitrateKbps; + return plan; + } + + plan.ladder = callVideoSizeLadder(plan.captureSize); + plan.encodeSize = plan.ladder.last(); + + for (int i = 0; i < plan.ladder.size(); i++) + { + const QSize &s = plan.ladder.at(i); + + if (qMin(s.width(), s.height()) <= kAdaptiveStartShortSide) + { + plan.encodeSize = s; + break; + } + } + + plan.bitrateKbps = qRound(callVideoBitrateKbps(plan.encodeSize, plan.frameRate, plan.codec, hw) + * kAdaptiveStartFactor); + + return plan; +} + +CallAudioPlan callPlanAudio(const CallSettings &cs) +{ + CallAudioPlan plan; + + plan.codec = QStringLiteral("opus"); + + switch (cs.qualityPreset) + { + case CallQualityMax: + plan.bitrateKbps = kMaxAudioBitrateKbps; + break; + + case CallQualityEconomy: + plan.bitrateKbps = kEconomyAudioBitrateKbps; + break; + + case CallQualityCustom: + plan.codec = cs.audioCodec; + plan.bitrateKbps = cs.audioBitrateKbps; + break; + + case CallQualityAdaptive: + default: + plan.bitrateKbps = kAdaptiveAudioBitrateKbps; + break; + } + + return plan; +} + +CallRateController::CallRateController() + : m_rung(0), m_bitrate(0.0), m_maxKbps(0), m_holdUntil(0), m_lastRungChange(0) +{ +} + +void CallRateController::start(const CallVideoPlan &plan, qint64 nowMs) +{ + m_ladder = plan.ladder; + m_rungKbps.clear(); + + for (int i = 0; i < m_ladder.size(); i++) + m_rungKbps << callVideoBitrateKbps(m_ladder.at(i), plan.frameRate, plan.codec, plan.acceleration != 0); + + m_rung = qMax(0, m_ladder.indexOf(plan.encodeSize)); + m_bitrate = plan.bitrateKbps; + m_maxKbps = plan.maxBitrateKbps; + m_holdUntil = nowMs; + m_lastRungChange = nowMs; + m_reason.clear(); +} + +bool CallRateController::update(const CallReceptionReport &report, int videoPacketsSent, qint64 nowMs) +{ + if (m_ladder.isEmpty()) + return false; + + const int oldKbps = bitrateKbps(); + const int oldRung = m_rung; + + const int received = report.audioReceived + report.videoReceived; + // The worse of the two streams rather than both together: there are + // several times as many audio packets as video ones at a low bitrate, and + // counted together they would hide a video stream losing a third of its + // packets. + const int audioExpected = report.audioReceived + report.audioLost; + const int videoExpected = report.videoReceived + report.videoLost; + const double loss = qMax(audioExpected > 0 ? (double)report.audioLost / audioExpected : 0.0, + videoExpected > 0 ? (double)report.videoLost / videoExpected : 0.0); + const int delay = qMax(0, report.queuingDelayMs); + // bits per millisecond are kbit/s + const double throughputKbps = report.periodMs > 0 ? report.videoOctets * 8.0 / report.periodMs : 0.0; + const bool outage = received == 0 && videoPacketsSent >= kOutagePackets; + + if (outage) + { + m_bitrate *= kOutageDecreaseFactor; + m_reason = QString("nothing received of %1 video packets").arg(videoPacketsSent); + } + else if (loss >= kLossDecrease) + { + m_bitrate *= kLossDecreaseFactor; + m_reason = QString("%1% loss").arg(loss * 100.0, 0, 'f', 1); + } + else if (delay >= kDelayDecreaseMs) + { + m_bitrate *= kDelayDecreaseFactor; + + if (throughputKbps > 0.0) + m_bitrate = qMin(m_bitrate, throughputKbps * kDelayThroughputFactor); + + m_reason = QString("%1 ms queuing delay, %2 kbit/s got through") + .arg(delay).arg(qRound(throughputKbps)); + } + else if (loss < kLossIncrease && delay < kDelayIncreaseMs && received > 0 && + videoPacketsSent > 0 && nowMs >= m_holdUntil) + { + const double seconds = qBound(0.1, report.periodMs / 1000.0, 10.0); + + m_bitrate = qMin((double)m_maxKbps, + qMax(m_bitrate * std::pow(kIncreaseFactorPerSecond, seconds), + m_bitrate + kMinIncreaseKbpsPerSecond * seconds)); + m_reason = QString("%1% loss, %2 ms queuing delay").arg(loss * 100.0, 0, 'f', 1).arg(delay); + } + + if (m_bitrate < oldKbps) + m_holdUntil = nowMs + kHoldAfterDecreaseMs; + + m_bitrate = qBound((double)kMinVideoBitrateKbps, m_bitrate, (double)m_maxKbps); + + // Down as far as the bitrate says, at once: holding a size the bitrate + // cannot carry only makes every frame of it look bad. + while (m_rung + 1 < m_ladder.size() && m_bitrate < m_rungKbps.at(m_rung) * kRungDownFactor) + m_rung++; + + // Up one step at a time, spaced out. + if (m_rung == oldRung && m_rung > 0 && nowMs - m_lastRungChange >= kRungUpIntervalMs && + m_bitrate >= m_rungKbps.at(m_rung - 1) * kRungUpFactor) + m_rung--; + + if (m_rung != oldRung) + m_lastRungChange = nowMs; + + return bitrateKbps() != oldKbps || m_rung != oldRung; +} diff --git a/pica-client/callquality.h b/pica-client/callquality.h new file mode 100644 index 0000000..a147433 --- /dev/null +++ b/pica-client/callquality.h @@ -0,0 +1,184 @@ +/* + (c) Copyright 2012 - 2026 Anton Sviridenko + https://picapica.im + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, version 3. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. +*/ +#ifndef CALLQUALITY_H +#define CALLQUALITY_H + +#include "callsettings.h" +#include <QList> +#include <QMetaType> +#include <QSize> +#include <QString> + +// What the call quality presets other than CallQualityCustom turn into: the +// codec, hardware encoder, picture size, frame rate and bitrate a call starts +// with, and for CallQualityAdaptive how those follow the connection during the +// 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 +// tests/test_callquality. + +// One hardware encoder that opened and encoded a frame on this machine, as +// found by VideoDevice::ProbeHardwareEncoders(). +struct CallHardwareEncoder +{ + // FFmpeg codec name, one of kCallVideoCodecs. + QString codec; + // The flag that reaches it. + VideoAcceleration acceleration; + // FFmpeg encoder name, e.g. "h264_vaapi", for showing to the user. + QString encoder; +}; + +// One picture size a camera offers and the frame rates it offers it at - the +// part of VideoCaptureFormat the planning needs. +struct CallCameraSize +{ + QSize size; + // Highest first; empty when the camera would not say. + QList<int> frameRates; +}; + +struct CallVideoPlan +{ + // FFmpeg codec name. + QString codec; + // The one VideoAcceleration flag to encode through, 0 for software. + int acceleration; + + // What the camera is asked for. + QSize captureSize; + int frameRate; + + // What gets encoded and sent at the start of the call: captureSize, or the + // captured picture scaled down. + QSize encodeSize; + int bitrateKbps; + + // CallQualityAdaptive: the bitrate follows the peer's 0x79 reports, see + // CallRateController, and the picture is scaled to one of these sizes, + // largest first and starting with captureSize, as the bitrate goes down + // and up. Empty for the other presets, whose plan holds for the whole + // call. + QList<QSize> ladder; + // The most the bitrate goes up to: what CallQualityMax would use for + // captureSize. + int maxBitrateKbps; + + bool adaptive() const { return !ladder.isEmpty(); } +}; + +struct CallAudioPlan +{ + // FFmpeg codec name. + QString codec; + // Only means something for a codec callAudioBitrateAdjustable() is true + // for. + int bitrateKbps; +}; + +// The bitrate that gives a picture of this size and rate good quality in the +// given codec, without spending bits on detail a call does not show - the +// target of CallQualityMax, and the ceiling CallQualityAdaptive climbs back +// to. Grows slower than the pixel rate, since a larger or faster picture has +// more in it that can be predicted. hardware is for a GPU encoder, which +// needs somewhat more than a software one for the same picture. +int callVideoBitrateKbps(const QSize &size, double frameRate, const QString &codec, bool hardware); + +// The sizes CallQualityAdaptive steps between for a picture captured at top: +// top itself, then the common sizes with a shorter side of 1440, 1080, 720, +// 540, 360, 270 and 180 that are smaller than it, at top's aspect ratio. +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. +// +// 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 audio codec and bitrate a call is made with: the stored ones for +// CallQualityCustom, the preset's otherwise. +CallAudioPlan callPlanAudio(const CallSettings &cs); + +// One 0x79 message: what the peer received of our media over one period, see +// doc/protocol-specification.txt. +struct CallReceptionReport +{ + int periodMs; + int audioReceived; + int audioLost; + int videoReceived; + int videoLost; + quint32 audioOctets; + quint32 videoOctets; + // How much later than usual our audio has been arriving, -1 when the peer + // received none to tell by. + int queuingDelayMs; +}; + +Q_DECLARE_METATYPE(CallReceptionReport) + +// Follows the connection for CallQualityAdaptive: takes the peer's reception +// reports and works out the bitrate and picture size to encode at. +// +// The bitrate goes down when packets get lost or start queueing up on the way +// - multiplicatively, and to below what actually got through when it is a +// queue - and creeps back up a few percent per report while the connection +// keeps up, to the plan's maximum. The picture size follows the bitrate: a +// step down once the bitrate is too low for the current size to look good, +// and a step up once it is well into what the next size up needs. The two +// thresholds are far enough apart that the size does not flap, and steps up +// are spaced out on top of that, each one costing a keyframe. +class CallRateController +{ +public: + CallRateController(); + + // Begins at plan.encodeSize and plan.bitrateKbps. + void start(const CallVideoPlan &plan, qint64 nowMs); + + // One report from the peer. videoPacketsSent is how many video packets + // went out since the previous one, which tells a connection that lets + // nothing through from a camera that stopped. True when bitrateKbps() or + // size() changed. + bool update(const CallReceptionReport &report, int videoPacketsSent, qint64 nowMs); + + int bitrateKbps() const { return qRound(m_bitrate); } + QSize size() const { return m_ladder.isEmpty() ? QSize() : m_ladder.at(m_rung); } + + // Why the last change was made, for the log. + QString reason() const { return m_reason; } + +private: + QList<QSize> m_ladder; + // callVideoBitrateKbps() for each size of m_ladder. + QList<int> m_rungKbps; + int m_rung; + double m_bitrate; + int m_maxKbps; + // No increase before this, after a decrease: the reports of the next + // second or two still describe the time before it took effect. + qint64 m_holdUntil; + qint64 m_lastRungChange; + QString m_reason; +}; + +#endif // CALLQUALITY_H diff --git a/pica-client/callsettings.cpp b/pica-client/callsettings.cpp index 10529c1..630f8e3 100644 --- a/pica-client/callsettings.cpp +++ b/pica-client/callsettings.cpp @@ -164,7 +164,19 @@ CallSettings CallSettings::load() Settings st(config_dbname); CallSettings cs; - cs.videoCodec = st.loadValue("call.video_codec", QLatin1String(kCallVideoCodecs[0].name)).toString(); + // Adaptive when never set, or set to something this build does not know. + const QString preset = st.loadValue("call.quality_preset", "adaptive").toString(); + + if (preset == QLatin1String("max")) + cs.qualityPreset = CallQualityMax; + else if (preset == QLatin1String("economy")) + cs.qualityPreset = CallQualityEconomy; + else if (preset == QLatin1String("custom")) + cs.qualityPreset = CallQualityCustom; + else + cs.qualityPreset = CallQualityAdaptive; + + cs.videoCodec =st.loadValue("call.video_codec", QLatin1String(kCallVideoCodecs[0].name)).toString(); cs.audioCodec = st.loadValue("call.audio_codec", QLatin1String(kCallAudioCodecs[0].name)).toString(); cs.videoBitrateKbps = st.loadValue("call.video_bitrate_kbps", kDefaultVideoBitrateKbps).toInt(); diff --git a/pica-client/callsettings.h b/pica-client/callsettings.h index fab19c3..38f8681 100644 --- a/pica-client/callsettings.h +++ b/pica-client/callsettings.h @@ -102,8 +102,34 @@ enum IncomingVideoLimit extern const QSize kIncomingVideoLimitSizes[]; extern const int kIncomingVideoLimitSizeCount; +// "Call quality" on the "Presets" tab: what decides the codecs, bitrates, +// 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. +enum CallQualityPreset +{ + // The largest picture and frame rate there is, at the bitrate it needs. + CallQualityMax, + // Starts in the middle and follows the peer's 0x79 reception reports: + // bitrate and picture size go down on loss or a growing delay, and back + // up to what CallQualityMax would use while the connection keeps up. + CallQualityAdaptive, + // Small picture, low frame rate and bitrate, the hardware encoder that + // costs the CPU least. + CallQualityEconomy, + // The codec, bitrate, picture size, frame rate and acceleration settings + // of the "Call Settings" and "Video Devices" tabs, as they are. + CallQualityCustom +}; + struct CallSettings { + // Everything below except the incoming video limit and the decoding + // acceleration only applies as it stands to CallQualityCustom; the other + // presets put values of their own in place of it at the start of a call. + CallQualityPreset qualityPreset; + // FFmpeg codec names, e.g. "h264" and "opus". QString videoCodec; QString audioCodec; diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp index 1698a97..b0eb6a5 100644 --- a/pica-client/dialogs/settingsdialog.cpp +++ b/pica-client/dialogs/settingsdialog.cpp @@ -20,6 +20,7 @@ #include "../audiodevice.h" #include "../videodevice.h" #include "../callsettings.h" +#include "../callquality.h" #include "../directc2csettings.h" #include "../../PICA_netconf.h" #include "../../PICA_proto.h" @@ -108,6 +109,11 @@ SettingsDialog::SettingsDialog(QWidget *parent) : videoRes = nullptr; videoFps = nullptr; + // Refreshed along with the camera's formats, which are filled before the + // Presets tab is built. + lbQualitySummary = nullptr; + hwProbeRequested = 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, // but the preview is built - and the layout that can resize it applied - @@ -129,6 +135,7 @@ SettingsDialog::SettingsDialog(QWidget *parent) : QWidget* audiodevtab = new QWidget(0); QWidget* videodevtab = new QWidget(0); QWidget* calltab = new QWidget(0); + QWidget* presetstab = new QWidget(0); QVBoxLayout *directc2cLayout = new QVBoxLayout(); QVBoxLayout *multiloginlayout = new QVBoxLayout(); @@ -553,8 +560,14 @@ 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->setWordWrap(true); + videodevLayout->addWidget(videoDev); videodevLayout->addWidget(videoDevRefresh); + videodevLayout->addWidget(lbVideoPresetHint); videodevLayout->addLayout(videoFormatLayout); videodevLayout->addWidget(cbPreferCompressed); #ifdef HAVE_VAAPI @@ -723,13 +736,75 @@ SettingsDialog::SettingsDialog(QWidget *parent) : incomingVideoLayout->addLayout(incomingVideoCustomLayout); gbIncomingVideo->setLayout(incomingVideoLayout); - callLayout->addLayout(callFormLayout); + // A widget of its own so that a preset can disable the lot at once. + callCustomBox = new QWidget(this); + callFormLayout->setContentsMargins(0, 0, 0, 0); + callCustomBox->setLayout(callFormLayout); + + lbCallPresetHint = new QLabel(tr("The codecs and bitrates below are only used with the \"Custom\" " + "call quality preset - see the Presets tab."), this); + lbCallPresetHint->setWordWrap(true); + + callLayout->addWidget(lbCallPresetHint); + callLayout->addWidget(callCustomBox); callLayout->addWidget(lbCallHint); callLayout->addWidget(gbIncomingVideo); callLayout->addStretch(1); calltab->setLayout(callLayout); +//Presets + // Several settings at once, all over the other tabs. Parented to the group + // box for the same reason as the echo cancellation buttons. + QGroupBox *gbQuality = new QGroupBox(tr("Call quality"), this); + QVBoxLayout *qualityLayout = new QVBoxLayout(); + const int radioIndent = style()->pixelMetric(QStyle::PM_ExclusiveIndicatorWidth) + + style()->pixelMetric(QStyle::PM_RadioButtonLabelSpacing); + + // Each choice with what it does underneath, indented under its label. + auto addQualityChoice = [&](const QString &label, const QString &description) { + QRadioButton *rb = new QRadioButton(label, gbQuality); + QLabel *lb = new QLabel(description, gbQuality); + + lb->setWordWrap(true); + lb->setContentsMargins(radioIndent, 0, 0, 0); + lb->setEnabled(false); + qualityLayout->addWidget(rb); + qualityLayout->addWidget(lb); + connect(rb, SIGNAL(toggled(bool)), this, SLOT(callQualityChanged())); + + return rb; + }; + + rbQualityMax = addQualityChoice(tr("Max quality"), + tr("The largest picture and the highest frame rate the camera offers, within what the " + "other side asks for, at the bitrate that picture needs.")); + rbQualityAdaptive = addQualityChoice(tr("Adaptive"), + tr("Starts at up to 720p and follows the connection: the other side reports what it " + "receives, and the picture size and bitrate go down when packets get lost or delayed, " + "and back up as far as Max quality would go while the connection keeps up.")); + rbQualityEconomy = addQualityChoice(tr("Economy"), + tr("A small picture at a low frame rate and bitrate, encoded in H.264 on the GPU where " + "possible: the least CPU, battery and bandwidth.")); + rbQualityCustom = addQualityChoice(tr("Custom"), + tr("The codecs, bitrates, picture size, frame rate and hardware encoding set on the Call " + "Settings and Video Devices tabs.")); + + gbQuality->setLayout(qualityLayout); + + lbQualitySummary = new QLabel(this); + lbQualitySummary->setWordWrap(true); + lbQualitySummary->setTextInteractionFlags(Qt::TextSelectableByMouse); + + connect(testCam, SIGNAL(hardwareEncodersProbed()), this, SLOT(hardwareEncodersProbed())); + + QVBoxLayout *presetsLayout = new QVBoxLayout(); + presetsLayout->addWidget(gbQuality); + presetsLayout->addWidget(lbQualitySummary); + presetsLayout->addStretch(1); + presetstab->setLayout(presetsLayout); + + tabW->addTab(presetstab, tr("Presets")); tabW->addTab(directc2ctab, tr("Direct Connections")); tabW->addTab(multilogintab, tr("Multiple Logins")); tabW->addTab(audiodevtab, tr("Audio Devices")); @@ -869,9 +944,17 @@ void SettingsDialog::toggleAudioTest() // The codec selected on the "Call Settings" tab, at the rate a call with // it would run at - same as the video test, this exercises what the // current selections do rather than a fixed pipeline of its own. - const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + // Or the preset's, with one selected. + CallSettings cs; + + cs.qualityPreset = selectedQualityPreset(); + cs.audioCodec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); + cs.audioBitrateKbps = callAudioBitrate->value(); + + const CallAudioPlan audio = callPlanAudio(cs); + const QString codec = audio.codec; const int rate = callAudioSampleRate(codec); - const int bitrate = callAudioBitrateAdjustable(codec) ? callAudioBitrate->value() * 1000 : 0; + const int bitrate = callAudioBitrateAdjustable(codec) ? audio.bitrateKbps * 1000 : 0; testMic->openSession(testSessionId(), testSessionId()); QMetaObject::invokeMethod(testMic, "configureCapture", Qt::QueuedConnection, @@ -1105,6 +1188,10 @@ void SettingsDialog::toggleVideoTest() Q_ARG(int, callVideoBitrate->value() * 1000), Q_ARG(int, selectedVideoEncodingAcceleration()), Q_ARG(QByteArray, testSessionId()), Q_ARG(QByteArray, testSessionId())); + // 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())); QMetaObject::invokeMethod(testCam, "Capture", Qt::QueuedConnection); // The decoder is only started once the camera has settled on a format, @@ -1531,6 +1618,9 @@ void SettingsDialog::fillVideoResolutions() videoRes->blockSignals(false); fillVideoFrameRates(); + + // What a preset makes of a camera depends on what the camera offers. + updateCallQualitySummary(); } void SettingsDialog::fillVideoFrameRates() @@ -1663,6 +1753,136 @@ int SettingsDialog::selectedVideoDecodingAcceleration() const return flags; } +CallQualityPreset SettingsDialog::selectedQualityPreset() const +{ + if (rbQualityMax->isChecked()) + return CallQualityMax; + if (rbQualityEconomy->isChecked()) + return CallQualityEconomy; + if (rbQualityCustom->isChecked()) + return CallQualityCustom; + + return CallQualityAdaptive; +} + +void SettingsDialog::callQualityChanged() +{ + // Each button's toggled() lands here, the one going off as well as the + // one going on; in between, none is checked. + if (!rbQualityMax->isChecked() && !rbQualityAdaptive->isChecked() && + !rbQualityEconomy->isChecked() && !rbQualityCustom->isChecked()) + return; + + updateCallQualityWidgets(); + updateCallQualitySummary(); +} + +void SettingsDialog::updateCallQualityWidgets() +{ + const bool custom = selectedQualityPreset() == CallQualityCustom; + + callCustomBox->setEnabled(custom); + videoRes->setEnabled(custom); + 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 + + lbCallPresetHint->setVisible(!custom); + lbVideoPresetHint->setVisible(!custom); +} + +static QString videoCodecDisplayName(const QString &codec) +{ + for (int i = 0; i < kCallVideoCodecCount; i++) + if (codec == QLatin1String(kCallVideoCodecs[i].name)) + return QLatin1String(kCallVideoCodecs[i].displayName); + + return codec; +} + +void SettingsDialog::updateCallQualitySummary() +{ + if (!lbQualitySummary) + return; + + const CallQualityPreset preset = selectedQualityPreset(); + QList<CallHardwareEncoder> hardware; + + if (!VideoDevice::HardwareEncodersProbed(&hardware)) + { + lbQualitySummary->setText(tr("Finding out which hardware video encoders work on this computer...")); + + // 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) + { + hwProbeRequested = true; + QMetaObject::invokeMethod(testCam, "probeHardwareEncoders", Qt::QueuedConnection); + } + + 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(", "))); + + if (preset != CallQualityCustom) + { + const CallVideoPlan video = callPlanVideo(preset, VideoDevice::CallCameraSizes(videoFormats), + QSize(0, 0), hardware); + CallSettings cs; + + cs.qualityPreset = preset; + + const CallAudioPlan audio = callPlanAudio(cs); + + text += QLatin1String("\n\n"); + text += tr("With the selected camera a call starts with %1 video encoded on the %2, %3x%4 " + "at %5 fps and %6 kbit/s, and Opus audio at %7 kbit/s.") + .arg(videoCodecDisplayName(video.codec), + video.acceleration ? tr("GPU") : tr("CPU")) + .arg(video.encodeSize.width()).arg(video.encodeSize.height()) + .arg(video.frameRate).arg(video.bitrateKbps).arg(audio.bitrateKbps); + + if (video.adaptive()) + text += QLatin1Char(' ') + tr("It goes as high as %1x%2 at %3 kbit/s and as low as %4x%5, " + "as the connection allows.") + .arg(video.captureSize.width()).arg(video.captureSize.height()) + .arg(video.maxBitrateKbps) + .arg(video.ladder.last().width()).arg(video.ladder.last().height()); + + text += QLatin1Char(' ') + tr("The other side can ask for a smaller picture."); + } + + lbQualitySummary->setText(text); +} + +void SettingsDialog::hardwareEncodersProbed() +{ + updateCallQualitySummary(); +} + void SettingsDialog::callAudioCodecChanged() { const QString codec = callAudioCodec->itemData(callAudioCodec->currentIndex()).toString(); @@ -1671,7 +1891,7 @@ void SettingsDialog::callAudioCodecChanged() { // Coming back from a fixed rate codec, whose rate is showing in the // box; the user's own choice is in audioBitrateKbps. - if (!callAudioBitrate->isEnabled()) + if (!callAudioBitrate->isEnabledTo(callCustomBox)) { callAudioBitrate->setEnabled(true); callAudioBitrate->setValue(audioBitrateKbps); @@ -1681,7 +1901,7 @@ void SettingsDialog::callAudioCodecChanged() return; } - if (callAudioBitrate->isEnabled()) + if (callAudioBitrate->isEnabledTo(callCustomBox)) audioBitrateKbps = callAudioBitrate->value(); // Show what the codec will actually run at rather than leaving a number @@ -2174,6 +2394,23 @@ void SettingsDialog::loadSettings() // actually changes - and the stored codec is often the one already showing. callAudioCodecChanged(); + switch (cs.qualityPreset) + { + case CallQualityMax: + rbQualityMax->setChecked(true); + break; + case CallQualityEconomy: + rbQualityEconomy->setChecked(true); + break; + case CallQualityCustom: + rbQualityCustom->setChecked(true); + break; + case CallQualityAdaptive: + default: + rbQualityAdaptive->setChecked(true); + break; + } + if (cs.incomingVideoLimit == IncomingVideoLimitCustom) rbIncomingVideoCustom->setChecked(true); else @@ -2237,6 +2474,9 @@ void SettingsDialog::loadSettings() int audioRingDevItem = audioRingDev->findData(audioRingDevVal); if (audioRingDevItem >= 0) audioRingDev->setCurrentIndex(audioRingDevItem); + + // Explicitly, for the same reason as callAudioCodecChanged() above. + callQualityChanged(); } void SettingsDialog::storeSettings() @@ -2294,6 +2534,9 @@ void SettingsDialog::storeSettings() st.storeValue("video.capture_framerate", QString::number(selectedVideoFrameRate())); st.storeValue("video.prefer_compressed", cbPreferCompressed->isChecked() ? "1" : "0"); + static const char * const kPresetKeys[] = { "max", "adaptive", "economy", "custom" }; + st.storeValue("call.quality_preset", kPresetKeys[selectedQualityPreset()]); + st.storeValue("call.video_codec", callVideoCodec->itemData(callVideoCodec->currentIndex()).toString()); st.storeValue("call.audio_codec", callAudioCodec->itemData(callAudioCodec->currentIndex()).toString()); st.storeValue("call.video_bitrate_kbps", QString::number(callVideoBitrate->value())); @@ -2301,7 +2544,7 @@ void SettingsDialog::storeSettings() // The box shows a fixed rate codec's own bitrate while such a codec is // selected; what gets stored is the user's choice either way, so that // switching back to Opus finds it again on the next visit. - if (callAudioBitrate->isEnabled()) + if (callAudioBitrate->isEnabledTo(callCustomBox)) audioBitrateKbps = callAudioBitrate->value(); st.storeValue("call.audio_bitrate_kbps", QString::number(audioBitrateKbps)); diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h index d5b624c..3525cbf 100644 --- a/pica-client/dialogs/settingsdialog.h +++ b/pica-client/dialogs/settingsdialog.h @@ -96,6 +96,27 @@ private: // told the user why, if it cannot be. bool validateAddrTable(); + // "Call quality" on the "Presets" tab, see CallQualityPreset. + QRadioButton *rbQualityMax; + QRadioButton *rbQualityAdaptive; + QRadioButton *rbQualityEconomy; + QRadioButton *rbQualityCustom; + // What the selected preset comes to on this machine with the selected + // 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; + // Say on the tabs the custom settings live on that a preset is deciding + // them instead. + QLabel *lbCallPresetHint; + QLabel *lbVideoPresetHint; + + CallQualityPreset selectedQualityPreset() const; + // Enables what only the Custom preset uses, and disables it otherwise. + void updateCallQualityWidgets(); + void updateCallQualitySummary(); + QRadioButton *rbMLPProhibit; QRadioButton *rbMLPReplace; QRadioButton *rbMLPAllowMultiple; @@ -147,6 +168,10 @@ private: QComboBox *callAudioCodec; QSpinBox *callVideoBitrate; QSpinBox *callAudioBitrate; + // Holds the four above, and is disabled with a preset other than Custom. + // Whether callAudioBitrate is disabled on its own account - a fixed rate + // codec - is told by isEnabledTo(callCustomBox), see audioBitrateKbps. + QWidget *callCustomBox; // "Maximum incoming video resolution": the recommended resolution a call // sends to the peer in 0x70/0x71, see IncomingVideoLimit. The combo box @@ -355,6 +380,8 @@ private slots: // Greys out the audio bitrate box for a codec whose bitrate is not ours to // choose - see audioBitrateKbps. void callAudioCodecChanged(); + void callQualityChanged(); + 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. void audioDriverChanged(int index); diff --git a/pica-client/skynet.cpp b/pica-client/skynet.cpp index 2fbe21d..c30cbf3 100644 --- a/pica-client/skynet.cpp +++ b/pica-client/skynet.cpp @@ -75,6 +75,11 @@ SkyNet::SkyNet() }; + cbs.call_reception_report_cb = call_reception_report_cb; + + // emitted from this object's thread, delivered on the GUI thread + qRegisterMetaType<CallReceptionReport>("CallReceptionReport"); + PICA_client_init(&cbs); this->active_nodelink = NULL; @@ -1483,6 +1488,11 @@ void SkyNet::emit_CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, emit CallMediaTransportChanged(peer_id, direct_udp, ciphersuitename, max_payload); } +void SkyNet::emit_CallReceptionReported(QByteArray peer_id, CallReceptionReport report) +{ + emit CallReceptionReported(peer_id, report); +} + //callbacks void SkyNet::newmsg_cb(const unsigned char *peer_id, const char *msgbuf, unsigned int nb, int type) @@ -1761,3 +1771,20 @@ void SkyNet::call_media_transport_cb(const unsigned char *peer_id, int transport ciphersuitename ? QString::fromLatin1(ciphersuitename) : QString(), max_payload); } + +void SkyNet::call_reception_report_cb(const unsigned char *peer_id, const struct PICA_call_reception_report *report) +{ + CallReceptionReport r; + + r.periodMs = report->period; + r.audioReceived = report->audio_received; + r.audioLost = report->audio_lost; + r.videoReceived = report->video_received; + r.videoLost = report->video_lost; + r.audioOctets = report->audio_octets; + r.videoOctets = report->video_octets; + r.queuingDelayMs = report->queuing_delay == PICA_PROTO_CALL_RECEPTION_REPORT_DELAY_UNKNOWN + ? -1 : report->queuing_delay; + + skynet->emit_CallReceptionReported(QByteArray((const char*)peer_id, PICA_ID_SIZE), r); +} diff --git a/pica-client/skynet.h b/pica-client/skynet.h index b766d28..86d9d54 100644 --- a/pica-client/skynet.h +++ b/pica-client/skynet.h @@ -24,6 +24,7 @@ #include "accounts.h" #include "directlistener.h" #include "directc2csettings.h" +#include "callquality.h" #include <QObject> #include <QThread> #include <QMap> @@ -114,6 +115,8 @@ signals: * data one media packet can carry from now on. */ void CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); + // The peer's 0x79: what it received of the media we sent it. + void CallReceptionReported(QByteArray peer_id, CallReceptionReport report); private: // Constructed in init(), once this SkyNet instance is running on its // own network thread and that thread's dedicated QSqlDatabase @@ -223,6 +226,7 @@ private: void emit_IncomingVideoPacket(QByteArray peer_id, quint16 seq_num, quint32 timestamp, QByteArray data); void emit_CallMediaTransportChanged(QByteArray peer_id, bool direct_udp, QString ciphersuitename, quint32 max_payload); + void emit_CallReceptionReported(QByteArray peer_id, CallReceptionReport report); static void newmsg_cb(const unsigned char *peer_id, const char* msgbuf, unsigned int nb, int type); @@ -284,6 +288,8 @@ private: static void call_media_transport_cb(const unsigned char *peer_id, int transport, const char *ciphersuitename, unsigned int max_payload); + static void call_reception_report_cb(const unsigned char *peer_id, const struct PICA_call_reception_report *report); + bool online() const; // Closes a listener that dcs no longer want and, with start set, begins // setting up the one they do. Returns whether a listener is being set diff --git a/pica-client/videodevice.cpp b/pica-client/videodevice.cpp index f7d080c..ab6f08e 100644 --- a/pica-client/videodevice.cpp +++ b/pica-client/videodevice.cpp @@ -25,6 +25,7 @@ #include <QFile> #include <QDebug> #include <QMutexLocker> +#include <QElapsedTimer> #include <QMap> #include <QPair> #include <cstring> @@ -731,7 +732,8 @@ VideoDevice::VideoDevice(QObject *parent) : QObject(parent), m_width(kDefaultCaptureWidth), m_height(kDefaultCaptureHeight), m_maxWidth(0), m_maxHeight(0), m_frameRate(kDefaultCaptureFrameRate), m_bitrate(kDefaultVideoBitrateKbps * 1000), - m_preferCompressed(false), + m_preferCompressed(false), m_preset(CallQualityCustom), m_planned(false), + m_fragmentsSent(0), m_acceleration(0), m_useVaapiRender(false), m_reconfigure(0), m_pendingWidth(0), m_pendingHeight(0), m_pendingAcceleration(0), m_pendingUseVaapiRender(false), @@ -799,6 +801,10 @@ void VideoDevice::configureCapture(QString deviceName, int width, int height, in m_bitrate = bitrate > 0 ? bitrate : kDefaultVideoBitrateKbps * 1000; m_preferCompressed = preferCompressed; m_acceleration = acceleration; + m_preset = CallQualityCustom; + + // Reports about the previous call's video say nothing about this one. + takeReports(); } void VideoDevice::limitCaptureSize(int width, int height) @@ -807,6 +813,36 @@ void VideoDevice::limitCaptureSize(int width, int height) m_maxHeight = qMax(0, height); } +void VideoDevice::setQualityPreset(int preset) +{ + m_preset = preset; +} + +void VideoDevice::reportReception(const CallReceptionReport &report) +{ + QMutexLocker locker(&m_reportMutex); + + // A capture loop that is not taking them - another preset, or no camera - + // would otherwise collect them for the whole call. + if (m_reports.size() < 16) + m_reports.append(report); +} + +QList<CallReceptionReport> VideoDevice::takeReports() +{ + QMutexLocker locker(&m_reportMutex); + QList<CallReceptionReport> reports = m_reports; + + m_reports.clear(); + return reports; +} + +void VideoDevice::probeHardwareEncoders() +{ + ProbeHardwareEncoders(); + emit hardwareEncodersProbed(); +} + void VideoDevice::configurePlayback(QString codec, int width, int height, int acceleration, bool useVaapiRender, QByteArray caller_id, QByteArray callee_id) @@ -1271,6 +1307,39 @@ void VideoDevice::Capture() const QList<VideoCaptureFormat> formats = VideoDevice::CaptureFormats(m_deviceName); + // A preset decides everything configureCapture() was given about the + // picture, out of what this camera, the peer and the GPU allow. Within + // the peer's limit already, so the step down below leaves it as it is. + m_planned = m_preset != CallQualityCustom; + m_fragmentsSent = 0; + takeReports(); + + if (m_planned) + { + m_plan = callPlanVideo((CallQualityPreset)m_preset, CallCameraSizes(formats), + QSize(m_maxWidth, m_maxHeight), ProbeHardwareEncoders()); + + m_codec = m_plan.codec; + m_acceleration = m_plan.acceleration; + m_width = m_plan.captureSize.width(); + m_height = m_plan.captureSize.height(); + m_frameRate = m_plan.frameRate; + m_bitrate = m_plan.bitrateKbps * 1000; + m_preferCompressed = false; + + qDebug() << QString("Call quality preset %1: %2 %3, camera at %4x%5 @%6, encoding %7x%8 at %9 kbit/s%10") + .arg(m_preset) + .arg(m_plan.codec, + m_plan.acceleration ? QStringLiteral("on the GPU") : QStringLiteral("on the CPU")) + .arg(m_width).arg(m_height).arg(m_frameRate) + .arg(m_plan.encodeSize.width()).arg(m_plan.encodeSize.height()) + .arg(m_plan.bitrateKbps) + .arg(m_plan.adaptive() + ? QString(", adapting up to %1x%2 at %3 kbit/s") + .arg(m_width).arg(m_height).arg(m_plan.maxBitrateKbps) + : QString()); + } + // Brought down to what the peer wants to receive before anything is asked // of the camera, so that the size below is the one every attempt is made // at and the one the encoder is opened for. @@ -1415,6 +1484,7 @@ void VideoDevice::emitFragments(const unsigned char *data, int size) emit packetReady(QByteArray((const char *)data + offset, chunk), isLast); offset += chunk; + m_fragmentsSent++; } } @@ -1650,50 +1720,56 @@ static AVCodecContext *openMediaFoundationEncoder(const AVCodec *enc, int width, } #endif -void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) +// An opened video encoder, as openVideoEncoder() hands it back. +struct VideoEncoderSession { - const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); + AVCodecContext *ctx; + // The surface pool it draws from, for an encoder that takes GPU surfaces. + AVBufferRef *hwFrames; + bool hardware; + // FFmpeg encoder name, e.g. "h264_vaapi" or "libx264". + QString name; +}; - // Which encoder produces the configured codec. Looked up once: the GPU - // attempt and the software fallback below are two encoders for the same - // codec, so the peer is told the same thing either way. - const int encIdx = videoEncoderIndex(m_codec); +static void closeVideoEncoder(VideoEncoderSession *s) +{ + if (s->ctx) + avcodec_free_context(&s->ctx); + if (s->hwFrames) + av_buffer_unref(&s->hwFrames); - // Two seconds between keyframes. A receiver that joins late or loses a - // 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); + s->ctx = nullptr; + s->hwFrames = nullptr; +} +// Opens an encoder for the codec at kVideoEncoders[encIdx]: through the GPU +// paths acceleration asks for, in the order VAAPI, Direct3D 12, Media +// Foundation, and in software when none of them opens and allowSoftware is +// set. Anything that goes wrong on the way to a GPU encoder - no such encoder +// built into FFmpeg, no usable device, no surface pool, the encoder refusing +// to open - is logged and only moves on to the next. +// +// False with *error set when nothing opened. +static bool openVideoEncoder(int encIdx, int acceleration, int width, int height, + AVRational frameRate, int64_t bitrate, int gopSize, + bool allowSoftware, VideoEncoderSession *out, QString *error) +{ int ret; - - // The camera hands us either raw frames or a compressed stream that is - // not being forwarded as-is; either way it goes through a decoder here to - // get raw pictures for the encoder. - const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id); - AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr; - if (!cam_dec || !dec_ctx || - avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || - avcodec_open2(dec_ctx, cam_dec, nullptr) < 0) - { - QString msg = "Could not open camera format decoder"; - qWarning() << msg; - emit errorOccurred(msg); - if (dec_ctx) avcodec_free_context(&dec_ctx); - return; - } - - // The GPU encoder is tried first when asked for, and anything that goes - // wrong on the way - no such encoder built into FFmpeg, no usable device, - // no surface pool, the encoder refusing to open - just leaves hardware - // false and takes the software path below. bool hardware = false; const AVCodec *enc = nullptr; AVCodecContext *enc_ctx = nullptr; AVBufferRef *hw_frames_ref = nullptr; + out->ctx = nullptr; + out->hwFrames = nullptr; + out->hardware = false; + out->name.clear(); + + Q_UNUSED(ret); + Q_UNUSED(acceleration); + #ifdef HAVE_VAAPI - if ((m_acceleration & VideoAccelerationVaapi) && VaapiContext::isAvailable()) + if ((acceleration & VideoAccelerationVaapi) && VaapiContext::isAvailable()) { enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].vaapiEncoder); AVBufferRef *hw_device_ref = enc ? VaapiContext::deviceRef() : nullptr; @@ -1701,7 +1777,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) if (hw_device_ref) { enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, nullptr, &hw_frames_ref); // Newer Intel GPUs (iHD driver, Gen11+) expose only the low-power @@ -1711,7 +1787,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) AVDictionary *opts = nullptr; av_dict_set(&opts, "low_power", "1", 0); enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_VAAPI, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, &opts, &hw_frames_ref); av_dict_free(&opts); } @@ -1742,10 +1818,10 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // that somehow has both - libva has a Windows port of its own - still // gets a hardware encoder if only one of the two comes up. // - // The device is created per capture session and dropped with it, unlike - // the VAAPI one: nothing else in the client holds a D3D12 device - the - // decoder makes its own, and rendering does not go through one. - if (!hardware && (m_acceleration & VideoAccelerationD3d12va)) + // The device is created per encoder and dropped with it, unlike the VAAPI + // one: nothing else in the client holds a D3D12 device - the decoder makes + // its own, and rendering does not go through one. + if (!hardware && (acceleration & VideoAccelerationD3d12va)) { const char *encoderName = kVideoEncoders[encIdx].d3d12vaEncoder; @@ -1779,7 +1855,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_dict_set(&options, "rc_mode", kRateControls[r], 0); enc_ctx = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, - m_width, m_height, frameRate, m_bitrate, gopSize, + width, height, frameRate, bitrate, gopSize, &options, &hw_frames_ref); av_dict_free(&options); } @@ -1799,7 +1875,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_dict_set(&options, "rc_mode", "CQP", 0); AVCodecContext *probe = openHwEncoder(enc, hw_device_ref, AV_PIX_FMT_D3D12, - m_width, m_height, frameRate, m_bitrate, + width, height, frameRate, bitrate, gopSize, &options, &probe_frames_ref); av_dict_free(&options); @@ -1850,7 +1926,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // encoder the GPU vendor's driver has registered with Windows, so it also // covers GPUs, drivers and versions of Windows that predate D3D12 video // encoding. - if (!hardware && (m_acceleration & VideoAccelerationMediaFoundation)) + if (!hardware && (acceleration & VideoAccelerationMediaFoundation)) { const char *encoderName = kVideoEncoders[encIdx].mediaFoundationEncoder; @@ -1858,8 +1934,8 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) if (enc) { - enc_ctx = openMediaFoundationEncoder(enc, m_width, m_height, frameRate, - m_bitrate, gopSize); + enc_ctx = openMediaFoundationEncoder(enc, width, height, frameRate, + bitrate, gopSize); hardware = enc_ctx != nullptr; } else if (encoderName) @@ -1878,55 +1954,331 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) } #endif - // Named rather than taken from enc->name because the VAAPI branch above - // may have left a different encoder in enc; filled in below for the - // software path, which is the only one the private options apply to. - QString swEncoderName; + if (hardware) + { + out->ctx = enc_ctx; + out->hwFrames = hw_frames_ref; + out->hardware = true; + out->name = QLatin1String(enc->name); + return true; + } - if (!hardware) + if (!allowSoftware) { - enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].swEncoder); - if (!enc) - enc = avcodec_find_encoder(kVideoEncoders[encIdx].id); - enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; - if (!enc || !enc_ctx) - { - QString msg = QString("No %1 encoder available").arg(QLatin1String(kVideoEncoders[encIdx].codec)); - qWarning() << msg; - emit errorOccurred(msg); - if (enc_ctx) avcodec_free_context(&enc_ctx); - avcodec_free_context(&dec_ctx); - return; - } + *error = QString("No hardware %1 encoder opened").arg(QLatin1String(kVideoEncoders[encIdx].codec)); + return false; + } + + enc = avcodec_find_encoder_by_name(kVideoEncoders[encIdx].swEncoder); + if (!enc) + enc = avcodec_find_encoder(kVideoEncoders[encIdx].id); + enc_ctx = enc ? avcodec_alloc_context3(enc) : nullptr; + if (!enc || !enc_ctx) + { + *error = QString("No %1 encoder available").arg(QLatin1String(kVideoEncoders[encIdx].codec)); + if (enc_ctx) avcodec_free_context(&enc_ctx); + return false; + } - swEncoderName = QLatin1String(enc->name); + const QString swEncoderName = QLatin1String(enc->name); + + 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->framerate = frameRate; + enc_ctx->bit_rate = bitrate; + enc_ctx->gop_size = gopSize; + // B-frames reorder output, which would cost latency in a live call. + enc_ctx->max_b_frames = 0; + + // Note the absence of AV_CODEC_FLAG_GLOBAL_HEADER: we want the parameter + // sets repeated in-band with every keyframe, since the receiving side has + // no out-of-band way to learn them and may start decoding mid-stream. + applyLiveEncoderOptions(enc_ctx, swEncoderName, kSliceMaxSize); + + if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + { + *error = QString("Could not open the %1 encoder: %2").arg(swEncoderName, ff_errstr(ret)); + avcodec_free_context(&enc_ctx); + return false; + } + + out->ctx = enc_ctx; + out->name = swEncoderName; + return true; +} + +// The frame the camera's pictures are scaled into for an encoder. With an +// encoder that draws on a surface pool this is only a staging buffer in system +// memory - NV12, which is what the GPU encoders take - that gets uploaded to a +// GPU surface before encoding; the encoder itself consumes surfaces and never +// sees this frame. Every other encoder, Media Foundation's included, takes it +// as it is. +static AVFrame *allocEncoderFrame(const AVCodecContext *enc_ctx) +{ + AVFrame *frame = av_frame_alloc(); + + if (!frame) + return nullptr; + + frame->format = enc_ctx->hw_frames_ctx ? AV_PIX_FMT_NV12 : enc_ctx->pix_fmt; + frame->width = enc_ctx->width; + frame->height = enc_ctx->height; + + if (av_frame_get_buffer(frame, 0) < 0) + av_frame_free(&frame); + + return frame; +} + +// Whether an opened encoder turns a frame into a packet: an encoder that +// opens is not always one that works - a driver can accept the settings and +// then fail on the first surface. +static bool encoderWorks(AVCodecContext *enc_ctx) +{ + AVFrame *frame = allocEncoderFrame(enc_ctx); + AVFrame *hw_frame = nullptr; + AVPacket *pkt = av_packet_alloc(); + bool works = false; + + if (!frame || !pkt) + goto out; + + { + ptrdiff_t linesizes[4]; + + for (int i = 0; i < 4; i++) + linesizes[i] = frame->linesize[i]; + + av_image_fill_black(frame->data, linesizes, (AVPixelFormat)frame->format, + AVCOL_RANGE_MPEG, frame->width, frame->height); + } + + frame->pts = 0; + + if (enc_ctx->hw_frames_ctx) + { + hw_frame = av_frame_alloc(); + + if (!hw_frame || + av_hwframe_get_buffer(enc_ctx->hw_frames_ctx, hw_frame, 0) < 0 || + av_hwframe_transfer_data(hw_frame, frame, 0) < 0) + goto out; + + hw_frame->pts = 0; + } + + if (avcodec_send_frame(enc_ctx, hw_frame ? hw_frame : frame) < 0 || + avcodec_send_frame(enc_ctx, nullptr) < 0) + goto out; + + while (avcodec_receive_packet(enc_ctx, pkt) == 0) + { + if (pkt->size > 0) + works = true; + + av_packet_unref(pkt); + } + +out: + av_packet_free(&pkt); + av_frame_free(&hw_frame); + av_frame_free(&frame); + + return works; +} + +static QMutex s_probeMutex; +static bool s_probed = false; +static QList<CallHardwareEncoder> s_hardwareEncoders; + +QList<CallHardwareEncoder> VideoDevice::ProbeHardwareEncoders() +{ + 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 + + // In the order openVideoEncoder() tries them. + static const VideoAcceleration kAccelerations[] = + { + VideoAccelerationVaapi, VideoAccelerationD3d12va, VideoAccelerationMediaFoundation + }; - enc_ctx->width = m_width; - enc_ctx->height = m_height; - enc_ctx->pix_fmt = AV_PIX_FMT_YUV420P; - enc_ctx->time_base = av_inv_q(frameRate); - enc_ctx->framerate = frameRate; - enc_ctx->bit_rate = m_bitrate; - enc_ctx->gop_size = gopSize; - // B-frames reorder output, which would cost latency in a live call. - enc_ctx->max_b_frames = 0; + // A common call size and rate: a GPU that cannot encode this is no use + // for a call either. + const AVRational frameRate = { 30, 1 }; - // Note the absence of AV_CODEC_FLAG_GLOBAL_HEADER: we want the parameter - // sets repeated in-band with every keyframe, since the receiving side has - // no out-of-band way to learn them and may start decoding mid-stream. - applyLiveEncoderOptions(enc_ctx, swEncoderName, kSliceMaxSize); + qDebug() << "Finding out which hardware video encoders work - failures below are expected"; - if ((ret = avcodec_open2(enc_ctx, enc, nullptr)) < 0) + for (unsigned int c = 0; c < sizeof(kVideoEncoders) / sizeof(kVideoEncoders[0]); c++) + { + for (unsigned int a = 0; a < sizeof(kAccelerations) / sizeof(kAccelerations[0]); a++) { - QString msg = QString("Could not open the %1 encoder: %2").arg(swEncoderName, ff_errstr(ret)); - qWarning() << msg; - emit errorOccurred(msg); - avcodec_free_context(&enc_ctx); - avcodec_free_context(&dec_ctx); - return; + const char *name = nullptr; + + if (kAccelerations[a] == VideoAccelerationVaapi) + { +#ifdef HAVE_VAAPI + name = kVideoEncoders[c].vaapiEncoder; +#endif + } + else if (kAccelerations[a] == VideoAccelerationD3d12va) + { +#ifdef HAVE_D3D12VA + name = kVideoEncoders[c].d3d12vaEncoder; +#endif + } + else + { +#ifdef Q_OS_WIN + name = kVideoEncoders[c].mediaFoundationEncoder; +#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; + + if (!openVideoEncoder((int)c, kAccelerations[a], 1280, 720, frameRate, 2000000, 60, + false, &es, &error)) + continue; + + if (encoderWorks(es.ctx)) + { + CallHardwareEncoder e; + + 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); + } + + closeVideoEncoder(&es); } } + QStringList names; + + for (int i = 0; i < s_hardwareEncoders.size(); i++) + names << s_hardwareEncoders.at(i).encoder; + + qDebug() << "Hardware video encoders that work here:" + << (names.isEmpty() ? QStringLiteral("none") : names.join(QLatin1String(", "))); + + s_probed = true; + + return s_hardwareEncoders; +} + +bool VideoDevice::HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders) +{ + // Not waiting is the point: a probe that is running holds the lock. + if (!s_probeMutex.tryLock()) + return false; + + const bool probed = s_probed; + + if (probed && encoders) + *encoders = s_hardwareEncoders; + + s_probeMutex.unlock(); + + return probed; +} + +QList<CallCameraSize> VideoDevice::CallCameraSizes(const QList<VideoCaptureFormat> &formats) +{ + QList<CallCameraSize> sizes; + + for (int i = 0; i < formats.size(); i++) + { + CallCameraSize s; + + s.size = QSize(formats.at(i).width, formats.at(i).height); + s.frameRates = formats.at(i).frameRates; + sizes << s; + } + + 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. +static const double kReopenBitrateStep = 0.15; +static const int kReopenIntervalMs = 5000; + +void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) +{ + const AVRational frameRate = cameraFrameRate(in_st, m_frameRate); + + // Which encoder produces the configured codec. Looked up once: the GPU + // attempt and the software fallback below are two encoders for the same + // codec, so the peer is told the same thing either way. + const int encIdx = videoEncoderIndex(m_codec); + + // Two seconds between keyframes. A receiver that joins late or loses a + // 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); + + // What gets encoded: the camera's picture as it is, or for a preset that + // sends less than the camera captures, scaled down. + QSize encodeSize(m_width, m_height); + + if (m_planned && m_plan.encodeSize.isValid()) + encodeSize = m_plan.encodeSize; + + int ret; + + // The camera hands us either raw frames or a compressed stream that is + // not being forwarded as-is; either way it goes through a decoder here to + // get raw pictures for the encoder. + const AVCodec *cam_dec = avcodec_find_decoder(in_st->codecpar->codec_id); + AVCodecContext *dec_ctx = cam_dec ? avcodec_alloc_context3(cam_dec) : nullptr; + if (!cam_dec || !dec_ctx || + avcodec_parameters_to_context(dec_ctx, in_st->codecpar) < 0 || + avcodec_open2(dec_ctx, cam_dec, nullptr) < 0) + { + QString msg = "Could not open camera format decoder"; + qWarning() << msg; + emit errorOccurred(msg); + if (dec_ctx) avcodec_free_context(&dec_ctx); + return; + } + + VideoEncoderSession encoder; + QString encoderError; + + if (!openVideoEncoder(encIdx, m_acceleration, encodeSize.width(), encodeSize.height(), + frameRate, m_bitrate, gopSize, true, &encoder, &encoderError)) + { + qWarning() << encoderError; + emit errorOccurred(encoderError); + avcodec_free_context(&dec_ctx); + return; + } + // Which format the camera is actually delivering, reported alongside the // encoder because the two together explain the frame rate: an uncompressed // camera stream is what caps the rate on a USB 2.0 bus, and seeing @@ -1939,10 +2291,8 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // Named from the encoder that was actually opened rather than written out // per API: "h264_vaapi" and "hevc_d3d12va" say both which codec and which // accelerator settled it, and cannot drift from what is running. - emit accelerationInUse(hardware - ? QString("GPU encoding (%1) from %2") - .arg(QLatin1String(enc->name), source) - : QString("CPU encoding (%1) from %2").arg(swEncoderName, source)); + emit accelerationInUse(QString(encoder.hardware ? "GPU encoding (%1) from %2" : "CPU encoding (%1) from %2") + .arg(encoder.name, source)); // Everything the camera sends is scaled to the encoder's size and re-encoded, // so this is what the peer will receive regardless of what the camera @@ -1954,36 +2304,34 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) // The rate is the camera's, not the encoder's: the encoder is configured // from it (see frameRate above) and encodes every frame it is given, so // what the camera delivers is what goes out. - emit captureStarted(QLatin1String(avcodec_get_name(enc_ctx->codec_id)), - enc_ctx->width, enc_ctx->height, av_q2d(frameRate)); + const QString codecName = QLatin1String(avcodec_get_name(encoder.ctx->codec_id)); - // What the camera's frames are scaled into. With an encoder that draws on - // a surface pool this is only a staging buffer in system memory - NV12, - // which is what the GPU encoders take - that gets uploaded to a GPU - // surface below; the encoder itself consumes surfaces and never sees this - // frame. Every other encoder, Media Foundation's included, takes it as it - // is. - AVPixelFormat sw_pix_fmt = enc_ctx->hw_frames_ctx ? AV_PIX_FMT_NV12 : enc_ctx->pix_fmt; + emit captureStarted(codecName, encoder.ctx->width, encoder.ctx->height, av_q2d(frameRate)); - AVFrame *enc_frame = av_frame_alloc(); - if (enc_frame) - { - enc_frame->format = sw_pix_fmt; - enc_frame->width = enc_ctx->width; - enc_frame->height = enc_ctx->height; - } - if (!enc_frame || av_frame_get_buffer(enc_frame, 0) < 0) + AVFrame *enc_frame = allocEncoderFrame(encoder.ctx); + if (!enc_frame) { QString msg = "Could not allocate encoder frame"; qWarning() << msg; emit errorOccurred(msg); - if (enc_frame) av_frame_free(&enc_frame); - if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); - avcodec_free_context(&enc_ctx); + closeVideoEncoder(&encoder); avcodec_free_context(&dec_ctx); return; } + // CallQualityAdaptive: the peer's reports decide the bitrate and size from + // here on, see CallRateController. + const bool adaptive = m_planned && m_plan.adaptive(); + CallRateController rate; + QElapsedTimer clock; + int64_t currentBitrate = m_bitrate; + qint64 lastReopen = 0; + + clock.start(); + + if (adaptive) + rate.start(m_plan, 0); + SwsContext *sws = nullptr; AVPacket *in_pkt = av_packet_alloc(); AVFrame *cam_frame = av_frame_alloc(); @@ -2015,6 +2363,110 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) while (avcodec_receive_frame(dec_ctx, cam_frame) == 0) { + // Between frames, so that a new encoder starts with a whole one. + if (adaptive) + { + const QList<CallReceptionReport> reports = takeReports(); + + for (int i = 0; i < reports.size(); i++) + { + if (rate.update(reports.at(i), m_fragmentsSent, clock.elapsed())) + qDebug() << QString("Adaptive call quality: %1x%2 at %3 kbit/s - %4") + .arg(rate.size().width()).arg(rate.size().height()) + .arg(rate.bitrateKbps()).arg(rate.reason()); + + m_fragmentsSent = 0; + } + + const QSize wantedSize = rate.size(); + const int64_t wantedBitrate = (int64_t)rate.bitrateKbps() * 1000; + bool reopen = wantedSize != encodeSize; + + if (!reopen && wantedBitrate != currentBitrate) + { + const double ratio = (double)wantedBitrate / currentBitrate; + + if (encoder.name == QLatin1String("libx264")) + { + // FFmpeg's libx264 wrapper compares this with what + // the encoder runs at before every frame, and hands a + // change to x264_encoder_reconfig(): no new encoder, + // no keyframe. + encoder.ctx->bit_rate = wantedBitrate; + currentBitrate = wantedBitrate; + } + else if (ratio <= 1.0 - kReopenBitrateStep || + (ratio >= 1.0 + kReopenBitrateStep && clock.elapsed() - lastReopen >= kReopenIntervalMs)) + { + reopen = true; + } + } + + // 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; + + 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 (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) + { + while (avcodec_receive_packet(encoder.ctx, out_pkt) == 0) + { + 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; + + // The scaler targets the encoder's size and format. + if (sws) + { + sws_freeContext(sws); + sws = nullptr; + } + + if (wantedSize != encodeSize) + { + encodeSize = wantedSize; + emit streamChanged(codecName, encodeSize.width(), encodeSize.height()); + } + } + else + { + 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; + // Built lazily: the camera's actual frame format and size are // only known once a frame has been decoded, and may differ from // what was requested. @@ -2025,7 +2477,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) swscaleSourceFormat((AVPixelFormat)cam_frame->format, &srcFullRange); sws = sws_getContext(cam_frame->width, cam_frame->height, srcFormat, - enc_ctx->width, enc_ctx->height, sw_pix_fmt, + enc_ctx->width, enc_ctx->height, (AVPixelFormat)enc_frame->format, SWS_BILINEAR, nullptr, nullptr, nullptr); if (!sws) { @@ -2133,8 +2585,7 @@ void VideoDevice::runTranscodeLoop(AVFormatContext *ifmt_ctx, AVStream *in_st) av_frame_free(&cam_frame); av_frame_free(&enc_frame); if (sws) sws_freeContext(sws); - if (hw_frames_ref) av_buffer_unref(&hw_frames_ref); - avcodec_free_context(&enc_ctx); + closeVideoEncoder(&encoder); avcodec_free_context(&dec_ctx); } diff --git a/pica-client/videodevice.h b/pica-client/videodevice.h index 14a906a..2724d63 100644 --- a/pica-client/videodevice.h +++ b/pica-client/videodevice.h @@ -19,6 +19,7 @@ #include "mediadevice.h" #include "callsettings.h" +#include "callquality.h" #include "vaapi.h" #include <QObject> #include <QString> @@ -29,6 +30,7 @@ #include <QWaitCondition> #include <QSize> #include <QAtomicInt> +#include <QList> // Reassembles the fragments of one encoded video frame, as carried by 0x77 // protocol messages - see the fragmentation description in @@ -193,6 +195,27 @@ public: // captureSizeWithin(). Queued after configureCapture(), which clears it. Q_INVOKABLE void limitCaptureSize(int width, int height); + // 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 + // 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); + + // One 0x79 report from the peer of the call, for CallQualityAdaptive to + // follow - see CallRateController. Ignored with any other preset. Safe to + // call from any thread, and called directly rather than queued for the + // 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(); + // Allows Capture()/Play() to run for the call this pair of ids names, // until Close() - the same arrangement as AudioDevice::openSession(). To // be called directly, before the calls that configure and start the @@ -327,6 +350,13 @@ signals: // encoding altogether - neither should have to be guessed at. void accelerationInUse(QString description); + // What is being sent changed in the middle of a capture: CallQualityAdaptive + // moved to another picture size. For a new 0x75; the codec stays the same. + void streamChanged(QString codec, int width, int height); + + // See probeHardwareEncoders(). + void hardwareEncodersProbed(); + public: virtual QList<MediaDeviceInfo> Enumerate(enum MediaDeviceStreamDirection dir); @@ -356,6 +386,21 @@ 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(); + + // The same, without waiting: false while the probe has not run yet. + static bool HardwareEncodersProbed(QList<CallHardwareEncoder> *encoders); + + // The sizes and rates of CaptureFormats() as the call quality planning + // takes them. + static QList<CallCameraSize> CallCameraSizes(const QList<VideoCaptureFormat> &formats); + private: QString m_deviceName; QString m_codec; @@ -367,6 +412,19 @@ private: int m_frameRate; int m_bitrate; bool m_preferCompressed; + // see setQualityPreset() + int m_preset; + // What Capture() made of a preset; m_planned is false for + // CallQualityCustom, which encodes at m_width x m_height. + CallVideoPlan m_plan; + bool m_planned; + + // see reportReception() + QMutex m_reportMutex; + QList<CallReceptionReport> m_reports; + QList<CallReceptionReport> takeReports(); + // Fragments emitted since the last report was taken. Capture thread only. + int m_fragmentsSent; // VideoAcceleration flags; which of them apply depends on the direction // this instance was configured for. int m_acceleration; |
