Skip to content

Commit fa04c7c

Browse files
committed
Limit the number of threads for VP8 encoding
When we switched to using PyAV for VP8 encoding we dropped the logic which defined the number of threads to use for encoding. This results in using as many threads as there are CPUs: https://github.com/FFmpeg/FFmpeg/blob/b6f84cd72acd84ba725922bd6a8967b416b2230a/libavcodec/libvpxenc.c#L1014 Restore the previous behaviour.
1 parent 71e79dd commit fa04c7c

File tree

2 files changed

+27
-1
lines changed

2 files changed

+27
-1
lines changed

src/aiortc/codecs/vpx.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import multiprocessing
12
import random
23
from struct import pack, unpack_from
34
from typing import Optional, Type, TypeVar, cast
@@ -22,6 +23,17 @@
2223
DESCRIPTOR_T = TypeVar("DESCRIPTOR_T", bound="VpxPayloadDescriptor")
2324

2425

26+
def number_of_threads(pixels: int, cpus: int) -> int:
27+
if pixels >= 1920 * 1080 and cpus > 8:
28+
return 8
29+
elif pixels > 1280 * 960 and cpus >= 6:
30+
return 3
31+
elif pixels > 640 * 480 and cpus >= 3:
32+
return 2
33+
else:
34+
return 1
35+
36+
2537
class VpxPayloadDescriptor:
2638
def __init__(
2739
self,
@@ -213,6 +225,9 @@ def encode(
213225
"static-thresh": "1",
214226
"undershoot-pct": "100",
215227
}
228+
self.codec.thread_count = number_of_threads(
229+
frame.width * frame.height, multiprocessing.cpu_count()
230+
)
216231

217232
data_to_send = b""
218233
for package in self.codec.encode(frame):

tests/test_vpx.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,12 @@
22
from unittest import TestCase
33

44
from aiortc.codecs import get_decoder, get_encoder
5-
from aiortc.codecs.vpx import Vp8Decoder, Vp8Encoder, VpxPayloadDescriptor
5+
from aiortc.codecs.vpx import (
6+
Vp8Decoder,
7+
Vp8Encoder,
8+
VpxPayloadDescriptor,
9+
number_of_threads,
10+
)
611
from aiortc.rtcrtpparameters import RTCRtpCodecParameters
712

813
from .codecs import CodecTestCase
@@ -234,6 +239,12 @@ def test_encoder_target_bitrate(self) -> None:
234239
self.assertTrue(len(payloads[0]) < 1300)
235240
self.assertAlmostEqual(timestamp, 3000, delta=1)
236241

242+
def test_number_of_threads(self) -> None:
243+
self.assertEqual(number_of_threads(1920 * 1080, 16), 8)
244+
self.assertEqual(number_of_threads(1920 * 1080, 8), 3)
245+
self.assertEqual(number_of_threads(1920 * 1080, 4), 2)
246+
self.assertEqual(number_of_threads(1920 * 1080, 2), 1)
247+
237248
def test_roundtrip_1280_720(self) -> None:
238249
self.roundtrip_video(VP8_CODEC, 1280, 720)
239250

0 commit comments

Comments
 (0)