Replies: 2 comments
This comment was marked as spam.
This comment was marked as spam.
-
The FFmpeg I can offer a solution: a token bucket. The principle is all over the web; it's basically using time calculation and a time-driven approach to achieve precise rate control. Simple and effective. Here's an implementation. import time
import threading
class TokenBucket:
"""
An implementation of the token bucket algorithm to maintain a nearly
constant consumption rate (FPS).
"""
def __init__(self, fps: float, capacity: int = 3):
"""
Initializes the TokenBucket.
:param fps: The rate of token generation (frames per second).
:param capacity: The maximum number of tokens the bucket can hold.
This allows for short bursts.
"""
self.period = 1.0 / fps
self.capacity = float(capacity)
self.tokens = float(capacity) # Start with a full bucket.
self.last_check = time.perf_counter()
self._lock = threading.Lock()
def _add_new_tokens(self) -> None:
now = time.perf_counter()
elapsed = now - self.last_check
new_tokens = elapsed / self.period
if new_tokens > 0:
self.tokens = min(self.capacity, self.tokens + new_tokens)
self.last_check = now
def consume(self) -> None:
"""
Consume one token. If no tokens are available, this method will
block until one is.
"""
while True:
with self._lock:
self._add_new_tokens()
if self.tokens >= 1:
self.tokens -= 1
return
# Sleep for a fraction of the period to avoid busy-waiting.
time.sleep(self.period * 0.5) Integrate it into your main loop. # ... (setup code)
bucket = TokenBucket(fps=fps)
# start frame loop
start = time()
for frame_i in range(total_frames):
bucket.consume()
surface = cairo.ImageSurface (cairo.FORMAT_RGB24, width, height)
ctx = cairo.Context (surface)
draw(ctx,frame_i , total_frames)
im = to_pil(surface)
frame = av.VideoFrame.from_image(im)
for packet in stream.encode(frame):
container.mux(packet)
# ... (cleanup code) Happy streaming by the way |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hi i working on a application for a livestream that need handle the encoding in real time.
the concept is that i generate the animation in Cairo and than pass thrue to ffmpeg using pillow but the that i have is that i can not generate this in real time in my test code this is to fast.
I know that ffmpeg have a realtime switch but i don't know how is done using pyav
my test code that i wand to stream
ffmpeg commandline that i current use for testing livestream to youtube
Beta Was this translation helpful? Give feedback.
All reactions