Files
SageTube/ytsage/main.py
T
Homer 5ae2817eea Stop the player freeing a render context libmpv still uses
The segfault: Qt destroys and recreates a widget's QOpenGLContext whenever it
moves to another top-level window, then calls initializeGL() again. libmpv
permits one render context per handle, so the second creation failed with
"There is already a mpv_render_context set" -- and the except branch assigned
self._render_ctx = None, dropping the last Python reference to the first
context, which libmpv was still holding a function pointer into. python-mpv's
MpvRenderContext has no __del__ and free() does not unregister the callback,
so the ctypes trampoline was collected while registered and the next frame
notification jumped into freed memory.

Two invariants fix it. initializeGL() now tears down any existing render
context first, so a second call is an ordinary recreation. Teardown clears
update_cb, calls free() with the GL context current, and only then drops the
reference -- and it is connected to QOpenGLContext.aboutToBeDestroyed, so it
runs before the GL context dies instead of never. The local reference during
teardown is load-bearing: it is what keeps the trampoline alive until free()
returns.

Three things were destroying that context. Fullscreen reparented the panel
into a new top-level window (twice per toggle) and put it back at the end of
the splitter, losing the pane layout; it now fullscreens the main window and
hides the chrome, reparenting nothing. The tab cross-fade and the dialog blur
both grab() the widget tree, which on an OpenGL surface forces a framebuffer
readback and returns black -- the fade is skipped for pages holding the video,
and dialogs dim rather than blur.

Verified on a real Wayland GL context: ten forced context destroy/recreate
cycles re-establish the render context every time, and the full app survives
tab switching, six fullscreen toggles and resizes with no render-context
error and a clean exit. Before this, the same startup dumped core.

Also here because they are one-line consequences of touching _create_mpv: an
explicit per-platform hwdec list ending in software decoding, and the restored
volume actually reaching mpv -- the slider set its value before connecting its
signal, so playback always started at 100.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-09 00:48:18 +02:00

72 lines
2.6 KiB
Python

import sys
from PySide6.QtCore import QCoreApplication, Qt
from PySide6.QtGui import QSurfaceFormat
from PySide6.QtWidgets import QApplication, QMessageBox
from .utils.ytsage_logger import logger
from .gui.ytsage_gui_main import YTSageApp # Import the main application class from ytsage_gui_main
def _configure_opengl() -> None:
"""
Must run before QApplication exists -- both settings are ignored afterwards.
AA_ShareOpenGLContexts puts every widget context in one sharing group, so
a reparent no longer loses GL *resources*. It does not stop Qt destroying
and recreating the widget's own context (MpvRenderWidget handles that);
it removes a whole second class of failure around it.
The surface format is deliberately minimal. mpv renders into our FBO and
needs no depth, stencil or alpha from the default framebuffer, and asking
for them is what produced `OpenGL error INVALID_ENUM` on some drivers. No
GL version or profile is requested on purpose: pinning a core profile
breaks software and GLES stacks that libmpv would otherwise accept.
"""
QCoreApplication.setAttribute(Qt.ApplicationAttribute.AA_ShareOpenGLContexts, True)
fmt = QSurfaceFormat()
fmt.setSwapBehavior(QSurfaceFormat.SwapBehavior.DoubleBuffer)
fmt.setSwapInterval(1)
fmt.setDepthBufferSize(0)
fmt.setStencilBufferSize(0)
fmt.setAlphaBufferSize(0)
QSurfaceFormat.setDefaultFormat(fmt)
def show_error_dialog(message):
# A QMessageBox needs a live QApplication; if startup failed before (or
# while) creating one, constructing the dialog would abort the process
# and swallow the real error.
if QApplication.instance() is None:
print(f"Application Error: {message}", file=sys.stderr)
return
error_dialog = QMessageBox()
error_dialog.setIcon(QMessageBox.Icon.Critical)
error_dialog.setText("Application Error")
error_dialog.setInformativeText(message)
error_dialog.setWindowTitle("Error")
error_dialog.exec()
def main():
try:
logger.info("Starting SageTube application")
_configure_opengl()
app = QApplication(sys.argv)
app.setApplicationName("SageTube")
app.setDesktopFileName("sagetube")
window = YTSageApp() # Instantiate the main application class
window.show()
logger.info("Application window shown, entering main loop")
sys.exit(app.exec())
except Exception as e:
logger.critical(f"Critical application error: {e}", exc_info=True)
show_error_dialog(f"Critical error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()