Attempt to reduce leak of ffmpeg previews

This commit is contained in:
Leo Vasanko 2023-11-21 12:22:03 +00:00
parent 71eb252b8d
commit 02c5e484b5

View File

@ -1,5 +1,4 @@
import asyncio import asyncio
import gc
import io import io
import mimetypes import mimetypes
import urllib.parse import urllib.parse
@ -10,6 +9,7 @@ from wsgiref.handlers import format_date_time
import av import av
import av.datasets import av.datasets
import fitz # PyMuPDF import fitz # PyMuPDF
from av.streams import SideData
from PIL import Image from PIL import Image
from sanic import Blueprint, empty, raw from sanic import Blueprint, empty, raw
from sanic.exceptions import NotFound from sanic.exceptions import NotFound
@ -97,24 +97,17 @@ def process_pdf(path, *, maxsize, maxzoom, quality, page_number=0):
def process_video(path, *, maxsize, quality): def process_video(path, *, maxsize, quality):
with av.open(str(path)) as container: with av.open(str(path)) as container:
stream = container.streams.video[0] stream = container.streams.video[0]
rotation = ( rot = stream.side_data and stream.side_data.get(SideData.DISPLAYMATRIX) or 0
stream.side_data
and stream.side_data.get(av.stream.SideData.DISPLAYMATRIX)
or 0
)
stream.codec_context.skip_frame = "NONKEY" stream.codec_context.skip_frame = "NONKEY"
container.seek(container.duration // 8) container.seek(container.duration // 8)
frame = next(container.decode(stream)) img = next(container.decode(stream)).to_image()
img = frame.to_image() del stream
del frame, stream
img.thumbnail((maxsize, maxsize)) img.thumbnail((maxsize, maxsize))
imgdata = io.BytesIO() imgdata = io.BytesIO()
if rotation: if rot:
img = img.rotate(rotation, expand=True) img = img.rotate(rot, expand=True)
img.save(imgdata, format="webp", quality=quality, method=4) img.save(imgdata, format="webp", quality=quality, method=4)
del img del img
ret = imgdata.getvalue() return imgdata.getvalue()
gc.collect()
return ret