summaryrefslogtreecommitdiffstats
path: root/pica-client/callquality.cpp
blob: 33289a1eaa6c28939151c9c66f8c100d2d354323 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
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;
}