G26: keep Windows textures alive through asynchronous unregister

Retain closed raw-pointer identities for late frames, release frame buffers
after engine completion, and serialize termination with decoded frame writes.
Add native regression controls for held raster buffers, inline completion,
failed raster posts, missing registrations, teardown and concurrent closure.

B252; Apache-2.0 dependency license and upstream history preserved.
This commit is contained in:
yunchan 2026-10-29 12:13:44 +09:00
parent 8cd34a80ff
commit 50efc18ec5
10 changed files with 1268 additions and 14 deletions

View file

@ -1,4 +1,4 @@
// Modified by the Kitedesk fork (2026, B212): closeTexture takes `recycle`.
// Modified by the Kitedesk fork (2026, B212/B252): closeTexture ownership.
import 'dart:typed_data';
export './texture_rgba_ffi.dart' show Native;
@ -20,8 +20,12 @@ class TextureRgbaRenderer {
///
/// Pass [recycle] = true only when nothing calls `onRgba` with the pointer
/// from [getTexturePtr] any more. On Linux the texture is then kept for the
/// next [createTexture] of the same window instead of being leaked
/// (Kitedesk fork, B212); other platforms ignore it.
/// next [createTexture] of the same window (Kitedesk fork, B212).
/// On Windows it may be destroyed only after the engine finishes unregistering
/// it. Without [recycle], Windows retains its closed identity for the process
/// lifetime so late raw-pointer frames cannot reach freed or reused memory;
/// its frame buffers are freed after unregistering (Kitedesk fork, B252).
/// Other platforms ignore [recycle].
///
/// @return a boolean to indicate whether the operation is sucessfully executed.
Future<bool> closeTexture(int key, {bool recycle = false}) {

58
windows/test/run_tests.sh Executable file
View file

@ -0,0 +1,58 @@
#!/usr/bin/env bash
# Kitedesk fork, 2026: builds windows/test/texture_rgba_renderer_plugin_test.cc
# on Linux with the plugin sources and the C++ client wrapper of the Flutter
# Windows engine, and runs each test in its own process. The engine files come
# from FLUTTER_WINDOWS_ENGINE, by default the windows-x64 engine artifacts of the
# Flutter SDK on PATH (or FLUTTER_ROOT) as `flutter precache --windows` leaves
# them: the C headers and cpp_client_wrapper/. No display, GPU or Windows needed.
# run_tests.sh -Wall -Werror build
# run_tests.sh --asan the same with AddressSanitizer and UBSan
# run_tests.sh --tsan the same with ThreadSanitizer
# OUT_DIR (default: a new temporary directory) receives the test binary.
set -euo pipefail
here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [ -z "${FLUTTER_WINDOWS_ENGINE:-}" ]; then
root=${FLUTTER_ROOT:-$(dirname "$(dirname "$(readlink -f "$(command -v flutter)")")")}
FLUTTER_WINDOWS_ENGINE=$root/bin/cache/artifacts/engine/windows-x64
fi
engine=$FLUTTER_WINDOWS_ENGINE
wrapper=$engine/cpp_client_wrapper
[ -f "$engine/flutter_texture_registrar.h" ] && [ -f "$wrapper/core_implementations.cc" ] || {
echo "no Flutter Windows engine headers and client wrapper in $engine" \
"(flutter precache --windows, or set FLUTTER_WINDOWS_ENGINE)" >&2
exit 2
}
out=${OUT_DIR:-$(mktemp -d)}
mkdir -p "$out"
# The client wrapper headers expect <cstdint> to come with the standard headers,
# as MSVC's do; libstdc++'s do not.
flags=(-std=c++17 -Wall -Werror -O1 -g -pthread -include cstdint -DFLUTTER_PLUGIN_IMPL '-D__declspec(x)=')
case "${1:-}" in
"") ;;
--asan) flags+=('-fsanitize=address,undefined' -fno-omit-frame-pointer -fno-sanitize-recover=undefined) ;;
--tsan)
flags+=(-fsanitize=thread)
export TSAN_OPTIONS=${TSAN_OPTIONS:-halt_on_error=1}
;;
*) echo "usage: $0 [--asan | --tsan]" >&2; exit 2 ;;
esac
bin=$out/texture_rgba_renderer_plugin_test
"${CXX:-clang++}" "${flags[@]}" -I"$here/shim" -I"$wrapper/include" -I"$engine" \
"$here/texture_rgba_renderer_plugin_test.cc" \
"$here/../texture_rgba.cpp" "$here/../texture_rgba_renderer_plugin.cpp" \
"$here/../texture_rgba_renderer_plugin_c_api.cpp" \
"$wrapper/core_implementations.cc" "$wrapper/plugin_registrar.cc" "$wrapper/standard_codec.cc" \
-o "$bin"
count=0
failed=0
for test in $("$bin" --list); do
count=$((count + 1))
if "$bin" "$test"; then
echo "PASS $test"
else
echo "FAIL $test"
failed=$((failed + 1))
fi
done
echo "$count tests, $((count - failed)) passed, $failed failed"
[ "$failed" -eq 0 ]

View file

@ -0,0 +1,3 @@
// Kitedesk fork, 2026: test-only stand-in for <VersionHelpers.h> (windows/test).
// The plugin includes it but uses nothing from it. Licensed under the Apache
// License, Version 2.0, like the rest of this package.

View file

@ -0,0 +1,63 @@
// Kitedesk fork, 2026: test-only stand-in for flutter_windows.h of the Flutter
// Windows engine (a18df97c) with the declarations that the client wrapper's
// plugin_registrar_windows.h and flutter_view.h use; windows/test defines them.
// Licensed under the Apache License, Version 2.0, like the rest of this
// package.
#ifndef KD_TEST_SHIM_FLUTTER_WINDOWS_H_
#define KD_TEST_SHIM_FLUTTER_WINDOWS_H_
#include <stddef.h>
#include <stdint.h>
#include <windows.h>
#include "flutter_export.h"
#include "flutter_messenger.h"
#include "flutter_plugin_registrar.h"
#if defined(__cplusplus)
extern "C" {
#endif
struct IDXGIAdapter;
struct FlutterDesktopView;
typedef struct FlutterDesktopView* FlutterDesktopViewRef;
typedef int64_t FlutterDesktopViewId;
typedef bool (*FlutterDesktopWindowProcCallback)(HWND /* hwnd */,
UINT /* uMsg */,
WPARAM /*wParam*/,
LPARAM /* lParam*/,
void* /* user data */,
LRESULT* result);
FLUTTER_EXPORT HWND FlutterDesktopViewGetHWND(FlutterDesktopViewRef view);
FLUTTER_EXPORT struct IDXGIAdapter* FlutterDesktopViewGetGraphicsAdapter(
FlutterDesktopViewRef view);
FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetView(
FlutterDesktopPluginRegistrarRef registrar);
FLUTTER_EXPORT FlutterDesktopViewRef FlutterDesktopPluginRegistrarGetViewById(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopViewId view_id);
FLUTTER_EXPORT void
FlutterDesktopPluginRegistrarRegisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate,
void* user_data);
FLUTTER_EXPORT void
FlutterDesktopPluginRegistrarUnregisterTopLevelWindowProcDelegate(
FlutterDesktopPluginRegistrarRef registrar,
FlutterDesktopWindowProcCallback delegate);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // KD_TEST_SHIM_FLUTTER_WINDOWS_H_

View file

@ -0,0 +1,17 @@
// Kitedesk fork, 2026: test-only stand-in for <windows.h>, so that the plugin
// and the engine's C++ client wrapper build on Linux for windows/test. It has
// only the types those headers use. Licensed under the Apache License,
// Version 2.0, like the rest of this package.
#ifndef KD_TEST_SHIM_WINDOWS_H_
#define KD_TEST_SHIM_WINDOWS_H_
#include <stdint.h>
typedef struct HWND__* HWND;
typedef unsigned int UINT;
typedef uintptr_t WPARAM;
typedef intptr_t LPARAM;
typedef intptr_t LRESULT;
#endif // KD_TEST_SHIM_WINDOWS_H_

File diff suppressed because it is too large Load diff

View file

@ -1,3 +1,6 @@
// Modified by the Kitedesk fork (2026, B252): no UnregisterTexture in the
// destructor; Terminate and FreeBuffers for closeTexture.
#include "texture_rgba.h"
#include <iostream>
@ -11,11 +14,6 @@ TextureRgba::TextureRgba(flutter::TextureRegistrar *texture_registrar)
this->texture_id_ = texture_registrar->RegisterTexture(texture_.get());
}
TextureRgba::~TextureRgba()
{
texture_registrar_->UnregisterTexture(texture_id_);
}
void TextureRgba::MarkVideoFrameAvailable(
std::vector<uint8_t> &buffer, size_t width, size_t height)
{
@ -45,6 +43,11 @@ void TextureRgba::MarkVideoFrameAvailable2(const uint8_t* buffer, const size_t b
return;
}
const std::lock_guard<std::mutex> lock(mutex_);
if (terminated_)
{
// Closed while the session still pushes frames to this pointer.
return;
}
int bg_index = fg_index_ ^ 1;
buffer_tmp_[bg_index].assign(buffer, buffer + buffer_length);
width_[bg_index] = width;
@ -61,6 +64,11 @@ void TextureRgba::MarkVideoFrameAvailable2(const uint8_t* buffer, const size_t b
inline const FlutterDesktopPixelBuffer *TextureRgba::buffer()
{
const std::lock_guard<std::mutex> lock(mutex_);
if (terminated_)
{
// Closed; the engine may draw the texture until it has unregistered it.
return nullptr;
}
if (buff_ready_)
{
fg_index_ ^= 1;
@ -71,3 +79,18 @@ inline const FlutterDesktopPixelBuffer *TextureRgba::buffer()
}
return &this->flutter_pixel_buffer_;
}
void TextureRgba::Terminate()
{
const std::lock_guard<std::mutex> lock(mutex_);
terminated_ = true;
}
void TextureRgba::FreeBuffers()
{
const std::lock_guard<std::mutex> lock(mutex_);
std::vector<uint8_t>().swap(buffer_tmp_[0]);
std::vector<uint8_t>().swap(buffer_tmp_[1]);
flutter_pixel_buffer_.buffer = nullptr;
buff_ready_ = false;
}

View file

@ -1,7 +1,14 @@
// Modified by the Kitedesk fork (2026, B252): the texture no longer
// unregisters itself when destroyed (closeTexture does, and the plugin keeps
// the object alive until the engine is done with it); a closed texture drops
// pushed frames, hands the engine no buffer, and frees its frame buffers once
// the engine has unregistered it.
#ifndef TEXTURE_RGBA_H_
#define TEXTURE_RGBA_H_
#include <flutter/texture_registrar.h>
#include <atomic>
#include <mutex>
#include <chrono>
@ -9,7 +16,6 @@ class TextureRgba
{
public:
TextureRgba(flutter::TextureRegistrar* texture_registrar);
~TextureRgba();
void MarkVideoFrameAvailable(std::vector<uint8_t>& buffer, size_t width, size_t height);
@ -19,12 +25,23 @@ public:
const FlutterDesktopPixelBuffer* buffer();
// Closes the texture: frames pushed from now on are dropped without
// touching the texture registrar, and the engine gets no buffer any more.
void Terminate();
// Frees the frame buffers. Call after Terminate, once the engine has
// unregistered the texture and so no longer reads them.
void FreeBuffers();
private:
FlutterDesktopPixelBuffer flutter_pixel_buffer_{};
flutter::TextureRegistrar* texture_registrar_ = nullptr;
std::unique_ptr<flutter::TextureVariant> texture_ = nullptr;
int64_t texture_id_;
std::mutex mutex_;
// Set and read with mutex_ held, so that no frame is copied or announced
// to the engine after Terminate returns.
std::atomic<bool> terminated_{false};
int fg_index_ = 0;
bool buff_ready_ = false;
size_t width_[2];

View file

@ -1,3 +1,9 @@
// Modified by the Kitedesk fork (2026, B252): closeTexture no longer destroys
// the texture before the engine is done with it, and keeps it for good unless
// "recycle" is set; the textures of a closing engine are kept the same way;
// createTexture of a key in use answers -1; getTexturePtr of a key that is not
// open answers 0.
#include "texture_rgba_renderer_plugin.h"
// This must be included before many other Windows headers.
@ -11,10 +17,32 @@
#include <flutter/standard_method_codec.h>
#include <memory>
#include <mutex>
#include <sstream>
#include <vector>
namespace texture_rgba_renderer {
namespace {
// Textures closed while frames may still be pushed to the pointer from
// getTexturePtr: closeTexture without "recycle" (a tab moving to another
// window keeps its session's pointer), or an engine going away first. They are
// never destroyed, so such a push finds a closed texture and not freed memory,
// and their address is never handed out again for another texture (ABA). Their
// lifetime is the process; each one keeps the object, not its frame buffers.
struct Retired {
std::mutex mutex;
std::vector<std::shared_ptr<TextureRgba>> textures;
};
Retired& retired() {
static Retired* instance = new Retired();
return *instance;
}
} // namespace
// static
void TextureRgbaRendererPlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows *registrar) {
@ -38,7 +66,28 @@ TextureRgbaRendererPlugin::TextureRgbaRendererPlugin() {
this->texture_registrar = nullptr;
}
TextureRgbaRendererPlugin::~TextureRgbaRendererPlugin() {}
TextureRgbaRendererPlugin::~TextureRgbaRendererPlugin() {
// The engine is going away (its texture registrar outlives the plugins), and
// sessions may still push frames to these textures.
for (auto &entry : textures_) {
CloseTexture(std::move(entry.second), false);
}
}
void TextureRgbaRendererPlugin::CloseTexture(
std::unique_ptr<TextureRgba> texture, bool recycle) {
std::shared_ptr<TextureRgba> closed = std::move(texture);
closed->Terminate();
if (!recycle) {
std::lock_guard<std::mutex> lock(retired().mutex);
retired().textures.push_back(closed);
}
// The engine removes the texture on its raster thread, which may draw it
// until then, and calls back there. Only then are the frame buffers freed,
// and a recycled texture is destroyed with the last reference.
this->texture_registrar->UnregisterTexture(closed->texture_id(),
[closed] { closed->FreeBuffers(); });
}
void TextureRgbaRendererPlugin::HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
@ -52,16 +101,27 @@ void TextureRgbaRendererPlugin::HandleMethodCall(
it->second = std::make_unique<TextureRgba>(this->texture_registrar);
result->Success(flutter::EncodableValue(it->second->texture_id()));
}
else {
// The key is in use. Without an answer the Dart future never completes.
result->Success(flutter::EncodableValue(int64_t(-1)));
}
}
else if (method_call.method_name().compare("closeTexture") == 0) {
auto args = std::get<flutter::EncodableMap>(*method_call.arguments());
auto key = std::get<int>(args.at(flutter::EncodableValue("key")));
if (textures_.find(key) == textures_.end()) {
auto it = textures_.find(key);
if (it == textures_.end()) {
result->Success(flutter::EncodableValue(false));
}
else {
this->texture_registrar->UnregisterTexture(textures_[key]->texture_id());
textures_.erase(key);
// "recycle": true promises that nothing pushes frames to the pointer
// from getTexturePtr any more, so the texture may be destroyed.
auto recycle = args.find(flutter::EncodableValue("recycle"));
const bool* recycle_value = recycle == args.end()
? nullptr : std::get_if<bool>(&recycle->second);
CloseTexture(std::move(it->second),
recycle_value != nullptr && *recycle_value);
textures_.erase(it);
result->Success(flutter::EncodableValue(true));
}
}
@ -83,7 +143,8 @@ void TextureRgbaRendererPlugin::HandleMethodCall(
auto args = std::get<flutter::EncodableMap>(*method_call.arguments());
auto key = std::get<int>(args.at(flutter::EncodableValue("key")));
if (textures_.find(key) == textures_.end()) {
result->Success(flutter::EncodableValue(-1));
// Not open (e.g. closed meanwhile): no pointer for the session.
result->Success(flutter::EncodableValue(0));
}
else {
// Return an address.

View file

@ -1,3 +1,7 @@
// Modified by the Kitedesk fork (2026, B252): closeTexture keeps the texture
// alive until the engine has unregistered it, and for good unless "recycle"
// says that nothing pushes frames to its pointer any more.
#ifndef FLUTTER_PLUGIN_TEXTURE_RGBA_RENDERER_PLUGIN_H_
#define FLUTTER_PLUGIN_TEXTURE_RGBA_RENDERER_PLUGIN_H_
@ -31,6 +35,8 @@ class TextureRgbaRendererPlugin : public flutter::Plugin {
void HandleMethodCall(
const flutter::MethodCall<flutter::EncodableValue> &method_call,
std::unique_ptr<flutter::MethodResult<flutter::EncodableValue>> result);
void CloseTexture(std::unique_ptr<TextureRgba> texture, bool recycle);
};
} // namespace texture_rgba_renderer