/*
(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 .
*/
#include "callquality.h"
#include
// 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 callVideoSizeLadder(const QSize &top)
{
QList 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 &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 &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 &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 &cameraSizes,
const QSize &peerLimit, const QList &hardware)
{
CallVideoPlan plan;
chooseEncoder(preset, hardware, &plan.codec, &plan.acceleration);
QList 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 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 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;
}