flet icon indicating copy to clipboard operation
flet copied to clipboard

bug: High memory usage and leak when streaming from local server (Flet 0.80.5)

Open LakshmanSagar opened this issue 10 months ago • 4 comments

Duplicate Check

  • [x] I have searched the opened issues and there are no duplicates

Describe the bug

In Flet version 0.80.5, the Video control fails to release native memory and background threads when streaming from a local embedded server (specifically a Golang-based HTTP server). This results in a massive linear RAM bloat (approx. 400MB per session). Even after stopping the video, clearing the playlist, and removing the view, the libmpv and libdav1d (software decoding) processes remain active, holding onto C-allocated buffers.

System Info

  • Flet Version: 0.80.5
  • OS: Linux (Ubuntu/Debian) / Windows
  • Backend Engine: Golang (HTTP ServeContent)
  • Decoder: Software decoding (AV1/HEVC via libdav1d)

Code sample

Code
[Paste your code here]

To reproduce

  • Initialize a Golang HTTP server that serves a high-bitrate video file using http.ServeContent.
  • Launch a Flet app using a Router and a flet_video.Video control.
  • Load the local Go-stream URL into the player on a sub-route (e.g., /player).
  • Navigate back to the Home view (/) and then back to the Player multiple times.
  • Observe RAM: In my tests, the memory reached 1.6 GB after cycling through only 4 videos, as each previous "session" remained resident in memory. Removing the Python View from page.views does not trigger the Dart dispose() method reliably in Flet 0.80.5. Consequently, the native libmpv handles are never released.

Expected behavior

When the Video control is removed from the widget tree (or the parent View is popped), it should trigger an explicit native dispose() signal. This should:

  • Immediately terminate all libdav1d decoding threads.
  • Close the HTTP socket connection to the Golang server.
  • Release all C-allocated frame buffers.

Observed Behavior The Python object is destroyed, but the Native/C-layer stays active. gc.collect() has no effect because the leak is inside the Flutter/native engine.

Screenshots / Videos

Captures

[Upload media here]

Operating System

Linux

Operating system details

Ubuntu 24.04 LTS

Flet version

0.80.5

Regression

No, it isn't

Suggestions

  • I think, in the underlying VideoControl.dart, the build method creates multiple stream listeners (player.stream.error.listen, player.stream.completed.listen, etc.) without ever cancelling them, maybe? These Dart listeners keep the media_kit Player alive I think
  • Maybe suggest a hard-dispose method or a way to manually trigger the native dispose() signal from the Python API?

Logs

Logs
[Paste your logs here]

Additional details

No response

LakshmanSagar avatar Feb 01 '26 12:02 LakshmanSagar

@LakshmanSagar I can double this! The problem is actually much simpler. Any instance of Flet Video has troubles cleaning it's memory. Bellow is an example, which spawns two videos in a loop. You can watch in your task manager of choice Flet's RAM usage go up (around 20MB/iteration - your case was much more memory hungry (probably bigger buffers)).

import asyncio
import warnings

import flet as ft
import flet_video as fv

warnings.filterwarnings("ignore", category=DeprecationWarning)

DELAY_S = 5

VIDEO_A = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerJoyrides.mp4"
VIDEO_B = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ForBiggerMeltdowns.mp4"


class SwapView(ft.View):
    def __init__(self, route: str, next_route: str, bgcolor: str, video_url: str):
        super().__init__(route=route, bgcolor=bgcolor, padding=20)

        self._next_route = next_route
        self._running = False
        self._task = None

        self.video = fv.Video(
            playlist=[fv.VideoMedia(resource=video_url)],
            playlist_mode=fv.PlaylistMode.SINGLE,
            autoplay=True,
            muted=True,
            fit=ft.BoxFit.CONTAIN,
            show_controls=True,
        )

        self.controls = [
            ft.Text(f"Route: {route}", size=20, weight=ft.FontWeight.BOLD),
            ft.Text(f"Auto-switch to: {next_route} in {DELAY_S}s"),
            ft.Row(
                [
                    ft.Button("Go /a", on_click=lambda e: self.page.go("/a")),
                    ft.Button("Go /b", on_click=lambda e: self.page.go("/b")),
                ]
            ),
            ft.Container(height=360, bgcolor=ft.Colors.BLACK, padding=10, content=self.video),
        ]

    def did_mount(self):
        self._running = True
        self._task = self.page.run_task(self._auto_switch)

    def will_unmount(self):
        self._running = False
        if self._task:
            try:
                self._task.cancel()
            except Exception:
                pass

    async def _auto_switch(self):
        await asyncio.sleep(DELAY_S)
        if self._running and self.page:
            self.page.go(self._next_route)


def main(page: ft.Page):
    page.title = "Video route switch test"
    page.padding = 0

    def route_change(e: ft.RouteChangeEvent):
        page.views.clear()

        if page.route == "/b":
            page.views.append(SwapView("/b", "/a", ft.Colors.GREEN_200, VIDEO_B))
        else:
            page.views.append(SwapView("/a", "/b", ft.Colors.BLUE_200, VIDEO_A))

        page.update()

    page.on_route_change = route_change
    page.go("/a")


ft.run(main)

Dejv311 avatar Feb 03 '26 15:02 Dejv311

@LakshmanSagar can you please try this?

https://github.com/media-kit/media-kit/issues/776#issuecomment-2072158673

Dejv311 avatar Feb 04 '26 08:02 Dejv311

Any solution for this

HappyCoder256 avatar Mar 01 '26 14:03 HappyCoder256

@LakshmanSagar @HappyCoder256 I found out that disabling the HW acceleration did solve the continuous MEM leaking (i.e. leakage caused by viewing a stream without rebuilding the control). The CPU load slightly increases, but results in a stable system (memory-wise).

The ft.Video no longer suffers from memory leaking during rebuilding the control because of this PR, so without the HW ACC I observe no leaking anymore on Linux. (FYI @ndonkoHenri)

configuration=fv.VideoConfiguration(
      output_driver="libmpv",
      enable_hardware_acceleration=False
)

See https://flet.dev/docs/controls/video/types/videoconfiguration/#flet_video.VideoConfiguration.enable_hardware_acceleration

Dejv311 avatar Jun 17 '26 13:06 Dejv311